diff --git a/.eslintrc.js b/.eslintrc.js index 9bd8e661237fd7..623c8f7bd2291d 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -8,9 +8,7 @@ NodePlugin.RULES_DIR = path.resolve(__dirname, 'tools', 'eslint-rules'); const ModuleFindPath = Module._findPath; const hacks = [ - 'eslint-plugin-node-core', - 'eslint-plugin-markdown', - 'babel-eslint', + 'eslint-plugin-node-core' ]; Module._findPath = (request, paths, isMain) => { const r = ModuleFindPath(request, paths, isMain); diff --git a/.gitignore b/.gitignore index dad5a3efd8bcae..43e3984290a801 100644 --- a/.gitignore +++ b/.gitignore @@ -135,3 +135,5 @@ deps/v8/gypfiles/Release/ deps/v8/third_party/eu-strip/ .DS_Store +tools/node_modules/* +node_modules/* diff --git a/Makefile b/Makefile index c3c9bdf6f765e4..50229bbe92ed3f 100644 --- a/Makefile +++ b/Makefile @@ -705,6 +705,7 @@ out/doc/api/assets/%: doc/api_assets/% out/doc/api/assets run-npm-ci = $(PWD)/$(NPM) ci +run-npm-task = $(PWD)/$(NPM) run LINK_DATA = out/doc/apilinks.json gen-api = tools/doc/generate.js --node-version=$(FULLVERSION) \ @@ -1172,8 +1173,7 @@ lint-md: | tools/.mdlintstamp LINT_JS_TARGETS = .eslintrc.js benchmark doc lib test tools -run-lint-js = tools/node_modules/eslint/bin/eslint.js --cache \ - --report-unused-disable-directives --ext=.js,.mjs,.md $(LINT_JS_TARGETS) +run-lint-js = $(call available-node,$(run-npm-ci)) && $(call available-node,$(run-npm-task) lint) run-lint-js-fix = $(run-lint-js) --fix .PHONY: lint-js-fix diff --git a/deps/acorn/acorn-walk/LICENSE b/deps/acorn/acorn-walk/LICENSE deleted file mode 100644 index 2c0632b6a7c63b..00000000000000 --- a/deps/acorn/acorn-walk/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (C) 2012-2018 by various contributors (see AUTHORS) - -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/deps/npm/node_modules/graceful-fs/LICENSE b/deps/npm/node_modules/graceful-fs/LICENSE deleted file mode 100644 index 9d2c8036969bed..00000000000000 --- a/deps/npm/node_modules/graceful-fs/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -The ISC License - -Copyright (c) Isaac Z. Schlueter, Ben Noordhuis, and Contributors - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR -IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/deps/npm/node_modules/graceful-fs/README.md b/deps/npm/node_modules/graceful-fs/README.md deleted file mode 100644 index 5273a50ad6a52c..00000000000000 --- a/deps/npm/node_modules/graceful-fs/README.md +++ /dev/null @@ -1,133 +0,0 @@ -# graceful-fs - -graceful-fs functions as a drop-in replacement for the fs module, -making various improvements. - -The improvements are meant to normalize behavior across different -platforms and environments, and to make filesystem access more -resilient to errors. - -## Improvements over [fs module](https://nodejs.org/api/fs.html) - -* Queues up `open` and `readdir` calls, and retries them once - something closes if there is an EMFILE error from too many file - descriptors. -* fixes `lchmod` for Node versions prior to 0.6.2. -* implements `fs.lutimes` if possible. Otherwise it becomes a noop. -* ignores `EINVAL` and `EPERM` errors in `chown`, `fchown` or - `lchown` if the user isn't root. -* makes `lchmod` and `lchown` become noops, if not available. -* retries reading a file if `read` results in EAGAIN error. - -On Windows, it retries renaming a file for up to one second if `EACCESS` -or `EPERM` error occurs, likely because antivirus software has locked -the directory. - -## USAGE - -```javascript -// use just like fs -var fs = require('graceful-fs') - -// now go and do stuff with it... -fs.readFileSync('some-file-or-whatever') -``` - -## Global Patching - -If you want to patch the global fs module (or any other fs-like -module) you can do this: - -```javascript -// Make sure to read the caveat below. -var realFs = require('fs') -var gracefulFs = require('graceful-fs') -gracefulFs.gracefulify(realFs) -``` - -This should only ever be done at the top-level application layer, in -order to delay on EMFILE errors from any fs-using dependencies. You -should **not** do this in a library, because it can cause unexpected -delays in other parts of the program. - -## Changes - -This module is fairly stable at this point, and used by a lot of -things. That being said, because it implements a subtle behavior -change in a core part of the node API, even modest changes can be -extremely breaking, and the versioning is thus biased towards -bumping the major when in doubt. - -The main change between major versions has been switching between -providing a fully-patched `fs` module vs monkey-patching the node core -builtin, and the approach by which a non-monkey-patched `fs` was -created. - -The goal is to trade `EMFILE` errors for slower fs operations. So, if -you try to open a zillion files, rather than crashing, `open` -operations will be queued up and wait for something else to `close`. - -There are advantages to each approach. Monkey-patching the fs means -that no `EMFILE` errors can possibly occur anywhere in your -application, because everything is using the same core `fs` module, -which is patched. However, it can also obviously cause undesirable -side-effects, especially if the module is loaded multiple times. - -Implementing a separate-but-identical patched `fs` module is more -surgical (and doesn't run the risk of patching multiple times), but -also imposes the challenge of keeping in sync with the core module. - -The current approach loads the `fs` module, and then creates a -lookalike object that has all the same methods, except a few that are -patched. It is safe to use in all versions of Node from 0.8 through -7.0. - -### v4 - -* Do not monkey-patch the fs module. This module may now be used as a - drop-in dep, and users can opt into monkey-patching the fs builtin - if their app requires it. - -### v3 - -* Monkey-patch fs, because the eval approach no longer works on recent - node. -* fixed possible type-error throw if rename fails on windows -* verify that we *never* get EMFILE errors -* Ignore ENOSYS from chmod/chown -* clarify that graceful-fs must be used as a drop-in - -### v2.1.0 - -* Use eval rather than monkey-patching fs. -* readdir: Always sort the results -* win32: requeue a file if error has an OK status - -### v2.0 - -* A return to monkey patching -* wrap process.cwd - -### v1.1 - -* wrap readFile -* Wrap fs.writeFile. -* readdir protection -* Don't clobber the fs builtin -* Handle fs.read EAGAIN errors by trying again -* Expose the curOpen counter -* No-op lchown/lchmod if not implemented -* fs.rename patch only for win32 -* Patch fs.rename to handle AV software on Windows -* Close #4 Chown should not fail on einval or eperm if non-root -* Fix isaacs/fstream#1 Only wrap fs one time -* Fix #3 Start at 1024 max files, then back off on EMFILE -* lutimes that doens't blow up on Linux -* A full on-rewrite using a queue instead of just swallowing the EMFILE error -* Wrap Read/Write streams as well - -### 1.0 - -* Update engines for node 0.6 -* Be lstat-graceful on Windows -* first diff --git a/deps/npm/node_modules/graceful-fs/clone.js b/deps/npm/node_modules/graceful-fs/clone.js deleted file mode 100644 index 028356c96ed536..00000000000000 --- a/deps/npm/node_modules/graceful-fs/clone.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict' - -module.exports = clone - -function clone (obj) { - if (obj === null || typeof obj !== 'object') - return obj - - if (obj instanceof Object) - var copy = { __proto__: obj.__proto__ } - else - var copy = Object.create(null) - - Object.getOwnPropertyNames(obj).forEach(function (key) { - Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) - }) - - return copy -} diff --git a/deps/npm/node_modules/graceful-fs/graceful-fs.js b/deps/npm/node_modules/graceful-fs/graceful-fs.js deleted file mode 100644 index ac206757e63c5a..00000000000000 --- a/deps/npm/node_modules/graceful-fs/graceful-fs.js +++ /dev/null @@ -1,279 +0,0 @@ -var fs = require('fs') -var polyfills = require('./polyfills.js') -var legacy = require('./legacy-streams.js') -var clone = require('./clone.js') - -var queue = [] - -var util = require('util') - -function noop () {} - -var debug = noop -if (util.debuglog) - debug = util.debuglog('gfs4') -else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) - debug = function() { - var m = util.format.apply(util, arguments) - m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ') - console.error(m) - } - -if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { - process.on('exit', function() { - debug(queue) - require('assert').equal(queue.length, 0) - }) -} - -module.exports = patch(clone(fs)) -if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) { - module.exports = patch(fs) - fs.__patched = true; -} - -// Always patch fs.close/closeSync, because we want to -// retry() whenever a close happens *anywhere* in the program. -// This is essential when multiple graceful-fs instances are -// in play at the same time. -module.exports.close = (function (fs$close) { return function (fd, cb) { - return fs$close.call(fs, fd, function (err) { - if (!err) - retry() - - if (typeof cb === 'function') - cb.apply(this, arguments) - }) -}})(fs.close) - -module.exports.closeSync = (function (fs$closeSync) { return function (fd) { - // Note that graceful-fs also retries when fs.closeSync() fails. - // Looks like a bug to me, although it's probably a harmless one. - var rval = fs$closeSync.apply(fs, arguments) - retry() - return rval -}})(fs.closeSync) - -// Only patch fs once, otherwise we'll run into a memory leak if -// graceful-fs is loaded multiple times, such as in test environments that -// reset the loaded modules between tests. -// We look for the string `graceful-fs` from the comment above. This -// way we are not adding any extra properties and it will detect if older -// versions of graceful-fs are installed. -if (!/\bgraceful-fs\b/.test(fs.closeSync.toString())) { - fs.closeSync = module.exports.closeSync; - fs.close = module.exports.close; -} - -function patch (fs) { - // Everything that references the open() function needs to be in here - polyfills(fs) - fs.gracefulify = patch - fs.FileReadStream = ReadStream; // Legacy name. - fs.FileWriteStream = WriteStream; // Legacy name. - fs.createReadStream = createReadStream - fs.createWriteStream = createWriteStream - var fs$readFile = fs.readFile - fs.readFile = readFile - function readFile (path, options, cb) { - if (typeof options === 'function') - cb = options, options = null - - return go$readFile(path, options, cb) - - function go$readFile (path, options, cb) { - return fs$readFile(path, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$readFile, [path, options, cb]]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() - } - }) - } - } - - var fs$writeFile = fs.writeFile - fs.writeFile = writeFile - function writeFile (path, data, options, cb) { - if (typeof options === 'function') - cb = options, options = null - - return go$writeFile(path, data, options, cb) - - function go$writeFile (path, data, options, cb) { - return fs$writeFile(path, data, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$writeFile, [path, data, options, cb]]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() - } - }) - } - } - - var fs$appendFile = fs.appendFile - if (fs$appendFile) - fs.appendFile = appendFile - function appendFile (path, data, options, cb) { - if (typeof options === 'function') - cb = options, options = null - - return go$appendFile(path, data, options, cb) - - function go$appendFile (path, data, options, cb) { - return fs$appendFile(path, data, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$appendFile, [path, data, options, cb]]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() - } - }) - } - } - - var fs$readdir = fs.readdir - fs.readdir = readdir - function readdir (path, options, cb) { - var args = [path] - if (typeof options !== 'function') { - args.push(options) - } else { - cb = options - } - args.push(go$readdir$cb) - - return go$readdir(args) - - function go$readdir$cb (err, files) { - if (files && files.sort) - files.sort() - - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$readdir, [args]]) - - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() - } - } - } - - function go$readdir (args) { - return fs$readdir.apply(fs, args) - } - - if (process.version.substr(0, 4) === 'v0.8') { - var legStreams = legacy(fs) - ReadStream = legStreams.ReadStream - WriteStream = legStreams.WriteStream - } - - var fs$ReadStream = fs.ReadStream - if (fs$ReadStream) { - ReadStream.prototype = Object.create(fs$ReadStream.prototype) - ReadStream.prototype.open = ReadStream$open - } - - var fs$WriteStream = fs.WriteStream - if (fs$WriteStream) { - WriteStream.prototype = Object.create(fs$WriteStream.prototype) - WriteStream.prototype.open = WriteStream$open - } - - fs.ReadStream = ReadStream - fs.WriteStream = WriteStream - - function ReadStream (path, options) { - if (this instanceof ReadStream) - return fs$ReadStream.apply(this, arguments), this - else - return ReadStream.apply(Object.create(ReadStream.prototype), arguments) - } - - function ReadStream$open () { - var that = this - open(that.path, that.flags, that.mode, function (err, fd) { - if (err) { - if (that.autoClose) - that.destroy() - - that.emit('error', err) - } else { - that.fd = fd - that.emit('open', fd) - that.read() - } - }) - } - - function WriteStream (path, options) { - if (this instanceof WriteStream) - return fs$WriteStream.apply(this, arguments), this - else - return WriteStream.apply(Object.create(WriteStream.prototype), arguments) - } - - function WriteStream$open () { - var that = this - open(that.path, that.flags, that.mode, function (err, fd) { - if (err) { - that.destroy() - that.emit('error', err) - } else { - that.fd = fd - that.emit('open', fd) - } - }) - } - - function createReadStream (path, options) { - return new ReadStream(path, options) - } - - function createWriteStream (path, options) { - return new WriteStream(path, options) - } - - var fs$open = fs.open - fs.open = open - function open (path, flags, mode, cb) { - if (typeof mode === 'function') - cb = mode, mode = null - - return go$open(path, flags, mode, cb) - - function go$open (path, flags, mode, cb) { - return fs$open(path, flags, mode, function (err, fd) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$open, [path, flags, mode, cb]]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() - } - }) - } - } - - return fs -} - -function enqueue (elem) { - debug('ENQUEUE', elem[0].name, elem[1]) - queue.push(elem) -} - -function retry () { - var elem = queue.shift() - if (elem) { - debug('RETRY', elem[0].name, elem[1]) - elem[0].apply(null, elem[1]) - } -} diff --git a/deps/npm/node_modules/graceful-fs/legacy-streams.js b/deps/npm/node_modules/graceful-fs/legacy-streams.js deleted file mode 100644 index d617b50fc0832d..00000000000000 --- a/deps/npm/node_modules/graceful-fs/legacy-streams.js +++ /dev/null @@ -1,118 +0,0 @@ -var Stream = require('stream').Stream - -module.exports = legacy - -function legacy (fs) { - return { - ReadStream: ReadStream, - WriteStream: WriteStream - } - - function ReadStream (path, options) { - if (!(this instanceof ReadStream)) return new ReadStream(path, options); - - Stream.call(this); - - var self = this; - - this.path = path; - this.fd = null; - this.readable = true; - this.paused = false; - - this.flags = 'r'; - this.mode = 438; /*=0666*/ - this.bufferSize = 64 * 1024; - - options = options || {}; - - // Mixin options into this - var keys = Object.keys(options); - for (var index = 0, length = keys.length; index < length; index++) { - var key = keys[index]; - this[key] = options[key]; - } - - if (this.encoding) this.setEncoding(this.encoding); - - if (this.start !== undefined) { - if ('number' !== typeof this.start) { - throw TypeError('start must be a Number'); - } - if (this.end === undefined) { - this.end = Infinity; - } else if ('number' !== typeof this.end) { - throw TypeError('end must be a Number'); - } - - if (this.start > this.end) { - throw new Error('start must be <= end'); - } - - this.pos = this.start; - } - - if (this.fd !== null) { - process.nextTick(function() { - self._read(); - }); - return; - } - - fs.open(this.path, this.flags, this.mode, function (err, fd) { - if (err) { - self.emit('error', err); - self.readable = false; - return; - } - - self.fd = fd; - self.emit('open', fd); - self._read(); - }) - } - - function WriteStream (path, options) { - if (!(this instanceof WriteStream)) return new WriteStream(path, options); - - Stream.call(this); - - this.path = path; - this.fd = null; - this.writable = true; - - this.flags = 'w'; - this.encoding = 'binary'; - this.mode = 438; /*=0666*/ - this.bytesWritten = 0; - - options = options || {}; - - // Mixin options into this - var keys = Object.keys(options); - for (var index = 0, length = keys.length; index < length; index++) { - var key = keys[index]; - this[key] = options[key]; - } - - if (this.start !== undefined) { - if ('number' !== typeof this.start) { - throw TypeError('start must be a Number'); - } - if (this.start < 0) { - throw new Error('start must be >= zero'); - } - - this.pos = this.start; - } - - this.busy = false; - this._queue = []; - - if (this.fd === null) { - this._open = fs.open; - this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); - this.flush(); - } - } -} diff --git a/deps/npm/node_modules/graceful-fs/polyfills.js b/deps/npm/node_modules/graceful-fs/polyfills.js deleted file mode 100644 index b964ed0806ceeb..00000000000000 --- a/deps/npm/node_modules/graceful-fs/polyfills.js +++ /dev/null @@ -1,329 +0,0 @@ -var constants = require('constants') - -var origCwd = process.cwd -var cwd = null - -var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform - -process.cwd = function() { - if (!cwd) - cwd = origCwd.call(process) - return cwd -} -try { - process.cwd() -} catch (er) {} - -var chdir = process.chdir -process.chdir = function(d) { - cwd = null - chdir.call(process, d) -} - -module.exports = patch - -function patch (fs) { - // (re-)implement some things that are known busted or missing. - - // lchmod, broken prior to 0.6.2 - // back-port the fix here. - if (constants.hasOwnProperty('O_SYMLINK') && - process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { - patchLchmod(fs) - } - - // lutimes implementation, or no-op - if (!fs.lutimes) { - patchLutimes(fs) - } - - // https://github.com/isaacs/node-graceful-fs/issues/4 - // Chown should not fail on einval or eperm if non-root. - // It should not fail on enosys ever, as this just indicates - // that a fs doesn't support the intended operation. - - fs.chown = chownFix(fs.chown) - fs.fchown = chownFix(fs.fchown) - fs.lchown = chownFix(fs.lchown) - - fs.chmod = chmodFix(fs.chmod) - fs.fchmod = chmodFix(fs.fchmod) - fs.lchmod = chmodFix(fs.lchmod) - - fs.chownSync = chownFixSync(fs.chownSync) - fs.fchownSync = chownFixSync(fs.fchownSync) - fs.lchownSync = chownFixSync(fs.lchownSync) - - fs.chmodSync = chmodFixSync(fs.chmodSync) - fs.fchmodSync = chmodFixSync(fs.fchmodSync) - fs.lchmodSync = chmodFixSync(fs.lchmodSync) - - fs.stat = statFix(fs.stat) - fs.fstat = statFix(fs.fstat) - fs.lstat = statFix(fs.lstat) - - fs.statSync = statFixSync(fs.statSync) - fs.fstatSync = statFixSync(fs.fstatSync) - fs.lstatSync = statFixSync(fs.lstatSync) - - // if lchmod/lchown do not exist, then make them no-ops - if (!fs.lchmod) { - fs.lchmod = function (path, mode, cb) { - if (cb) process.nextTick(cb) - } - fs.lchmodSync = function () {} - } - if (!fs.lchown) { - fs.lchown = function (path, uid, gid, cb) { - if (cb) process.nextTick(cb) - } - fs.lchownSync = function () {} - } - - // on Windows, A/V software can lock the directory, causing this - // to fail with an EACCES or EPERM if the directory contains newly - // created files. Try again on failure, for up to 60 seconds. - - // Set the timeout this long because some Windows Anti-Virus, such as Parity - // bit9, may lock files for up to a minute, causing npm package install - // failures. Also, take care to yield the scheduler. Windows scheduling gives - // CPU to a busy looping process, which can cause the program causing the lock - // contention to be starved of CPU by node, so the contention doesn't resolve. - if (platform === "win32") { - fs.rename = (function (fs$rename) { return function (from, to, cb) { - var start = Date.now() - var backoff = 0; - fs$rename(from, to, function CB (er) { - if (er - && (er.code === "EACCES" || er.code === "EPERM") - && Date.now() - start < 60000) { - setTimeout(function() { - fs.stat(to, function (stater, st) { - if (stater && stater.code === "ENOENT") - fs$rename(from, to, CB); - else - cb(er) - }) - }, backoff) - if (backoff < 100) - backoff += 10; - return; - } - if (cb) cb(er) - }) - }})(fs.rename) - } - - // if read() returns EAGAIN, then just try it again. - fs.read = (function (fs$read) { return function (fd, buffer, offset, length, position, callback_) { - var callback - if (callback_ && typeof callback_ === 'function') { - var eagCounter = 0 - callback = function (er, _, __) { - if (er && er.code === 'EAGAIN' && eagCounter < 10) { - eagCounter ++ - return fs$read.call(fs, fd, buffer, offset, length, position, callback) - } - callback_.apply(this, arguments) - } - } - return fs$read.call(fs, fd, buffer, offset, length, position, callback) - }})(fs.read) - - fs.readSync = (function (fs$readSync) { return function (fd, buffer, offset, length, position) { - var eagCounter = 0 - while (true) { - try { - return fs$readSync.call(fs, fd, buffer, offset, length, position) - } catch (er) { - if (er.code === 'EAGAIN' && eagCounter < 10) { - eagCounter ++ - continue - } - throw er - } - } - }})(fs.readSync) - - function patchLchmod (fs) { - fs.lchmod = function (path, mode, callback) { - fs.open( path - , constants.O_WRONLY | constants.O_SYMLINK - , mode - , function (err, fd) { - if (err) { - if (callback) callback(err) - return - } - // prefer to return the chmod error, if one occurs, - // but still try to close, and report closing errors if they occur. - fs.fchmod(fd, mode, function (err) { - fs.close(fd, function(err2) { - if (callback) callback(err || err2) - }) - }) - }) - } - - fs.lchmodSync = function (path, mode) { - var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) - - // prefer to return the chmod error, if one occurs, - // but still try to close, and report closing errors if they occur. - var threw = true - var ret - try { - ret = fs.fchmodSync(fd, mode) - threw = false - } finally { - if (threw) { - try { - fs.closeSync(fd) - } catch (er) {} - } else { - fs.closeSync(fd) - } - } - return ret - } - } - - function patchLutimes (fs) { - if (constants.hasOwnProperty("O_SYMLINK")) { - fs.lutimes = function (path, at, mt, cb) { - fs.open(path, constants.O_SYMLINK, function (er, fd) { - if (er) { - if (cb) cb(er) - return - } - fs.futimes(fd, at, mt, function (er) { - fs.close(fd, function (er2) { - if (cb) cb(er || er2) - }) - }) - }) - } - - fs.lutimesSync = function (path, at, mt) { - var fd = fs.openSync(path, constants.O_SYMLINK) - var ret - var threw = true - try { - ret = fs.futimesSync(fd, at, mt) - threw = false - } finally { - if (threw) { - try { - fs.closeSync(fd) - } catch (er) {} - } else { - fs.closeSync(fd) - } - } - return ret - } - - } else { - fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } - fs.lutimesSync = function () {} - } - } - - function chmodFix (orig) { - if (!orig) return orig - return function (target, mode, cb) { - return orig.call(fs, target, mode, function (er) { - if (chownErOk(er)) er = null - if (cb) cb.apply(this, arguments) - }) - } - } - - function chmodFixSync (orig) { - if (!orig) return orig - return function (target, mode) { - try { - return orig.call(fs, target, mode) - } catch (er) { - if (!chownErOk(er)) throw er - } - } - } - - - function chownFix (orig) { - if (!orig) return orig - return function (target, uid, gid, cb) { - return orig.call(fs, target, uid, gid, function (er) { - if (chownErOk(er)) er = null - if (cb) cb.apply(this, arguments) - }) - } - } - - function chownFixSync (orig) { - if (!orig) return orig - return function (target, uid, gid) { - try { - return orig.call(fs, target, uid, gid) - } catch (er) { - if (!chownErOk(er)) throw er - } - } - } - - - function statFix (orig) { - if (!orig) return orig - // Older versions of Node erroneously returned signed integers for - // uid + gid. - return function (target, cb) { - return orig.call(fs, target, function (er, stats) { - if (!stats) return cb.apply(this, arguments) - if (stats.uid < 0) stats.uid += 0x100000000 - if (stats.gid < 0) stats.gid += 0x100000000 - if (cb) cb.apply(this, arguments) - }) - } - } - - function statFixSync (orig) { - if (!orig) return orig - // Older versions of Node erroneously returned signed integers for - // uid + gid. - return function (target) { - var stats = orig.call(fs, target) - if (stats.uid < 0) stats.uid += 0x100000000 - if (stats.gid < 0) stats.gid += 0x100000000 - return stats; - } - } - - // ENOSYS means that the fs doesn't support the op. Just ignore - // that, because it doesn't matter. - // - // if there's no getuid, or if getuid() is something other - // than 0, and the error is EINVAL or EPERM, then just ignore - // it. - // - // This specific case is a silent failure in cp, install, tar, - // and most other unix tools that manage permissions. - // - // When running as root, or if other types of errors are - // encountered, then it's strict. - function chownErOk (er) { - if (!er) - return true - - if (er.code === "ENOSYS") - return true - - var nonroot = !process.getuid || process.getuid() !== 0 - if (nonroot) { - if (er.code === "EINVAL" || er.code === "EPERM") - return true - } - - return false - } -} diff --git a/package.json b/package.json new file mode 100644 index 00000000000000..530a14b715d1e6 --- /dev/null +++ b/package.json @@ -0,0 +1,17 @@ +{ + "name": "node-core", + "author": "The Amazing Node.js Contributors", + "version": "1.0.0", + "description": "Base tools to help manage node core", + "license": "MIT", + "scripts": { + "lint": "eslint --cache --report-unused-disable-directives --ext=.js,.mjs,.md .eslintrc.js benchmark doc lib test tools" + }, + "dependencies": { + "babel-eslint": "8.2.1", + "eslint": "5.14.1", + "eslint-plugin-markdown": "1.0.0", + "glob": "7.1.3", + "js-yaml": "3.12.1" + } +} diff --git a/tools/doc/common.js b/tools/doc/common.js index 86daae6cfc6d56..8a5f33731f8335 100644 --- a/tools/doc/common.js +++ b/tools/doc/common.js @@ -1,7 +1,6 @@ 'use strict'; -const yaml = - require(`${__dirname}/../node_modules/eslint/node_modules/js-yaml`); +const yaml = require(`js-yaml`); function isYAMLBlock(text) { return /^ - -### anyTypeAnnotation -```javascript -t.anyTypeAnnotation() -``` - -See also `t.isAnyTypeAnnotation(node, opts)` and `t.assertAnyTypeAnnotation(node, opts)`. - -Aliases: `Flow`, `FlowBaseAnnotation` - - ---- - -### arrayExpression -```javascript -t.arrayExpression(elements) -``` - -See also `t.isArrayExpression(node, opts)` and `t.assertArrayExpression(node, opts)`. - -Aliases: `Expression` - - - `elements`: `Array` (default: `[]`) - ---- - -### arrayPattern -```javascript -t.arrayPattern(elements) -``` - -See also `t.isArrayPattern(node, opts)` and `t.assertArrayPattern(node, opts)`. - -Aliases: `Pattern`, `PatternLike`, `LVal` - - - `elements`: `Array` (required) - - `decorators`: `Array` (default: `null`) - - `typeAnnotation`: `TypeAnnotation | TSTypeAnnotation | Noop` (default: `null`) - ---- - -### arrayTypeAnnotation -```javascript -t.arrayTypeAnnotation(elementType) -``` - -See also `t.isArrayTypeAnnotation(node, opts)` and `t.assertArrayTypeAnnotation(node, opts)`. - -Aliases: `Flow` - - - `elementType` (required) - ---- - -### arrowFunctionExpression -```javascript -t.arrowFunctionExpression(params, body, async) -``` - -See also `t.isArrowFunctionExpression(node, opts)` and `t.assertArrowFunctionExpression(node, opts)`. - -Aliases: `Scopable`, `Function`, `BlockParent`, `FunctionParent`, `Expression`, `Pureish` - - - `params`: `Array` (required) - - `body`: `BlockStatement | Expression` (required) - - `async`: `boolean` (default: `false`) - - `expression`: `boolean` (default: `null`) - - `generator`: `boolean` (default: `false`) - - `returnType`: `TypeAnnotation | TSTypeAnnotation | Noop` (default: `null`) - - `typeParameters`: `TypeParameterDeclaration | TSTypeParameterDeclaration | Noop` (default: `null`) - ---- - -### assignmentExpression -```javascript -t.assignmentExpression(operator, left, right) -``` - -See also `t.isAssignmentExpression(node, opts)` and `t.assertAssignmentExpression(node, opts)`. - -Aliases: `Expression` - - - `operator`: `string` (required) - - `left`: `LVal` (required) - - `right`: `Expression` (required) - ---- - -### assignmentPattern -```javascript -t.assignmentPattern(left, right) -``` - -See also `t.isAssignmentPattern(node, opts)` and `t.assertAssignmentPattern(node, opts)`. - -Aliases: `Pattern`, `PatternLike`, `LVal` - - - `left`: `Identifier | ObjectPattern | ArrayPattern` (required) - - `right`: `Expression` (required) - - `decorators`: `Array` (default: `null`) - - `typeAnnotation`: `TypeAnnotation | TSTypeAnnotation | Noop` (default: `null`) - ---- - -### awaitExpression -```javascript -t.awaitExpression(argument) -``` - -See also `t.isAwaitExpression(node, opts)` and `t.assertAwaitExpression(node, opts)`. - -Aliases: `Expression`, `Terminatorless` - - - `argument`: `Expression` (required) - ---- - -### binaryExpression -```javascript -t.binaryExpression(operator, left, right) -``` - -See also `t.isBinaryExpression(node, opts)` and `t.assertBinaryExpression(node, opts)`. - -Aliases: `Binary`, `Expression` - - - `operator`: `'+' | '-' | '/' | '%' | '*' | '**' | '&' | '|' | '>>' | '>>>' | '<<' | '^' | '==' | '===' | '!=' | '!==' | 'in' | 'instanceof' | '>' | '<' | '>=' | '<='` (required) - - `left`: `Expression` (required) - - `right`: `Expression` (required) - ---- - -### bindExpression -```javascript -t.bindExpression(object, callee) -``` - -See also `t.isBindExpression(node, opts)` and `t.assertBindExpression(node, opts)`. - -Aliases: `Expression` - - - `object` (required) - - `callee` (required) - ---- - -### blockStatement -```javascript -t.blockStatement(body, directives) -``` - -See also `t.isBlockStatement(node, opts)` and `t.assertBlockStatement(node, opts)`. - -Aliases: `Scopable`, `BlockParent`, `Block`, `Statement` - - - `body`: `Array` (required) - - `directives`: `Array` (default: `[]`) - ---- - -### booleanLiteral -```javascript -t.booleanLiteral(value) -``` - -See also `t.isBooleanLiteral(node, opts)` and `t.assertBooleanLiteral(node, opts)`. - -Aliases: `Expression`, `Pureish`, `Literal`, `Immutable` - - - `value`: `boolean` (required) - ---- - -### booleanLiteralTypeAnnotation -```javascript -t.booleanLiteralTypeAnnotation() -``` - -See also `t.isBooleanLiteralTypeAnnotation(node, opts)` and `t.assertBooleanLiteralTypeAnnotation(node, opts)`. - -Aliases: `Flow` - - ---- - -### booleanTypeAnnotation -```javascript -t.booleanTypeAnnotation() -``` - -See also `t.isBooleanTypeAnnotation(node, opts)` and `t.assertBooleanTypeAnnotation(node, opts)`. - -Aliases: `Flow`, `FlowBaseAnnotation` - - ---- - -### breakStatement -```javascript -t.breakStatement(label) -``` - -See also `t.isBreakStatement(node, opts)` and `t.assertBreakStatement(node, opts)`. - -Aliases: `Statement`, `Terminatorless`, `CompletionStatement` - - - `label`: `Identifier` (default: `null`) - ---- - -### callExpression -```javascript -t.callExpression(callee, arguments) -``` - -See also `t.isCallExpression(node, opts)` and `t.assertCallExpression(node, opts)`. - -Aliases: `Expression` - - - `callee`: `Expression` (required) - - `arguments`: `Array` (required) - - `optional`: `true | false` (default: `null`) - - `typeParameters`: `TypeParameterInstantiation | TSTypeParameterInstantiation` (default: `null`) - ---- - -### catchClause -```javascript -t.catchClause(param, body) -``` - -See also `t.isCatchClause(node, opts)` and `t.assertCatchClause(node, opts)`. - -Aliases: `Scopable`, `BlockParent` - - - `param`: `Identifier` (default: `null`) - - `body`: `BlockStatement` (required) - ---- - -### classBody -```javascript -t.classBody(body) -``` - -See also `t.isClassBody(node, opts)` and `t.assertClassBody(node, opts)`. - - - `body`: `Array` (required) - ---- - -### classDeclaration -```javascript -t.classDeclaration(id, superClass, body, decorators) -``` - -See also `t.isClassDeclaration(node, opts)` and `t.assertClassDeclaration(node, opts)`. - -Aliases: `Scopable`, `Class`, `Statement`, `Declaration`, `Pureish` - - - `id`: `Identifier` (default: `null`) - - `superClass`: `Expression` (default: `null`) - - `body`: `ClassBody` (required) - - `decorators`: `Array` (default: `null`) - - `abstract`: `boolean` (default: `null`) - - `declare`: `boolean` (default: `null`) - - `implements`: `Array` (default: `null`) - - `mixins` (default: `null`) - - `superTypeParameters`: `TypeParameterInstantiation | TSTypeParameterInstantiation` (default: `null`) - - `typeParameters`: `TypeParameterDeclaration | TSTypeParameterDeclaration | Noop` (default: `null`) - ---- - -### classExpression -```javascript -t.classExpression(id, superClass, body, decorators) -``` - -See also `t.isClassExpression(node, opts)` and `t.assertClassExpression(node, opts)`. - -Aliases: `Scopable`, `Class`, `Expression`, `Pureish` - - - `id`: `Identifier` (default: `null`) - - `superClass`: `Expression` (default: `null`) - - `body`: `ClassBody` (required) - - `decorators`: `Array` (default: `null`) - - `implements`: `Array` (default: `null`) - - `mixins` (default: `null`) - - `superTypeParameters`: `TypeParameterInstantiation | TSTypeParameterInstantiation` (default: `null`) - - `typeParameters`: `TypeParameterDeclaration | TSTypeParameterDeclaration | Noop` (default: `null`) - ---- - -### classImplements -```javascript -t.classImplements(id, typeParameters) -``` - -See also `t.isClassImplements(node, opts)` and `t.assertClassImplements(node, opts)`. - -Aliases: `Flow` - - - `id` (required) - - `typeParameters` (required) - ---- - -### classMethod -```javascript -t.classMethod(kind, key, params, body, computed, static) -``` - -See also `t.isClassMethod(node, opts)` and `t.assertClassMethod(node, opts)`. - -Aliases: `Function`, `Scopable`, `BlockParent`, `FunctionParent`, `Method` - - - `kind`: `"get" | "set" | "method" | "constructor"` (default: `'method'`) - - `key`: if computed then `Expression` else `Identifier | Literal` (required) - - `params`: `Array` (required) - - `body`: `BlockStatement` (required) - - `computed`: `boolean` (default: `false`) - - `static`: `boolean` (default: `null`) - - `abstract`: `boolean` (default: `null`) - - `access`: `"public" | "private" | "protected"` (default: `null`) - - `accessibility`: `"public" | "private" | "protected"` (default: `null`) - - `async`: `boolean` (default: `false`) - - `decorators`: `Array` (default: `null`) - - `generator`: `boolean` (default: `false`) - - `optional`: `boolean` (default: `null`) - - `returnType`: `TypeAnnotation | TSTypeAnnotation | Noop` (default: `null`) - - `typeParameters`: `TypeParameterDeclaration | TSTypeParameterDeclaration | Noop` (default: `null`) - ---- - -### classProperty -```javascript -t.classProperty(key, value, typeAnnotation, decorators, computed) -``` - -See also `t.isClassProperty(node, opts)` and `t.assertClassProperty(node, opts)`. - -Aliases: `Property` - - - `key` (required) - - `value`: `Expression` (default: `null`) - - `typeAnnotation`: `TypeAnnotation | TSTypeAnnotation | Noop` (default: `null`) - - `decorators`: `Array` (default: `null`) - - `computed`: `boolean` (default: `false`) - - `abstract`: `boolean` (default: `null`) - - `accessibility`: `"public" | "private" | "protected"` (default: `null`) - - `optional`: `boolean` (default: `null`) - - `readonly`: `boolean` (default: `null`) - - `static`: `boolean` (default: `null`) - ---- - -### conditionalExpression -```javascript -t.conditionalExpression(test, consequent, alternate) -``` - -See also `t.isConditionalExpression(node, opts)` and `t.assertConditionalExpression(node, opts)`. - -Aliases: `Expression`, `Conditional` - - - `test`: `Expression` (required) - - `consequent`: `Expression` (required) - - `alternate`: `Expression` (required) - ---- - -### continueStatement -```javascript -t.continueStatement(label) -``` - -See also `t.isContinueStatement(node, opts)` and `t.assertContinueStatement(node, opts)`. - -Aliases: `Statement`, `Terminatorless`, `CompletionStatement` - - - `label`: `Identifier` (default: `null`) - ---- - -### debuggerStatement -```javascript -t.debuggerStatement() -``` - -See also `t.isDebuggerStatement(node, opts)` and `t.assertDebuggerStatement(node, opts)`. - -Aliases: `Statement` - - ---- - -### declareClass -```javascript -t.declareClass(id, typeParameters, extends, body) -``` - -See also `t.isDeclareClass(node, opts)` and `t.assertDeclareClass(node, opts)`. - -Aliases: `Flow`, `FlowDeclaration`, `Statement`, `Declaration` - - - `id` (required) - - `typeParameters` (required) - - `extends` (required) - - `body` (required) - ---- - -### declareExportAllDeclaration -```javascript -t.declareExportAllDeclaration(source) -``` - -See also `t.isDeclareExportAllDeclaration(node, opts)` and `t.assertDeclareExportAllDeclaration(node, opts)`. - -Aliases: `Flow`, `FlowDeclaration`, `Statement`, `Declaration` - - - `source` (required) - ---- - -### declareExportDeclaration -```javascript -t.declareExportDeclaration(declaration, specifiers, source) -``` - -See also `t.isDeclareExportDeclaration(node, opts)` and `t.assertDeclareExportDeclaration(node, opts)`. - -Aliases: `Flow`, `FlowDeclaration`, `Statement`, `Declaration` - - - `declaration` (required) - - `specifiers` (required) - - `source` (required) - ---- - -### declareFunction -```javascript -t.declareFunction(id) -``` - -See also `t.isDeclareFunction(node, opts)` and `t.assertDeclareFunction(node, opts)`. - -Aliases: `Flow`, `FlowDeclaration`, `Statement`, `Declaration` - - - `id` (required) - ---- - -### declareInterface -```javascript -t.declareInterface(id, typeParameters, extends, body) -``` - -See also `t.isDeclareInterface(node, opts)` and `t.assertDeclareInterface(node, opts)`. - -Aliases: `Flow`, `FlowDeclaration`, `Statement`, `Declaration` - - - `id` (required) - - `typeParameters` (required) - - `extends` (required) - - `body` (required) - ---- - -### declareModule -```javascript -t.declareModule(id, body) -``` - -See also `t.isDeclareModule(node, opts)` and `t.assertDeclareModule(node, opts)`. - -Aliases: `Flow`, `FlowDeclaration`, `Statement`, `Declaration` - - - `id` (required) - - `body` (required) - ---- - -### declareModuleExports -```javascript -t.declareModuleExports(typeAnnotation) -``` - -See also `t.isDeclareModuleExports(node, opts)` and `t.assertDeclareModuleExports(node, opts)`. - -Aliases: `Flow`, `FlowDeclaration`, `Statement`, `Declaration` - - - `typeAnnotation` (required) - ---- - -### declareOpaqueType -```javascript -t.declareOpaqueType(id, typeParameters, supertype) -``` - -See also `t.isDeclareOpaqueType(node, opts)` and `t.assertDeclareOpaqueType(node, opts)`. - -Aliases: `Flow`, `FlowDeclaration`, `Statement`, `Declaration` - - - `id` (required) - - `typeParameters` (required) - - `supertype` (required) - ---- - -### declareTypeAlias -```javascript -t.declareTypeAlias(id, typeParameters, right) -``` - -See also `t.isDeclareTypeAlias(node, opts)` and `t.assertDeclareTypeAlias(node, opts)`. - -Aliases: `Flow`, `FlowDeclaration`, `Statement`, `Declaration` - - - `id` (required) - - `typeParameters` (required) - - `right` (required) - ---- - -### declareVariable -```javascript -t.declareVariable(id) -``` - -See also `t.isDeclareVariable(node, opts)` and `t.assertDeclareVariable(node, opts)`. - -Aliases: `Flow`, `FlowDeclaration`, `Statement`, `Declaration` - - - `id` (required) - ---- - -### declaredPredicate -```javascript -t.declaredPredicate(value) -``` - -See also `t.isDeclaredPredicate(node, opts)` and `t.assertDeclaredPredicate(node, opts)`. - -Aliases: `Flow`, `FlowPredicate` - - - `value` (required) - ---- - -### decorator -```javascript -t.decorator(expression) -``` - -See also `t.isDecorator(node, opts)` and `t.assertDecorator(node, opts)`. - - - `expression`: `Expression` (required) - ---- - -### directive -```javascript -t.directive(value) -``` - -See also `t.isDirective(node, opts)` and `t.assertDirective(node, opts)`. - - - `value`: `DirectiveLiteral` (required) - ---- - -### directiveLiteral -```javascript -t.directiveLiteral(value) -``` - -See also `t.isDirectiveLiteral(node, opts)` and `t.assertDirectiveLiteral(node, opts)`. - - - `value`: `string` (required) - ---- - -### doExpression -```javascript -t.doExpression(body) -``` - -See also `t.isDoExpression(node, opts)` and `t.assertDoExpression(node, opts)`. - -Aliases: `Expression` - - - `body`: `BlockStatement` (required) - ---- - -### doWhileStatement -```javascript -t.doWhileStatement(test, body) -``` - -See also `t.isDoWhileStatement(node, opts)` and `t.assertDoWhileStatement(node, opts)`. - -Aliases: `Statement`, `BlockParent`, `Loop`, `While`, `Scopable` - - - `test`: `Expression` (required) - - `body`: `Statement` (required) - ---- - -### emptyStatement -```javascript -t.emptyStatement() -``` - -See also `t.isEmptyStatement(node, opts)` and `t.assertEmptyStatement(node, opts)`. - -Aliases: `Statement` - - ---- - -### emptyTypeAnnotation -```javascript -t.emptyTypeAnnotation() -``` - -See also `t.isEmptyTypeAnnotation(node, opts)` and `t.assertEmptyTypeAnnotation(node, opts)`. - -Aliases: `Flow`, `FlowBaseAnnotation` - - ---- - -### existsTypeAnnotation -```javascript -t.existsTypeAnnotation() -``` - -See also `t.isExistsTypeAnnotation(node, opts)` and `t.assertExistsTypeAnnotation(node, opts)`. - -Aliases: `Flow` - - ---- - -### exportAllDeclaration -```javascript -t.exportAllDeclaration(source) -``` - -See also `t.isExportAllDeclaration(node, opts)` and `t.assertExportAllDeclaration(node, opts)`. - -Aliases: `Statement`, `Declaration`, `ModuleDeclaration`, `ExportDeclaration` - - - `source`: `StringLiteral` (required) - ---- - -### exportDefaultDeclaration -```javascript -t.exportDefaultDeclaration(declaration) -``` - -See also `t.isExportDefaultDeclaration(node, opts)` and `t.assertExportDefaultDeclaration(node, opts)`. - -Aliases: `Statement`, `Declaration`, `ModuleDeclaration`, `ExportDeclaration` - - - `declaration`: `FunctionDeclaration | TSDeclareFunction | ClassDeclaration | Expression` (required) - ---- - -### exportDefaultSpecifier -```javascript -t.exportDefaultSpecifier(exported) -``` - -See also `t.isExportDefaultSpecifier(node, opts)` and `t.assertExportDefaultSpecifier(node, opts)`. - -Aliases: `ModuleSpecifier` - - - `exported`: `Identifier` (required) - ---- - -### exportNamedDeclaration -```javascript -t.exportNamedDeclaration(declaration, specifiers, source) -``` - -See also `t.isExportNamedDeclaration(node, opts)` and `t.assertExportNamedDeclaration(node, opts)`. - -Aliases: `Statement`, `Declaration`, `ModuleDeclaration`, `ExportDeclaration` - - - `declaration`: `Declaration` (default: `null`) - - `specifiers`: `Array` (required) - - `source`: `StringLiteral` (default: `null`) - ---- - -### exportNamespaceSpecifier -```javascript -t.exportNamespaceSpecifier(exported) -``` - -See also `t.isExportNamespaceSpecifier(node, opts)` and `t.assertExportNamespaceSpecifier(node, opts)`. - -Aliases: `ModuleSpecifier` - - - `exported`: `Identifier` (required) - ---- - -### exportSpecifier -```javascript -t.exportSpecifier(local, exported) -``` - -See also `t.isExportSpecifier(node, opts)` and `t.assertExportSpecifier(node, opts)`. - -Aliases: `ModuleSpecifier` - - - `local`: `Identifier` (required) - - `exported`: `Identifier` (required) - ---- - -### expressionStatement -```javascript -t.expressionStatement(expression) -``` - -See also `t.isExpressionStatement(node, opts)` and `t.assertExpressionStatement(node, opts)`. - -Aliases: `Statement`, `ExpressionWrapper` - - - `expression`: `Expression` (required) - ---- - -### file -```javascript -t.file(program, comments, tokens) -``` - -See also `t.isFile(node, opts)` and `t.assertFile(node, opts)`. - - - `program`: `Program` (required) - - `comments` (required) - - `tokens` (required) - ---- - -### forInStatement -```javascript -t.forInStatement(left, right, body) -``` - -See also `t.isForInStatement(node, opts)` and `t.assertForInStatement(node, opts)`. - -Aliases: `Scopable`, `Statement`, `For`, `BlockParent`, `Loop`, `ForXStatement` - - - `left`: `VariableDeclaration | LVal` (required) - - `right`: `Expression` (required) - - `body`: `Statement` (required) - ---- - -### forOfStatement -```javascript -t.forOfStatement(left, right, body) -``` - -See also `t.isForOfStatement(node, opts)` and `t.assertForOfStatement(node, opts)`. - -Aliases: `Scopable`, `Statement`, `For`, `BlockParent`, `Loop`, `ForXStatement` - - - `left`: `VariableDeclaration | LVal` (required) - - `right`: `Expression` (required) - - `body`: `Statement` (required) - - `await`: `boolean` (default: `false`) - ---- - -### forStatement -```javascript -t.forStatement(init, test, update, body) -``` - -See also `t.isForStatement(node, opts)` and `t.assertForStatement(node, opts)`. - -Aliases: `Scopable`, `Statement`, `For`, `BlockParent`, `Loop` - - - `init`: `VariableDeclaration | Expression` (default: `null`) - - `test`: `Expression` (default: `null`) - - `update`: `Expression` (default: `null`) - - `body`: `Statement` (required) - ---- - -### functionDeclaration -```javascript -t.functionDeclaration(id, params, body, generator, async) -``` - -See also `t.isFunctionDeclaration(node, opts)` and `t.assertFunctionDeclaration(node, opts)`. - -Aliases: `Scopable`, `Function`, `BlockParent`, `FunctionParent`, `Statement`, `Pureish`, `Declaration` - - - `id`: `Identifier` (default: `null`) - - `params`: `Array` (required) - - `body`: `BlockStatement` (required) - - `generator`: `boolean` (default: `false`) - - `async`: `boolean` (default: `false`) - - `declare`: `boolean` (default: `null`) - - `returnType`: `TypeAnnotation | TSTypeAnnotation | Noop` (default: `null`) - - `typeParameters`: `TypeParameterDeclaration | TSTypeParameterDeclaration | Noop` (default: `null`) - ---- - -### functionExpression -```javascript -t.functionExpression(id, params, body, generator, async) -``` - -See also `t.isFunctionExpression(node, opts)` and `t.assertFunctionExpression(node, opts)`. - -Aliases: `Scopable`, `Function`, `BlockParent`, `FunctionParent`, `Expression`, `Pureish` - - - `id`: `Identifier` (default: `null`) - - `params`: `Array` (required) - - `body`: `BlockStatement` (required) - - `generator`: `boolean` (default: `false`) - - `async`: `boolean` (default: `false`) - - `returnType`: `TypeAnnotation | TSTypeAnnotation | Noop` (default: `null`) - - `typeParameters`: `TypeParameterDeclaration | TSTypeParameterDeclaration | Noop` (default: `null`) - ---- - -### functionTypeAnnotation -```javascript -t.functionTypeAnnotation(typeParameters, params, rest, returnType) -``` - -See also `t.isFunctionTypeAnnotation(node, opts)` and `t.assertFunctionTypeAnnotation(node, opts)`. - -Aliases: `Flow` - - - `typeParameters` (required) - - `params` (required) - - `rest` (required) - - `returnType` (required) - ---- - -### functionTypeParam -```javascript -t.functionTypeParam(name, typeAnnotation) -``` - -See also `t.isFunctionTypeParam(node, opts)` and `t.assertFunctionTypeParam(node, opts)`. - -Aliases: `Flow` - - - `name` (required) - - `typeAnnotation` (required) - ---- - -### genericTypeAnnotation -```javascript -t.genericTypeAnnotation(id, typeParameters) -``` - -See also `t.isGenericTypeAnnotation(node, opts)` and `t.assertGenericTypeAnnotation(node, opts)`. - -Aliases: `Flow` - - - `id` (required) - - `typeParameters` (required) - ---- - -### identifier -```javascript -t.identifier(name) -``` - -See also `t.isIdentifier(node, opts)` and `t.assertIdentifier(node, opts)`. - -Aliases: `Expression`, `PatternLike`, `LVal`, `TSEntityName` - - - `name`: `string` (required) - - `decorators`: `Array` (default: `null`) - - `optional`: `boolean` (default: `null`) - - `typeAnnotation`: `TypeAnnotation | TSTypeAnnotation | Noop` (default: `null`) - ---- - -### ifStatement -```javascript -t.ifStatement(test, consequent, alternate) -``` - -See also `t.isIfStatement(node, opts)` and `t.assertIfStatement(node, opts)`. - -Aliases: `Statement`, `Conditional` - - - `test`: `Expression` (required) - - `consequent`: `Statement` (required) - - `alternate`: `Statement` (default: `null`) - ---- - -### import -```javascript -t.import() -``` - -See also `t.isImport(node, opts)` and `t.assertImport(node, opts)`. - -Aliases: `Expression` - - ---- - -### importDeclaration -```javascript -t.importDeclaration(specifiers, source) -``` - -See also `t.isImportDeclaration(node, opts)` and `t.assertImportDeclaration(node, opts)`. - -Aliases: `Statement`, `Declaration`, `ModuleDeclaration` - - - `specifiers`: `Array` (required) - - `source`: `StringLiteral` (required) - ---- - -### importDefaultSpecifier -```javascript -t.importDefaultSpecifier(local) -``` - -See also `t.isImportDefaultSpecifier(node, opts)` and `t.assertImportDefaultSpecifier(node, opts)`. - -Aliases: `ModuleSpecifier` - - - `local`: `Identifier` (required) - ---- - -### importNamespaceSpecifier -```javascript -t.importNamespaceSpecifier(local) -``` - -See also `t.isImportNamespaceSpecifier(node, opts)` and `t.assertImportNamespaceSpecifier(node, opts)`. - -Aliases: `ModuleSpecifier` - - - `local`: `Identifier` (required) - ---- - -### importSpecifier -```javascript -t.importSpecifier(local, imported) -``` - -See also `t.isImportSpecifier(node, opts)` and `t.assertImportSpecifier(node, opts)`. - -Aliases: `ModuleSpecifier` - - - `local`: `Identifier` (required) - - `imported`: `Identifier` (required) - - `importKind`: `null | 'type' | 'typeof'` (default: `null`) - ---- - -### inferredPredicate -```javascript -t.inferredPredicate() -``` - -See also `t.isInferredPredicate(node, opts)` and `t.assertInferredPredicate(node, opts)`. - -Aliases: `Flow`, `FlowPredicate` - - ---- - -### interfaceDeclaration -```javascript -t.interfaceDeclaration(id, typeParameters, extends, body) -``` - -See also `t.isInterfaceDeclaration(node, opts)` and `t.assertInterfaceDeclaration(node, opts)`. - -Aliases: `Flow`, `FlowDeclaration`, `Statement`, `Declaration` - - - `id` (required) - - `typeParameters` (required) - - `extends` (required) - - `body` (required) - ---- - -### interfaceExtends -```javascript -t.interfaceExtends(id, typeParameters) -``` - -See also `t.isInterfaceExtends(node, opts)` and `t.assertInterfaceExtends(node, opts)`. - -Aliases: `Flow` - - - `id` (required) - - `typeParameters` (required) - ---- - -### intersectionTypeAnnotation -```javascript -t.intersectionTypeAnnotation(types) -``` - -See also `t.isIntersectionTypeAnnotation(node, opts)` and `t.assertIntersectionTypeAnnotation(node, opts)`. - -Aliases: `Flow` - - - `types` (required) - ---- - -### jSXAttribute -```javascript -t.jSXAttribute(name, value) -``` - -See also `t.isJSXAttribute(node, opts)` and `t.assertJSXAttribute(node, opts)`. - -Aliases: `JSX`, `Immutable` - - - `name`: `JSXIdentifier | JSXNamespacedName` (required) - - `value`: `JSXElement | JSXFragment | StringLiteral | JSXExpressionContainer` (default: `null`) - ---- - -### jSXClosingElement -```javascript -t.jSXClosingElement(name) -``` - -See also `t.isJSXClosingElement(node, opts)` and `t.assertJSXClosingElement(node, opts)`. - -Aliases: `JSX`, `Immutable` - - - `name`: `JSXIdentifier | JSXMemberExpression` (required) - ---- - -### jSXClosingFragment -```javascript -t.jSXClosingFragment() -``` - -See also `t.isJSXClosingFragment(node, opts)` and `t.assertJSXClosingFragment(node, opts)`. - -Aliases: `JSX`, `Immutable` - - ---- - -### jSXElement -```javascript -t.jSXElement(openingElement, closingElement, children, selfClosing) -``` - -See also `t.isJSXElement(node, opts)` and `t.assertJSXElement(node, opts)`. - -Aliases: `JSX`, `Immutable`, `Expression` - - - `openingElement`: `JSXOpeningElement` (required) - - `closingElement`: `JSXClosingElement` (default: `null`) - - `children`: `Array` (required) - - `selfClosing` (required) - ---- - -### jSXEmptyExpression -```javascript -t.jSXEmptyExpression() -``` - -See also `t.isJSXEmptyExpression(node, opts)` and `t.assertJSXEmptyExpression(node, opts)`. - -Aliases: `JSX` - - ---- - -### jSXExpressionContainer -```javascript -t.jSXExpressionContainer(expression) -``` - -See also `t.isJSXExpressionContainer(node, opts)` and `t.assertJSXExpressionContainer(node, opts)`. - -Aliases: `JSX`, `Immutable` - - - `expression`: `Expression` (required) - ---- - -### jSXFragment -```javascript -t.jSXFragment(openingFragment, closingFragment, children) -``` - -See also `t.isJSXFragment(node, opts)` and `t.assertJSXFragment(node, opts)`. - -Aliases: `JSX`, `Immutable`, `Expression` - - - `openingFragment`: `JSXOpeningFragment` (required) - - `closingFragment`: `JSXClosingFragment` (required) - - `children`: `Array` (required) - ---- - -### jSXIdentifier -```javascript -t.jSXIdentifier(name) -``` - -See also `t.isJSXIdentifier(node, opts)` and `t.assertJSXIdentifier(node, opts)`. - -Aliases: `JSX` - - - `name`: `string` (required) - ---- - -### jSXMemberExpression -```javascript -t.jSXMemberExpression(object, property) -``` - -See also `t.isJSXMemberExpression(node, opts)` and `t.assertJSXMemberExpression(node, opts)`. - -Aliases: `JSX` - - - `object`: `JSXMemberExpression | JSXIdentifier` (required) - - `property`: `JSXIdentifier` (required) - ---- - -### jSXNamespacedName -```javascript -t.jSXNamespacedName(namespace, name) -``` - -See also `t.isJSXNamespacedName(node, opts)` and `t.assertJSXNamespacedName(node, opts)`. - -Aliases: `JSX` - - - `namespace`: `JSXIdentifier` (required) - - `name`: `JSXIdentifier` (required) - ---- - -### jSXOpeningElement -```javascript -t.jSXOpeningElement(name, attributes, selfClosing) -``` - -See also `t.isJSXOpeningElement(node, opts)` and `t.assertJSXOpeningElement(node, opts)`. - -Aliases: `JSX`, `Immutable` - - - `name`: `JSXIdentifier | JSXMemberExpression` (required) - - `attributes`: `Array` (required) - - `selfClosing`: `boolean` (default: `false`) - ---- - -### jSXOpeningFragment -```javascript -t.jSXOpeningFragment() -``` - -See also `t.isJSXOpeningFragment(node, opts)` and `t.assertJSXOpeningFragment(node, opts)`. - -Aliases: `JSX`, `Immutable` - - ---- - -### jSXSpreadAttribute -```javascript -t.jSXSpreadAttribute(argument) -``` - -See also `t.isJSXSpreadAttribute(node, opts)` and `t.assertJSXSpreadAttribute(node, opts)`. - -Aliases: `JSX` - - - `argument`: `Expression` (required) - ---- - -### jSXSpreadChild -```javascript -t.jSXSpreadChild(expression) -``` - -See also `t.isJSXSpreadChild(node, opts)` and `t.assertJSXSpreadChild(node, opts)`. - -Aliases: `JSX`, `Immutable` - - - `expression`: `Expression` (required) - ---- - -### jSXText -```javascript -t.jSXText(value) -``` - -See also `t.isJSXText(node, opts)` and `t.assertJSXText(node, opts)`. - -Aliases: `JSX`, `Immutable` - - - `value`: `string` (required) - ---- - -### labeledStatement -```javascript -t.labeledStatement(label, body) -``` - -See also `t.isLabeledStatement(node, opts)` and `t.assertLabeledStatement(node, opts)`. - -Aliases: `Statement` - - - `label`: `Identifier` (required) - - `body`: `Statement` (required) - ---- - -### logicalExpression -```javascript -t.logicalExpression(operator, left, right) -``` - -See also `t.isLogicalExpression(node, opts)` and `t.assertLogicalExpression(node, opts)`. - -Aliases: `Binary`, `Expression` - - - `operator`: `'||' | '&&' | '??'` (required) - - `left`: `Expression` (required) - - `right`: `Expression` (required) - ---- - -### memberExpression -```javascript -t.memberExpression(object, property, computed, optional) -``` - -See also `t.isMemberExpression(node, opts)` and `t.assertMemberExpression(node, opts)`. - -Aliases: `Expression`, `LVal` - - - `object`: `Expression` (required) - - `property`: if computed then `Expression` else `Identifier` (required) - - `computed`: `boolean` (default: `false`) - - `optional`: `true | false` (default: `null`) - ---- - -### metaProperty -```javascript -t.metaProperty(meta, property) -``` - -See also `t.isMetaProperty(node, opts)` and `t.assertMetaProperty(node, opts)`. - -Aliases: `Expression` - - - `meta`: `Identifier` (required) - - `property`: `Identifier` (required) - ---- - -### mixedTypeAnnotation -```javascript -t.mixedTypeAnnotation() -``` - -See also `t.isMixedTypeAnnotation(node, opts)` and `t.assertMixedTypeAnnotation(node, opts)`. - -Aliases: `Flow`, `FlowBaseAnnotation` - - ---- - -### newExpression -```javascript -t.newExpression(callee, arguments) -``` - -See also `t.isNewExpression(node, opts)` and `t.assertNewExpression(node, opts)`. - -Aliases: `Expression` - - - `callee`: `Expression` (required) - - `arguments`: `Array` (required) - - `optional`: `true | false` (default: `null`) - - `typeParameters`: `TypeParameterInstantiation | TSTypeParameterInstantiation` (default: `null`) - ---- - -### noop -```javascript -t.noop() -``` - -See also `t.isNoop(node, opts)` and `t.assertNoop(node, opts)`. - - ---- - -### nullLiteral -```javascript -t.nullLiteral() -``` - -See also `t.isNullLiteral(node, opts)` and `t.assertNullLiteral(node, opts)`. - -Aliases: `Expression`, `Pureish`, `Literal`, `Immutable` - - ---- - -### nullLiteralTypeAnnotation -```javascript -t.nullLiteralTypeAnnotation() -``` - -See also `t.isNullLiteralTypeAnnotation(node, opts)` and `t.assertNullLiteralTypeAnnotation(node, opts)`. - -Aliases: `Flow`, `FlowBaseAnnotation` - - ---- - -### nullableTypeAnnotation -```javascript -t.nullableTypeAnnotation(typeAnnotation) -``` - -See also `t.isNullableTypeAnnotation(node, opts)` and `t.assertNullableTypeAnnotation(node, opts)`. - -Aliases: `Flow` - - - `typeAnnotation` (required) - ---- - -### numberLiteralTypeAnnotation -```javascript -t.numberLiteralTypeAnnotation() -``` - -See also `t.isNumberLiteralTypeAnnotation(node, opts)` and `t.assertNumberLiteralTypeAnnotation(node, opts)`. - -Aliases: `Flow` - - ---- - -### numberTypeAnnotation -```javascript -t.numberTypeAnnotation() -``` - -See also `t.isNumberTypeAnnotation(node, opts)` and `t.assertNumberTypeAnnotation(node, opts)`. - -Aliases: `Flow`, `FlowBaseAnnotation` - - ---- - -### numericLiteral -```javascript -t.numericLiteral(value) -``` - -See also `t.isNumericLiteral(node, opts)` and `t.assertNumericLiteral(node, opts)`. - -Aliases: `Expression`, `Pureish`, `Literal`, `Immutable` - - - `value`: `number` (required) - ---- - -### objectExpression -```javascript -t.objectExpression(properties) -``` - -See also `t.isObjectExpression(node, opts)` and `t.assertObjectExpression(node, opts)`. - -Aliases: `Expression` - - - `properties`: `Array` (required) - ---- - -### objectMethod -```javascript -t.objectMethod(kind, key, params, body, computed) -``` - -See also `t.isObjectMethod(node, opts)` and `t.assertObjectMethod(node, opts)`. - -Aliases: `UserWhitespacable`, `Function`, `Scopable`, `BlockParent`, `FunctionParent`, `Method`, `ObjectMember` - - - `kind`: `"method" | "get" | "set"` (default: `'method'`) - - `key`: if computed then `Expression` else `Identifier | Literal` (required) - - `params`: `Array` (required) - - `body`: `BlockStatement` (required) - - `computed`: `boolean` (default: `false`) - - `async`: `boolean` (default: `false`) - - `decorators`: `Array` (default: `null`) - - `generator`: `boolean` (default: `false`) - - `returnType`: `TypeAnnotation | TSTypeAnnotation | Noop` (default: `null`) - - `typeParameters`: `TypeParameterDeclaration | TSTypeParameterDeclaration | Noop` (default: `null`) - ---- - -### objectPattern -```javascript -t.objectPattern(properties) -``` - -See also `t.isObjectPattern(node, opts)` and `t.assertObjectPattern(node, opts)`. - -Aliases: `Pattern`, `PatternLike`, `LVal` - - - `properties`: `Array` (required) - - `decorators`: `Array` (default: `null`) - - `typeAnnotation`: `TypeAnnotation | TSTypeAnnotation | Noop` (default: `null`) - ---- - -### objectProperty -```javascript -t.objectProperty(key, value, computed, shorthand, decorators) -``` - -See also `t.isObjectProperty(node, opts)` and `t.assertObjectProperty(node, opts)`. - -Aliases: `UserWhitespacable`, `Property`, `ObjectMember` - - - `key`: if computed then `Expression` else `Identifier | Literal` (required) - - `value`: `Expression | PatternLike` (required) - - `computed`: `boolean` (default: `false`) - - `shorthand`: `boolean` (default: `false`) - - `decorators`: `Array` (default: `null`) - ---- - -### objectTypeAnnotation -```javascript -t.objectTypeAnnotation(properties, indexers, callProperties) -``` - -See also `t.isObjectTypeAnnotation(node, opts)` and `t.assertObjectTypeAnnotation(node, opts)`. - -Aliases: `Flow` - - - `properties` (required) - - `indexers` (required) - - `callProperties` (required) - ---- - -### objectTypeCallProperty -```javascript -t.objectTypeCallProperty(value) -``` - -See also `t.isObjectTypeCallProperty(node, opts)` and `t.assertObjectTypeCallProperty(node, opts)`. - -Aliases: `Flow`, `UserWhitespacable` - - - `value` (required) - ---- - -### objectTypeIndexer -```javascript -t.objectTypeIndexer(id, key, value) -``` - -See also `t.isObjectTypeIndexer(node, opts)` and `t.assertObjectTypeIndexer(node, opts)`. - -Aliases: `Flow`, `UserWhitespacable` - - - `id` (required) - - `key` (required) - - `value` (required) - ---- - -### objectTypeProperty -```javascript -t.objectTypeProperty(key, value) -``` - -See also `t.isObjectTypeProperty(node, opts)` and `t.assertObjectTypeProperty(node, opts)`. - -Aliases: `Flow`, `UserWhitespacable` - - - `key` (required) - - `value` (required) - ---- - -### objectTypeSpreadProperty -```javascript -t.objectTypeSpreadProperty(argument) -``` - -See also `t.isObjectTypeSpreadProperty(node, opts)` and `t.assertObjectTypeSpreadProperty(node, opts)`. - -Aliases: `Flow`, `UserWhitespacable` - - - `argument` (required) - ---- - -### opaqueType -```javascript -t.opaqueType(id, typeParameters, supertype, impltype) -``` - -See also `t.isOpaqueType(node, opts)` and `t.assertOpaqueType(node, opts)`. - -Aliases: `Flow`, `FlowDeclaration`, `Statement`, `Declaration` - - - `id` (required) - - `typeParameters` (required) - - `supertype` (required) - - `impltype` (required) - ---- - -### parenthesizedExpression -```javascript -t.parenthesizedExpression(expression) -``` - -See also `t.isParenthesizedExpression(node, opts)` and `t.assertParenthesizedExpression(node, opts)`. - -Aliases: `Expression`, `ExpressionWrapper` - - - `expression`: `Expression` (required) - ---- - -### program -```javascript -t.program(body, directives, sourceType) -``` - -See also `t.isProgram(node, opts)` and `t.assertProgram(node, opts)`. - -Aliases: `Scopable`, `BlockParent`, `Block` - - - `body`: `Array` (required) - - `directives`: `Array` (default: `[]`) - - `sourceType`: `'script' | 'module'` (default: `'script'`) - - `sourceFile`: `string` (default: `null`) - ---- - -### qualifiedTypeIdentifier -```javascript -t.qualifiedTypeIdentifier(id, qualification) -``` - -See also `t.isQualifiedTypeIdentifier(node, opts)` and `t.assertQualifiedTypeIdentifier(node, opts)`. - -Aliases: `Flow` - - - `id` (required) - - `qualification` (required) - ---- - -### regExpLiteral -```javascript -t.regExpLiteral(pattern, flags) -``` - -See also `t.isRegExpLiteral(node, opts)` and `t.assertRegExpLiteral(node, opts)`. - -Aliases: `Expression`, `Literal` - - - `pattern`: `string` (required) - - `flags`: `string` (default: `''`) - ---- - -### restElement -```javascript -t.restElement(argument) -``` - -See also `t.isRestElement(node, opts)` and `t.assertRestElement(node, opts)`. - -Aliases: `LVal`, `PatternLike` - - - `argument`: `LVal` (required) - - `decorators`: `Array` (default: `null`) - - `typeAnnotation`: `TypeAnnotation | TSTypeAnnotation | Noop` (default: `null`) - ---- - -### returnStatement -```javascript -t.returnStatement(argument) -``` - -See also `t.isReturnStatement(node, opts)` and `t.assertReturnStatement(node, opts)`. - -Aliases: `Statement`, `Terminatorless`, `CompletionStatement` - - - `argument`: `Expression` (default: `null`) - ---- - -### sequenceExpression -```javascript -t.sequenceExpression(expressions) -``` - -See also `t.isSequenceExpression(node, opts)` and `t.assertSequenceExpression(node, opts)`. - -Aliases: `Expression` - - - `expressions`: `Array` (required) - ---- - -### spreadElement -```javascript -t.spreadElement(argument) -``` - -See also `t.isSpreadElement(node, opts)` and `t.assertSpreadElement(node, opts)`. - -Aliases: `UnaryLike` - - - `argument`: `Expression` (required) - ---- - -### stringLiteral -```javascript -t.stringLiteral(value) -``` - -See also `t.isStringLiteral(node, opts)` and `t.assertStringLiteral(node, opts)`. - -Aliases: `Expression`, `Pureish`, `Literal`, `Immutable` - - - `value`: `string` (required) - ---- - -### stringLiteralTypeAnnotation -```javascript -t.stringLiteralTypeAnnotation() -``` - -See also `t.isStringLiteralTypeAnnotation(node, opts)` and `t.assertStringLiteralTypeAnnotation(node, opts)`. - -Aliases: `Flow` - - ---- - -### stringTypeAnnotation -```javascript -t.stringTypeAnnotation() -``` - -See also `t.isStringTypeAnnotation(node, opts)` and `t.assertStringTypeAnnotation(node, opts)`. - -Aliases: `Flow`, `FlowBaseAnnotation` - - ---- - -### super -```javascript -t.super() -``` - -See also `t.isSuper(node, opts)` and `t.assertSuper(node, opts)`. - -Aliases: `Expression` - - ---- - -### switchCase -```javascript -t.switchCase(test, consequent) -``` - -See also `t.isSwitchCase(node, opts)` and `t.assertSwitchCase(node, opts)`. - - - `test`: `Expression` (default: `null`) - - `consequent`: `Array` (required) - ---- - -### switchStatement -```javascript -t.switchStatement(discriminant, cases) -``` - -See also `t.isSwitchStatement(node, opts)` and `t.assertSwitchStatement(node, opts)`. - -Aliases: `Statement`, `BlockParent`, `Scopable` - - - `discriminant`: `Expression` (required) - - `cases`: `Array` (required) - ---- - -### tSAnyKeyword -```javascript -t.tSAnyKeyword() -``` - -See also `t.isTSAnyKeyword(node, opts)` and `t.assertTSAnyKeyword(node, opts)`. - -Aliases: `TSType` - - ---- - -### tSArrayType -```javascript -t.tSArrayType(elementType) -``` - -See also `t.isTSArrayType(node, opts)` and `t.assertTSArrayType(node, opts)`. - -Aliases: `TSType` - - - `elementType`: `TSType` (required) - ---- - -### tSAsExpression -```javascript -t.tSAsExpression(expression, typeAnnotation) -``` - -See also `t.isTSAsExpression(node, opts)` and `t.assertTSAsExpression(node, opts)`. - -Aliases: `Expression` - - - `expression`: `Expression` (required) - - `typeAnnotation`: `TSType` (required) - ---- - -### tSBooleanKeyword -```javascript -t.tSBooleanKeyword() -``` - -See also `t.isTSBooleanKeyword(node, opts)` and `t.assertTSBooleanKeyword(node, opts)`. - -Aliases: `TSType` - - ---- - -### tSCallSignatureDeclaration -```javascript -t.tSCallSignatureDeclaration(typeParameters, parameters, typeAnnotation) -``` - -See also `t.isTSCallSignatureDeclaration(node, opts)` and `t.assertTSCallSignatureDeclaration(node, opts)`. - -Aliases: `TSTypeElement` - - - `typeParameters`: `TSTypeParameterDeclaration` (default: `null`) - - `parameters`: `Array` (default: `null`) - - `typeAnnotation`: `TSTypeAnnotation` (default: `null`) - ---- - -### tSConstructSignatureDeclaration -```javascript -t.tSConstructSignatureDeclaration(typeParameters, parameters, typeAnnotation) -``` - -See also `t.isTSConstructSignatureDeclaration(node, opts)` and `t.assertTSConstructSignatureDeclaration(node, opts)`. - -Aliases: `TSTypeElement` - - - `typeParameters`: `TSTypeParameterDeclaration` (default: `null`) - - `parameters`: `Array` (default: `null`) - - `typeAnnotation`: `TSTypeAnnotation` (default: `null`) - ---- - -### tSConstructorType -```javascript -t.tSConstructorType(typeParameters, typeAnnotation) -``` - -See also `t.isTSConstructorType(node, opts)` and `t.assertTSConstructorType(node, opts)`. - -Aliases: `TSType` - - - `typeParameters`: `TSTypeParameterDeclaration` (default: `null`) - - `typeAnnotation`: `TSTypeAnnotation` (default: `null`) - - `parameters`: `Array` (default: `null`) - ---- - -### tSDeclareFunction -```javascript -t.tSDeclareFunction(id, typeParameters, params, returnType) -``` - -See also `t.isTSDeclareFunction(node, opts)` and `t.assertTSDeclareFunction(node, opts)`. - -Aliases: `Statement`, `Declaration` - - - `id`: `Identifier` (default: `null`) - - `typeParameters`: `TSTypeParameterDeclaration | Noop` (default: `null`) - - `params`: `Array` (required) - - `returnType`: `TSTypeAnnotation | Noop` (default: `null`) - - `async`: `boolean` (default: `false`) - - `declare`: `boolean` (default: `null`) - - `generator`: `boolean` (default: `false`) - ---- - -### tSDeclareMethod -```javascript -t.tSDeclareMethod(decorators, key, typeParameters, params, returnType) -``` - -See also `t.isTSDeclareMethod(node, opts)` and `t.assertTSDeclareMethod(node, opts)`. - - - `decorators`: `Array` (default: `null`) - - `key` (required) - - `typeParameters`: `TSTypeParameterDeclaration | Noop` (default: `null`) - - `params`: `Array` (required) - - `returnType`: `TSTypeAnnotation | Noop` (default: `null`) - - `abstract`: `boolean` (default: `null`) - - `access`: `"public" | "private" | "protected"` (default: `null`) - - `accessibility`: `"public" | "private" | "protected"` (default: `null`) - - `async`: `boolean` (default: `false`) - - `computed`: `boolean` (default: `false`) - - `generator`: `boolean` (default: `false`) - - `kind`: `"get" | "set" | "method" | "constructor"` (default: `'method'`) - - `optional`: `boolean` (default: `null`) - - `static`: `boolean` (default: `null`) - ---- - -### tSEnumDeclaration -```javascript -t.tSEnumDeclaration(id, members) -``` - -See also `t.isTSEnumDeclaration(node, opts)` and `t.assertTSEnumDeclaration(node, opts)`. - -Aliases: `Statement`, `Declaration` - - - `id`: `Identifier` (required) - - `members`: `Array` (required) - - `const`: `boolean` (default: `null`) - - `declare`: `boolean` (default: `null`) - - `initializer`: `Expression` (default: `null`) - ---- - -### tSEnumMember -```javascript -t.tSEnumMember(id, initializer) -``` - -See also `t.isTSEnumMember(node, opts)` and `t.assertTSEnumMember(node, opts)`. - - - `id`: `Identifier | StringLiteral` (required) - - `initializer`: `Expression` (default: `null`) - ---- - -### tSExportAssignment -```javascript -t.tSExportAssignment(expression) -``` - -See also `t.isTSExportAssignment(node, opts)` and `t.assertTSExportAssignment(node, opts)`. - -Aliases: `Statement` - - - `expression`: `Expression` (required) - ---- - -### tSExpressionWithTypeArguments -```javascript -t.tSExpressionWithTypeArguments(expression, typeParameters) -``` - -See also `t.isTSExpressionWithTypeArguments(node, opts)` and `t.assertTSExpressionWithTypeArguments(node, opts)`. - -Aliases: `TSType` - - - `expression`: `TSEntityName` (required) - - `typeParameters`: `TSTypeParameterInstantiation` (default: `null`) - ---- - -### tSExternalModuleReference -```javascript -t.tSExternalModuleReference(expression) -``` - -See also `t.isTSExternalModuleReference(node, opts)` and `t.assertTSExternalModuleReference(node, opts)`. - - - `expression`: `StringLiteral` (required) - ---- - -### tSFunctionType -```javascript -t.tSFunctionType(typeParameters, typeAnnotation) -``` - -See also `t.isTSFunctionType(node, opts)` and `t.assertTSFunctionType(node, opts)`. - -Aliases: `TSType` - - - `typeParameters`: `TSTypeParameterDeclaration` (default: `null`) - - `typeAnnotation`: `TSTypeAnnotation` (default: `null`) - - `parameters`: `Array` (default: `null`) - ---- - -### tSImportEqualsDeclaration -```javascript -t.tSImportEqualsDeclaration(id, moduleReference) -``` - -See also `t.isTSImportEqualsDeclaration(node, opts)` and `t.assertTSImportEqualsDeclaration(node, opts)`. - -Aliases: `Statement` - - - `id`: `Identifier` (required) - - `moduleReference`: `TSEntityName | TSExternalModuleReference` (required) - - `isExport`: `boolean` (default: `null`) - ---- - -### tSIndexSignature -```javascript -t.tSIndexSignature(parameters, typeAnnotation) -``` - -See also `t.isTSIndexSignature(node, opts)` and `t.assertTSIndexSignature(node, opts)`. - -Aliases: `TSTypeElement` - - - `parameters`: `Array` (required) - - `typeAnnotation`: `TSTypeAnnotation` (default: `null`) - - `readonly`: `boolean` (default: `null`) - ---- - -### tSIndexedAccessType -```javascript -t.tSIndexedAccessType(objectType, indexType) -``` - -See also `t.isTSIndexedAccessType(node, opts)` and `t.assertTSIndexedAccessType(node, opts)`. - -Aliases: `TSType` - - - `objectType`: `TSType` (required) - - `indexType`: `TSType` (required) - ---- - -### tSInterfaceBody -```javascript -t.tSInterfaceBody(body) -``` - -See also `t.isTSInterfaceBody(node, opts)` and `t.assertTSInterfaceBody(node, opts)`. - - - `body`: `Array` (required) - ---- - -### tSInterfaceDeclaration -```javascript -t.tSInterfaceDeclaration(id, typeParameters, extends, body) -``` - -See also `t.isTSInterfaceDeclaration(node, opts)` and `t.assertTSInterfaceDeclaration(node, opts)`. - -Aliases: `Statement`, `Declaration` - - - `id`: `Identifier` (required) - - `typeParameters`: `TSTypeParameterDeclaration` (default: `null`) - - `extends`: `Array` (default: `null`) - - `body`: `TSInterfaceBody` (required) - - `declare`: `boolean` (default: `null`) - ---- - -### tSIntersectionType -```javascript -t.tSIntersectionType(types) -``` - -See also `t.isTSIntersectionType(node, opts)` and `t.assertTSIntersectionType(node, opts)`. - -Aliases: `TSType` - - - `types`: `Array` (required) - ---- - -### tSLiteralType -```javascript -t.tSLiteralType(literal) -``` - -See also `t.isTSLiteralType(node, opts)` and `t.assertTSLiteralType(node, opts)`. - -Aliases: `TSType` - - - `literal`: `NumericLiteral | StringLiteral | BooleanLiteral` (required) - ---- - -### tSMappedType -```javascript -t.tSMappedType(typeParameter, typeAnnotation) -``` - -See also `t.isTSMappedType(node, opts)` and `t.assertTSMappedType(node, opts)`. - -Aliases: `TSType` - - - `typeParameter`: `TSTypeParameter` (required) - - `typeAnnotation`: `TSType` (default: `null`) - - `optional`: `boolean` (default: `null`) - - `readonly`: `boolean` (default: `null`) - ---- - -### tSMethodSignature -```javascript -t.tSMethodSignature(key, typeParameters, parameters, typeAnnotation) -``` - -See also `t.isTSMethodSignature(node, opts)` and `t.assertTSMethodSignature(node, opts)`. - -Aliases: `TSTypeElement` - - - `key`: `Expression` (required) - - `typeParameters`: `TSTypeParameterDeclaration` (default: `null`) - - `parameters`: `Array` (default: `null`) - - `typeAnnotation`: `TSTypeAnnotation` (default: `null`) - - `computed`: `boolean` (default: `null`) - - `optional`: `boolean` (default: `null`) - ---- - -### tSModuleBlock -```javascript -t.tSModuleBlock(body) -``` - -See also `t.isTSModuleBlock(node, opts)` and `t.assertTSModuleBlock(node, opts)`. - - - `body`: `Array` (required) - ---- - -### tSModuleDeclaration -```javascript -t.tSModuleDeclaration(id, body) -``` - -See also `t.isTSModuleDeclaration(node, opts)` and `t.assertTSModuleDeclaration(node, opts)`. - -Aliases: `Statement`, `Declaration` - - - `id`: `Identifier | StringLiteral` (required) - - `body`: `TSModuleBlock | TSModuleDeclaration` (required) - - `declare`: `boolean` (default: `null`) - - `global`: `boolean` (default: `null`) - ---- - -### tSNamespaceExportDeclaration -```javascript -t.tSNamespaceExportDeclaration(id) -``` - -See also `t.isTSNamespaceExportDeclaration(node, opts)` and `t.assertTSNamespaceExportDeclaration(node, opts)`. - -Aliases: `Statement` - - - `id`: `Identifier` (required) - ---- - -### tSNeverKeyword -```javascript -t.tSNeverKeyword() -``` - -See also `t.isTSNeverKeyword(node, opts)` and `t.assertTSNeverKeyword(node, opts)`. - -Aliases: `TSType` - - ---- - -### tSNonNullExpression -```javascript -t.tSNonNullExpression(expression) -``` - -See also `t.isTSNonNullExpression(node, opts)` and `t.assertTSNonNullExpression(node, opts)`. - -Aliases: `Expression` - - - `expression`: `Expression` (required) - ---- - -### tSNullKeyword -```javascript -t.tSNullKeyword() -``` - -See also `t.isTSNullKeyword(node, opts)` and `t.assertTSNullKeyword(node, opts)`. - -Aliases: `TSType` - - ---- - -### tSNumberKeyword -```javascript -t.tSNumberKeyword() -``` - -See also `t.isTSNumberKeyword(node, opts)` and `t.assertTSNumberKeyword(node, opts)`. - -Aliases: `TSType` - - ---- - -### tSObjectKeyword -```javascript -t.tSObjectKeyword() -``` - -See also `t.isTSObjectKeyword(node, opts)` and `t.assertTSObjectKeyword(node, opts)`. - -Aliases: `TSType` - - ---- - -### tSParameterProperty -```javascript -t.tSParameterProperty(parameter) -``` - -See also `t.isTSParameterProperty(node, opts)` and `t.assertTSParameterProperty(node, opts)`. - -Aliases: `LVal` - - - `parameter`: `Identifier | AssignmentPattern` (required) - - `accessibility`: `'public' | 'private' | 'protected'` (default: `null`) - - `readonly`: `boolean` (default: `null`) - ---- - -### tSParenthesizedType -```javascript -t.tSParenthesizedType(typeAnnotation) -``` - -See also `t.isTSParenthesizedType(node, opts)` and `t.assertTSParenthesizedType(node, opts)`. - -Aliases: `TSType` - - - `typeAnnotation`: `TSType` (required) - ---- - -### tSPropertySignature -```javascript -t.tSPropertySignature(key, typeAnnotation, initializer) -``` - -See also `t.isTSPropertySignature(node, opts)` and `t.assertTSPropertySignature(node, opts)`. - -Aliases: `TSTypeElement` - - - `key`: `Expression` (required) - - `typeAnnotation`: `TSTypeAnnotation` (default: `null`) - - `initializer`: `Expression` (default: `null`) - - `computed`: `boolean` (default: `null`) - - `optional`: `boolean` (default: `null`) - - `readonly`: `boolean` (default: `null`) - ---- - -### tSQualifiedName -```javascript -t.tSQualifiedName(left, right) -``` - -See also `t.isTSQualifiedName(node, opts)` and `t.assertTSQualifiedName(node, opts)`. - -Aliases: `TSEntityName` - - - `left`: `TSEntityName` (required) - - `right`: `Identifier` (required) - ---- - -### tSStringKeyword -```javascript -t.tSStringKeyword() -``` - -See also `t.isTSStringKeyword(node, opts)` and `t.assertTSStringKeyword(node, opts)`. - -Aliases: `TSType` - - ---- - -### tSSymbolKeyword -```javascript -t.tSSymbolKeyword() -``` - -See also `t.isTSSymbolKeyword(node, opts)` and `t.assertTSSymbolKeyword(node, opts)`. - -Aliases: `TSType` - - ---- - -### tSThisType -```javascript -t.tSThisType() -``` - -See also `t.isTSThisType(node, opts)` and `t.assertTSThisType(node, opts)`. - -Aliases: `TSType` - - ---- - -### tSTupleType -```javascript -t.tSTupleType(elementTypes) -``` - -See also `t.isTSTupleType(node, opts)` and `t.assertTSTupleType(node, opts)`. - -Aliases: `TSType` - - - `elementTypes`: `Array` (required) - ---- - -### tSTypeAliasDeclaration -```javascript -t.tSTypeAliasDeclaration(id, typeParameters, typeAnnotation) -``` - -See also `t.isTSTypeAliasDeclaration(node, opts)` and `t.assertTSTypeAliasDeclaration(node, opts)`. - -Aliases: `Statement`, `Declaration` - - - `id`: `Identifier` (required) - - `typeParameters`: `TSTypeParameterDeclaration` (default: `null`) - - `typeAnnotation`: `TSType` (required) - - `declare`: `boolean` (default: `null`) - ---- - -### tSTypeAnnotation -```javascript -t.tSTypeAnnotation(typeAnnotation) -``` - -See also `t.isTSTypeAnnotation(node, opts)` and `t.assertTSTypeAnnotation(node, opts)`. - - - `typeAnnotation`: `TSType` (required) - ---- - -### tSTypeAssertion -```javascript -t.tSTypeAssertion(typeAnnotation, expression) -``` - -See also `t.isTSTypeAssertion(node, opts)` and `t.assertTSTypeAssertion(node, opts)`. - -Aliases: `Expression` - - - `typeAnnotation`: `TSType` (required) - - `expression`: `Expression` (required) - ---- - -### tSTypeLiteral -```javascript -t.tSTypeLiteral(members) -``` - -See also `t.isTSTypeLiteral(node, opts)` and `t.assertTSTypeLiteral(node, opts)`. - -Aliases: `TSType` - - - `members`: `Array` (required) - ---- - -### tSTypeOperator -```javascript -t.tSTypeOperator(typeAnnotation) -``` - -See also `t.isTSTypeOperator(node, opts)` and `t.assertTSTypeOperator(node, opts)`. - -Aliases: `TSType` - - - `typeAnnotation`: `TSType` (required) - - `operator`: `string` (default: `null`) - ---- - -### tSTypeParameter -```javascript -t.tSTypeParameter(constraint, default) -``` - -See also `t.isTSTypeParameter(node, opts)` and `t.assertTSTypeParameter(node, opts)`. - - - `constraint`: `TSType` (default: `null`) - - `default`: `TSType` (default: `null`) - - `name`: `string` (default: `null`) - ---- - -### tSTypeParameterDeclaration -```javascript -t.tSTypeParameterDeclaration(params) -``` - -See also `t.isTSTypeParameterDeclaration(node, opts)` and `t.assertTSTypeParameterDeclaration(node, opts)`. - - - `params`: `Array` (required) - ---- - -### tSTypeParameterInstantiation -```javascript -t.tSTypeParameterInstantiation(params) -``` - -See also `t.isTSTypeParameterInstantiation(node, opts)` and `t.assertTSTypeParameterInstantiation(node, opts)`. - - - `params`: `Array` (required) - ---- - -### tSTypePredicate -```javascript -t.tSTypePredicate(parameterName, typeAnnotation) -``` - -See also `t.isTSTypePredicate(node, opts)` and `t.assertTSTypePredicate(node, opts)`. - -Aliases: `TSType` - - - `parameterName`: `Identifier | TSThisType` (required) - - `typeAnnotation`: `TSTypeAnnotation` (required) - ---- - -### tSTypeQuery -```javascript -t.tSTypeQuery(exprName) -``` - -See also `t.isTSTypeQuery(node, opts)` and `t.assertTSTypeQuery(node, opts)`. - -Aliases: `TSType` - - - `exprName`: `TSEntityName` (required) - ---- - -### tSTypeReference -```javascript -t.tSTypeReference(typeName, typeParameters) -``` - -See also `t.isTSTypeReference(node, opts)` and `t.assertTSTypeReference(node, opts)`. - -Aliases: `TSType` - - - `typeName`: `TSEntityName` (required) - - `typeParameters`: `TSTypeParameterInstantiation` (default: `null`) - ---- - -### tSUndefinedKeyword -```javascript -t.tSUndefinedKeyword() -``` - -See also `t.isTSUndefinedKeyword(node, opts)` and `t.assertTSUndefinedKeyword(node, opts)`. - -Aliases: `TSType` - - ---- - -### tSUnionType -```javascript -t.tSUnionType(types) -``` - -See also `t.isTSUnionType(node, opts)` and `t.assertTSUnionType(node, opts)`. - -Aliases: `TSType` - - - `types`: `Array` (required) - ---- - -### tSVoidKeyword -```javascript -t.tSVoidKeyword() -``` - -See also `t.isTSVoidKeyword(node, opts)` and `t.assertTSVoidKeyword(node, opts)`. - -Aliases: `TSType` - - ---- - -### taggedTemplateExpression -```javascript -t.taggedTemplateExpression(tag, quasi) -``` - -See also `t.isTaggedTemplateExpression(node, opts)` and `t.assertTaggedTemplateExpression(node, opts)`. - -Aliases: `Expression` - - - `tag`: `Expression` (required) - - `quasi`: `TemplateLiteral` (required) - ---- - -### templateElement -```javascript -t.templateElement(value, tail) -``` - -See also `t.isTemplateElement(node, opts)` and `t.assertTemplateElement(node, opts)`. - - - `value` (required) - - `tail`: `boolean` (default: `false`) - ---- - -### templateLiteral -```javascript -t.templateLiteral(quasis, expressions) -``` - -See also `t.isTemplateLiteral(node, opts)` and `t.assertTemplateLiteral(node, opts)`. - -Aliases: `Expression`, `Literal` - - - `quasis`: `Array` (required) - - `expressions`: `Array` (required) - ---- - -### thisExpression -```javascript -t.thisExpression() -``` - -See also `t.isThisExpression(node, opts)` and `t.assertThisExpression(node, opts)`. - -Aliases: `Expression` - - ---- - -### thisTypeAnnotation -```javascript -t.thisTypeAnnotation() -``` - -See also `t.isThisTypeAnnotation(node, opts)` and `t.assertThisTypeAnnotation(node, opts)`. - -Aliases: `Flow`, `FlowBaseAnnotation` - - ---- - -### throwStatement -```javascript -t.throwStatement(argument) -``` - -See also `t.isThrowStatement(node, opts)` and `t.assertThrowStatement(node, opts)`. - -Aliases: `Statement`, `Terminatorless`, `CompletionStatement` - - - `argument`: `Expression` (required) - ---- - -### tryStatement -```javascript -t.tryStatement(block, handler, finalizer) -``` - -See also `t.isTryStatement(node, opts)` and `t.assertTryStatement(node, opts)`. - -Aliases: `Statement` - - - `block`: `BlockStatement` (required) - - `handler`: `CatchClause` (default: `null`) - - `finalizer`: `BlockStatement` (default: `null`) - ---- - -### tupleTypeAnnotation -```javascript -t.tupleTypeAnnotation(types) -``` - -See also `t.isTupleTypeAnnotation(node, opts)` and `t.assertTupleTypeAnnotation(node, opts)`. - -Aliases: `Flow` - - - `types` (required) - ---- - -### typeAlias -```javascript -t.typeAlias(id, typeParameters, right) -``` - -See also `t.isTypeAlias(node, opts)` and `t.assertTypeAlias(node, opts)`. - -Aliases: `Flow`, `FlowDeclaration`, `Statement`, `Declaration` - - - `id` (required) - - `typeParameters` (required) - - `right` (required) - ---- - -### typeAnnotation -```javascript -t.typeAnnotation(typeAnnotation) -``` - -See also `t.isTypeAnnotation(node, opts)` and `t.assertTypeAnnotation(node, opts)`. - -Aliases: `Flow` - - - `typeAnnotation`: `Flow` (required) - ---- - -### typeCastExpression -```javascript -t.typeCastExpression(expression, typeAnnotation) -``` - -See also `t.isTypeCastExpression(node, opts)` and `t.assertTypeCastExpression(node, opts)`. - -Aliases: `Flow`, `ExpressionWrapper`, `Expression` - - - `expression` (required) - - `typeAnnotation` (required) - ---- - -### typeParameter -```javascript -t.typeParameter(bound, default) -``` - -See also `t.isTypeParameter(node, opts)` and `t.assertTypeParameter(node, opts)`. - -Aliases: `Flow` - - - `bound`: `TypeAnnotation` (default: `null`) - - `default`: `Flow` (default: `null`) - - `name`: `string` (default: `null`) - ---- - -### typeParameterDeclaration -```javascript -t.typeParameterDeclaration(params) -``` - -See also `t.isTypeParameterDeclaration(node, opts)` and `t.assertTypeParameterDeclaration(node, opts)`. - -Aliases: `Flow` - - - `params`: `Array` (required) - ---- - -### typeParameterInstantiation -```javascript -t.typeParameterInstantiation(params) -``` - -See also `t.isTypeParameterInstantiation(node, opts)` and `t.assertTypeParameterInstantiation(node, opts)`. - -Aliases: `Flow` - - - `params`: `Array` (required) - ---- - -### typeofTypeAnnotation -```javascript -t.typeofTypeAnnotation(argument) -``` - -See also `t.isTypeofTypeAnnotation(node, opts)` and `t.assertTypeofTypeAnnotation(node, opts)`. - -Aliases: `Flow` - - - `argument` (required) - ---- - -### unaryExpression -```javascript -t.unaryExpression(operator, argument, prefix) -``` - -See also `t.isUnaryExpression(node, opts)` and `t.assertUnaryExpression(node, opts)`. - -Aliases: `UnaryLike`, `Expression` - - - `operator`: `'void' | 'throw' | 'delete' | '!' | '+' | '-' | '~' | 'typeof'` (required) - - `argument`: `Expression` (required) - - `prefix`: `boolean` (default: `true`) - ---- - -### unionTypeAnnotation -```javascript -t.unionTypeAnnotation(types) -``` - -See also `t.isUnionTypeAnnotation(node, opts)` and `t.assertUnionTypeAnnotation(node, opts)`. - -Aliases: `Flow` - - - `types` (required) - ---- - -### updateExpression -```javascript -t.updateExpression(operator, argument, prefix) -``` - -See also `t.isUpdateExpression(node, opts)` and `t.assertUpdateExpression(node, opts)`. - -Aliases: `Expression` - - - `operator`: `'++' | '--'` (required) - - `argument`: `Expression` (required) - - `prefix`: `boolean` (default: `false`) - ---- - -### variableDeclaration -```javascript -t.variableDeclaration(kind, declarations) -``` - -See also `t.isVariableDeclaration(node, opts)` and `t.assertVariableDeclaration(node, opts)`. - -Aliases: `Statement`, `Declaration` - - - `kind`: `"var" | "let" | "const"` (required) - - `declarations`: `Array` (required) - - `declare`: `boolean` (default: `null`) - ---- - -### variableDeclarator -```javascript -t.variableDeclarator(id, init) -``` - -See also `t.isVariableDeclarator(node, opts)` and `t.assertVariableDeclarator(node, opts)`. - - - `id`: `LVal` (required) - - `init`: `Expression` (default: `null`) - ---- - -### voidTypeAnnotation -```javascript -t.voidTypeAnnotation() -``` - -See also `t.isVoidTypeAnnotation(node, opts)` and `t.assertVoidTypeAnnotation(node, opts)`. - -Aliases: `Flow`, `FlowBaseAnnotation` - - ---- - -### whileStatement -```javascript -t.whileStatement(test, body) -``` - -See also `t.isWhileStatement(node, opts)` and `t.assertWhileStatement(node, opts)`. - -Aliases: `Statement`, `BlockParent`, `Loop`, `While`, `Scopable` - - - `test`: `Expression` (required) - - `body`: `BlockStatement | Statement` (required) - ---- - -### withStatement -```javascript -t.withStatement(object, body) -``` - -See also `t.isWithStatement(node, opts)` and `t.assertWithStatement(node, opts)`. - -Aliases: `Statement` - - - `object`: `Expression` (required) - - `body`: `BlockStatement | Statement` (required) - ---- - -### yieldExpression -```javascript -t.yieldExpression(argument, delegate) -``` - -See also `t.isYieldExpression(node, opts)` and `t.assertYieldExpression(node, opts)`. - -Aliases: `Expression`, `Terminatorless` - - - `argument`: `Expression` (default: `null`) - - `delegate`: `boolean` (default: `false`) - ---- - - - - diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/asserts/assertNode.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/asserts/assertNode.js deleted file mode 100644 index 783ee0dbccfae8..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/asserts/assertNode.js +++ /dev/null @@ -1,15 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = assertNode; - -var _isNode = _interopRequireDefault(require("../validators/isNode")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function assertNode(node) { - if (!(0, _isNode.default)(node)) { - var type = node && node.type || JSON.stringify(node); - throw new TypeError("Not a valid node of type \"" + type + "\""); - } -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/asserts/generated/index.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/asserts/generated/index.js deleted file mode 100644 index 8c2b91eed30430..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/asserts/generated/index.js +++ /dev/null @@ -1,2215 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.assertArrayExpression = assertArrayExpression; -exports.assertAssignmentExpression = assertAssignmentExpression; -exports.assertBinaryExpression = assertBinaryExpression; -exports.assertDirective = assertDirective; -exports.assertDirectiveLiteral = assertDirectiveLiteral; -exports.assertBlockStatement = assertBlockStatement; -exports.assertBreakStatement = assertBreakStatement; -exports.assertCallExpression = assertCallExpression; -exports.assertCatchClause = assertCatchClause; -exports.assertConditionalExpression = assertConditionalExpression; -exports.assertContinueStatement = assertContinueStatement; -exports.assertDebuggerStatement = assertDebuggerStatement; -exports.assertDoWhileStatement = assertDoWhileStatement; -exports.assertEmptyStatement = assertEmptyStatement; -exports.assertExpressionStatement = assertExpressionStatement; -exports.assertFile = assertFile; -exports.assertForInStatement = assertForInStatement; -exports.assertForStatement = assertForStatement; -exports.assertFunctionDeclaration = assertFunctionDeclaration; -exports.assertFunctionExpression = assertFunctionExpression; -exports.assertIdentifier = assertIdentifier; -exports.assertIfStatement = assertIfStatement; -exports.assertLabeledStatement = assertLabeledStatement; -exports.assertStringLiteral = assertStringLiteral; -exports.assertNumericLiteral = assertNumericLiteral; -exports.assertNullLiteral = assertNullLiteral; -exports.assertBooleanLiteral = assertBooleanLiteral; -exports.assertRegExpLiteral = assertRegExpLiteral; -exports.assertLogicalExpression = assertLogicalExpression; -exports.assertMemberExpression = assertMemberExpression; -exports.assertNewExpression = assertNewExpression; -exports.assertProgram = assertProgram; -exports.assertObjectExpression = assertObjectExpression; -exports.assertObjectMethod = assertObjectMethod; -exports.assertObjectProperty = assertObjectProperty; -exports.assertRestElement = assertRestElement; -exports.assertReturnStatement = assertReturnStatement; -exports.assertSequenceExpression = assertSequenceExpression; -exports.assertSwitchCase = assertSwitchCase; -exports.assertSwitchStatement = assertSwitchStatement; -exports.assertThisExpression = assertThisExpression; -exports.assertThrowStatement = assertThrowStatement; -exports.assertTryStatement = assertTryStatement; -exports.assertUnaryExpression = assertUnaryExpression; -exports.assertUpdateExpression = assertUpdateExpression; -exports.assertVariableDeclaration = assertVariableDeclaration; -exports.assertVariableDeclarator = assertVariableDeclarator; -exports.assertWhileStatement = assertWhileStatement; -exports.assertWithStatement = assertWithStatement; -exports.assertAssignmentPattern = assertAssignmentPattern; -exports.assertArrayPattern = assertArrayPattern; -exports.assertArrowFunctionExpression = assertArrowFunctionExpression; -exports.assertClassBody = assertClassBody; -exports.assertClassDeclaration = assertClassDeclaration; -exports.assertClassExpression = assertClassExpression; -exports.assertExportAllDeclaration = assertExportAllDeclaration; -exports.assertExportDefaultDeclaration = assertExportDefaultDeclaration; -exports.assertExportNamedDeclaration = assertExportNamedDeclaration; -exports.assertExportSpecifier = assertExportSpecifier; -exports.assertForOfStatement = assertForOfStatement; -exports.assertImportDeclaration = assertImportDeclaration; -exports.assertImportDefaultSpecifier = assertImportDefaultSpecifier; -exports.assertImportNamespaceSpecifier = assertImportNamespaceSpecifier; -exports.assertImportSpecifier = assertImportSpecifier; -exports.assertMetaProperty = assertMetaProperty; -exports.assertClassMethod = assertClassMethod; -exports.assertObjectPattern = assertObjectPattern; -exports.assertSpreadElement = assertSpreadElement; -exports.assertSuper = assertSuper; -exports.assertTaggedTemplateExpression = assertTaggedTemplateExpression; -exports.assertTemplateElement = assertTemplateElement; -exports.assertTemplateLiteral = assertTemplateLiteral; -exports.assertYieldExpression = assertYieldExpression; -exports.assertAnyTypeAnnotation = assertAnyTypeAnnotation; -exports.assertArrayTypeAnnotation = assertArrayTypeAnnotation; -exports.assertBooleanTypeAnnotation = assertBooleanTypeAnnotation; -exports.assertBooleanLiteralTypeAnnotation = assertBooleanLiteralTypeAnnotation; -exports.assertNullLiteralTypeAnnotation = assertNullLiteralTypeAnnotation; -exports.assertClassImplements = assertClassImplements; -exports.assertDeclareClass = assertDeclareClass; -exports.assertDeclareFunction = assertDeclareFunction; -exports.assertDeclareInterface = assertDeclareInterface; -exports.assertDeclareModule = assertDeclareModule; -exports.assertDeclareModuleExports = assertDeclareModuleExports; -exports.assertDeclareTypeAlias = assertDeclareTypeAlias; -exports.assertDeclareOpaqueType = assertDeclareOpaqueType; -exports.assertDeclareVariable = assertDeclareVariable; -exports.assertDeclareExportDeclaration = assertDeclareExportDeclaration; -exports.assertDeclareExportAllDeclaration = assertDeclareExportAllDeclaration; -exports.assertDeclaredPredicate = assertDeclaredPredicate; -exports.assertExistsTypeAnnotation = assertExistsTypeAnnotation; -exports.assertFunctionTypeAnnotation = assertFunctionTypeAnnotation; -exports.assertFunctionTypeParam = assertFunctionTypeParam; -exports.assertGenericTypeAnnotation = assertGenericTypeAnnotation; -exports.assertInferredPredicate = assertInferredPredicate; -exports.assertInterfaceExtends = assertInterfaceExtends; -exports.assertInterfaceDeclaration = assertInterfaceDeclaration; -exports.assertIntersectionTypeAnnotation = assertIntersectionTypeAnnotation; -exports.assertMixedTypeAnnotation = assertMixedTypeAnnotation; -exports.assertEmptyTypeAnnotation = assertEmptyTypeAnnotation; -exports.assertNullableTypeAnnotation = assertNullableTypeAnnotation; -exports.assertNumberLiteralTypeAnnotation = assertNumberLiteralTypeAnnotation; -exports.assertNumberTypeAnnotation = assertNumberTypeAnnotation; -exports.assertObjectTypeAnnotation = assertObjectTypeAnnotation; -exports.assertObjectTypeCallProperty = assertObjectTypeCallProperty; -exports.assertObjectTypeIndexer = assertObjectTypeIndexer; -exports.assertObjectTypeProperty = assertObjectTypeProperty; -exports.assertObjectTypeSpreadProperty = assertObjectTypeSpreadProperty; -exports.assertOpaqueType = assertOpaqueType; -exports.assertQualifiedTypeIdentifier = assertQualifiedTypeIdentifier; -exports.assertStringLiteralTypeAnnotation = assertStringLiteralTypeAnnotation; -exports.assertStringTypeAnnotation = assertStringTypeAnnotation; -exports.assertThisTypeAnnotation = assertThisTypeAnnotation; -exports.assertTupleTypeAnnotation = assertTupleTypeAnnotation; -exports.assertTypeofTypeAnnotation = assertTypeofTypeAnnotation; -exports.assertTypeAlias = assertTypeAlias; -exports.assertTypeAnnotation = assertTypeAnnotation; -exports.assertTypeCastExpression = assertTypeCastExpression; -exports.assertTypeParameter = assertTypeParameter; -exports.assertTypeParameterDeclaration = assertTypeParameterDeclaration; -exports.assertTypeParameterInstantiation = assertTypeParameterInstantiation; -exports.assertUnionTypeAnnotation = assertUnionTypeAnnotation; -exports.assertVoidTypeAnnotation = assertVoidTypeAnnotation; -exports.assertJSXAttribute = assertJSXAttribute; -exports.assertJSXClosingElement = assertJSXClosingElement; -exports.assertJSXElement = assertJSXElement; -exports.assertJSXEmptyExpression = assertJSXEmptyExpression; -exports.assertJSXExpressionContainer = assertJSXExpressionContainer; -exports.assertJSXSpreadChild = assertJSXSpreadChild; -exports.assertJSXIdentifier = assertJSXIdentifier; -exports.assertJSXMemberExpression = assertJSXMemberExpression; -exports.assertJSXNamespacedName = assertJSXNamespacedName; -exports.assertJSXOpeningElement = assertJSXOpeningElement; -exports.assertJSXSpreadAttribute = assertJSXSpreadAttribute; -exports.assertJSXText = assertJSXText; -exports.assertJSXFragment = assertJSXFragment; -exports.assertJSXOpeningFragment = assertJSXOpeningFragment; -exports.assertJSXClosingFragment = assertJSXClosingFragment; -exports.assertNoop = assertNoop; -exports.assertParenthesizedExpression = assertParenthesizedExpression; -exports.assertAwaitExpression = assertAwaitExpression; -exports.assertBindExpression = assertBindExpression; -exports.assertClassProperty = assertClassProperty; -exports.assertImport = assertImport; -exports.assertDecorator = assertDecorator; -exports.assertDoExpression = assertDoExpression; -exports.assertExportDefaultSpecifier = assertExportDefaultSpecifier; -exports.assertExportNamespaceSpecifier = assertExportNamespaceSpecifier; -exports.assertTSParameterProperty = assertTSParameterProperty; -exports.assertTSDeclareFunction = assertTSDeclareFunction; -exports.assertTSDeclareMethod = assertTSDeclareMethod; -exports.assertTSQualifiedName = assertTSQualifiedName; -exports.assertTSCallSignatureDeclaration = assertTSCallSignatureDeclaration; -exports.assertTSConstructSignatureDeclaration = assertTSConstructSignatureDeclaration; -exports.assertTSPropertySignature = assertTSPropertySignature; -exports.assertTSMethodSignature = assertTSMethodSignature; -exports.assertTSIndexSignature = assertTSIndexSignature; -exports.assertTSAnyKeyword = assertTSAnyKeyword; -exports.assertTSNumberKeyword = assertTSNumberKeyword; -exports.assertTSObjectKeyword = assertTSObjectKeyword; -exports.assertTSBooleanKeyword = assertTSBooleanKeyword; -exports.assertTSStringKeyword = assertTSStringKeyword; -exports.assertTSSymbolKeyword = assertTSSymbolKeyword; -exports.assertTSVoidKeyword = assertTSVoidKeyword; -exports.assertTSUndefinedKeyword = assertTSUndefinedKeyword; -exports.assertTSNullKeyword = assertTSNullKeyword; -exports.assertTSNeverKeyword = assertTSNeverKeyword; -exports.assertTSThisType = assertTSThisType; -exports.assertTSFunctionType = assertTSFunctionType; -exports.assertTSConstructorType = assertTSConstructorType; -exports.assertTSTypeReference = assertTSTypeReference; -exports.assertTSTypePredicate = assertTSTypePredicate; -exports.assertTSTypeQuery = assertTSTypeQuery; -exports.assertTSTypeLiteral = assertTSTypeLiteral; -exports.assertTSArrayType = assertTSArrayType; -exports.assertTSTupleType = assertTSTupleType; -exports.assertTSUnionType = assertTSUnionType; -exports.assertTSIntersectionType = assertTSIntersectionType; -exports.assertTSParenthesizedType = assertTSParenthesizedType; -exports.assertTSTypeOperator = assertTSTypeOperator; -exports.assertTSIndexedAccessType = assertTSIndexedAccessType; -exports.assertTSMappedType = assertTSMappedType; -exports.assertTSLiteralType = assertTSLiteralType; -exports.assertTSExpressionWithTypeArguments = assertTSExpressionWithTypeArguments; -exports.assertTSInterfaceDeclaration = assertTSInterfaceDeclaration; -exports.assertTSInterfaceBody = assertTSInterfaceBody; -exports.assertTSTypeAliasDeclaration = assertTSTypeAliasDeclaration; -exports.assertTSAsExpression = assertTSAsExpression; -exports.assertTSTypeAssertion = assertTSTypeAssertion; -exports.assertTSEnumDeclaration = assertTSEnumDeclaration; -exports.assertTSEnumMember = assertTSEnumMember; -exports.assertTSModuleDeclaration = assertTSModuleDeclaration; -exports.assertTSModuleBlock = assertTSModuleBlock; -exports.assertTSImportEqualsDeclaration = assertTSImportEqualsDeclaration; -exports.assertTSExternalModuleReference = assertTSExternalModuleReference; -exports.assertTSNonNullExpression = assertTSNonNullExpression; -exports.assertTSExportAssignment = assertTSExportAssignment; -exports.assertTSNamespaceExportDeclaration = assertTSNamespaceExportDeclaration; -exports.assertTSTypeAnnotation = assertTSTypeAnnotation; -exports.assertTSTypeParameterInstantiation = assertTSTypeParameterInstantiation; -exports.assertTSTypeParameterDeclaration = assertTSTypeParameterDeclaration; -exports.assertTSTypeParameter = assertTSTypeParameter; -exports.assertExpression = assertExpression; -exports.assertBinary = assertBinary; -exports.assertScopable = assertScopable; -exports.assertBlockParent = assertBlockParent; -exports.assertBlock = assertBlock; -exports.assertStatement = assertStatement; -exports.assertTerminatorless = assertTerminatorless; -exports.assertCompletionStatement = assertCompletionStatement; -exports.assertConditional = assertConditional; -exports.assertLoop = assertLoop; -exports.assertWhile = assertWhile; -exports.assertExpressionWrapper = assertExpressionWrapper; -exports.assertFor = assertFor; -exports.assertForXStatement = assertForXStatement; -exports.assertFunction = assertFunction; -exports.assertFunctionParent = assertFunctionParent; -exports.assertPureish = assertPureish; -exports.assertDeclaration = assertDeclaration; -exports.assertPatternLike = assertPatternLike; -exports.assertLVal = assertLVal; -exports.assertTSEntityName = assertTSEntityName; -exports.assertLiteral = assertLiteral; -exports.assertImmutable = assertImmutable; -exports.assertUserWhitespacable = assertUserWhitespacable; -exports.assertMethod = assertMethod; -exports.assertObjectMember = assertObjectMember; -exports.assertProperty = assertProperty; -exports.assertUnaryLike = assertUnaryLike; -exports.assertPattern = assertPattern; -exports.assertClass = assertClass; -exports.assertModuleDeclaration = assertModuleDeclaration; -exports.assertExportDeclaration = assertExportDeclaration; -exports.assertModuleSpecifier = assertModuleSpecifier; -exports.assertFlow = assertFlow; -exports.assertFlowBaseAnnotation = assertFlowBaseAnnotation; -exports.assertFlowDeclaration = assertFlowDeclaration; -exports.assertFlowPredicate = assertFlowPredicate; -exports.assertJSX = assertJSX; -exports.assertTSTypeElement = assertTSTypeElement; -exports.assertTSType = assertTSType; -exports.assertNumberLiteral = assertNumberLiteral; -exports.assertRegexLiteral = assertRegexLiteral; -exports.assertRestProperty = assertRestProperty; -exports.assertSpreadProperty = assertSpreadProperty; - -var _is = _interopRequireDefault(require("../../validators/is")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function assert(type, node, opts) { - if (!(0, _is.default)(type, node, opts)) { - throw new Error("Expected type \"" + type + "\" with option " + JSON.stringify(opts) + ", but instead got \"" + node.type + "\"."); - } -} - -function assertArrayExpression(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ArrayExpression", node, opts); -} - -function assertAssignmentExpression(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("AssignmentExpression", node, opts); -} - -function assertBinaryExpression(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("BinaryExpression", node, opts); -} - -function assertDirective(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("Directive", node, opts); -} - -function assertDirectiveLiteral(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("DirectiveLiteral", node, opts); -} - -function assertBlockStatement(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("BlockStatement", node, opts); -} - -function assertBreakStatement(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("BreakStatement", node, opts); -} - -function assertCallExpression(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("CallExpression", node, opts); -} - -function assertCatchClause(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("CatchClause", node, opts); -} - -function assertConditionalExpression(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ConditionalExpression", node, opts); -} - -function assertContinueStatement(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ContinueStatement", node, opts); -} - -function assertDebuggerStatement(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("DebuggerStatement", node, opts); -} - -function assertDoWhileStatement(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("DoWhileStatement", node, opts); -} - -function assertEmptyStatement(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("EmptyStatement", node, opts); -} - -function assertExpressionStatement(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ExpressionStatement", node, opts); -} - -function assertFile(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("File", node, opts); -} - -function assertForInStatement(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ForInStatement", node, opts); -} - -function assertForStatement(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ForStatement", node, opts); -} - -function assertFunctionDeclaration(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("FunctionDeclaration", node, opts); -} - -function assertFunctionExpression(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("FunctionExpression", node, opts); -} - -function assertIdentifier(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("Identifier", node, opts); -} - -function assertIfStatement(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("IfStatement", node, opts); -} - -function assertLabeledStatement(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("LabeledStatement", node, opts); -} - -function assertStringLiteral(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("StringLiteral", node, opts); -} - -function assertNumericLiteral(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("NumericLiteral", node, opts); -} - -function assertNullLiteral(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("NullLiteral", node, opts); -} - -function assertBooleanLiteral(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("BooleanLiteral", node, opts); -} - -function assertRegExpLiteral(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("RegExpLiteral", node, opts); -} - -function assertLogicalExpression(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("LogicalExpression", node, opts); -} - -function assertMemberExpression(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("MemberExpression", node, opts); -} - -function assertNewExpression(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("NewExpression", node, opts); -} - -function assertProgram(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("Program", node, opts); -} - -function assertObjectExpression(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ObjectExpression", node, opts); -} - -function assertObjectMethod(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ObjectMethod", node, opts); -} - -function assertObjectProperty(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ObjectProperty", node, opts); -} - -function assertRestElement(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("RestElement", node, opts); -} - -function assertReturnStatement(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ReturnStatement", node, opts); -} - -function assertSequenceExpression(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("SequenceExpression", node, opts); -} - -function assertSwitchCase(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("SwitchCase", node, opts); -} - -function assertSwitchStatement(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("SwitchStatement", node, opts); -} - -function assertThisExpression(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ThisExpression", node, opts); -} - -function assertThrowStatement(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ThrowStatement", node, opts); -} - -function assertTryStatement(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TryStatement", node, opts); -} - -function assertUnaryExpression(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("UnaryExpression", node, opts); -} - -function assertUpdateExpression(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("UpdateExpression", node, opts); -} - -function assertVariableDeclaration(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("VariableDeclaration", node, opts); -} - -function assertVariableDeclarator(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("VariableDeclarator", node, opts); -} - -function assertWhileStatement(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("WhileStatement", node, opts); -} - -function assertWithStatement(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("WithStatement", node, opts); -} - -function assertAssignmentPattern(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("AssignmentPattern", node, opts); -} - -function assertArrayPattern(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ArrayPattern", node, opts); -} - -function assertArrowFunctionExpression(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ArrowFunctionExpression", node, opts); -} - -function assertClassBody(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ClassBody", node, opts); -} - -function assertClassDeclaration(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ClassDeclaration", node, opts); -} - -function assertClassExpression(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ClassExpression", node, opts); -} - -function assertExportAllDeclaration(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ExportAllDeclaration", node, opts); -} - -function assertExportDefaultDeclaration(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ExportDefaultDeclaration", node, opts); -} - -function assertExportNamedDeclaration(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ExportNamedDeclaration", node, opts); -} - -function assertExportSpecifier(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ExportSpecifier", node, opts); -} - -function assertForOfStatement(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ForOfStatement", node, opts); -} - -function assertImportDeclaration(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ImportDeclaration", node, opts); -} - -function assertImportDefaultSpecifier(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ImportDefaultSpecifier", node, opts); -} - -function assertImportNamespaceSpecifier(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ImportNamespaceSpecifier", node, opts); -} - -function assertImportSpecifier(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ImportSpecifier", node, opts); -} - -function assertMetaProperty(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("MetaProperty", node, opts); -} - -function assertClassMethod(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ClassMethod", node, opts); -} - -function assertObjectPattern(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ObjectPattern", node, opts); -} - -function assertSpreadElement(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("SpreadElement", node, opts); -} - -function assertSuper(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("Super", node, opts); -} - -function assertTaggedTemplateExpression(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TaggedTemplateExpression", node, opts); -} - -function assertTemplateElement(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TemplateElement", node, opts); -} - -function assertTemplateLiteral(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TemplateLiteral", node, opts); -} - -function assertYieldExpression(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("YieldExpression", node, opts); -} - -function assertAnyTypeAnnotation(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("AnyTypeAnnotation", node, opts); -} - -function assertArrayTypeAnnotation(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ArrayTypeAnnotation", node, opts); -} - -function assertBooleanTypeAnnotation(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("BooleanTypeAnnotation", node, opts); -} - -function assertBooleanLiteralTypeAnnotation(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("BooleanLiteralTypeAnnotation", node, opts); -} - -function assertNullLiteralTypeAnnotation(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("NullLiteralTypeAnnotation", node, opts); -} - -function assertClassImplements(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ClassImplements", node, opts); -} - -function assertDeclareClass(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("DeclareClass", node, opts); -} - -function assertDeclareFunction(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("DeclareFunction", node, opts); -} - -function assertDeclareInterface(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("DeclareInterface", node, opts); -} - -function assertDeclareModule(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("DeclareModule", node, opts); -} - -function assertDeclareModuleExports(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("DeclareModuleExports", node, opts); -} - -function assertDeclareTypeAlias(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("DeclareTypeAlias", node, opts); -} - -function assertDeclareOpaqueType(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("DeclareOpaqueType", node, opts); -} - -function assertDeclareVariable(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("DeclareVariable", node, opts); -} - -function assertDeclareExportDeclaration(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("DeclareExportDeclaration", node, opts); -} - -function assertDeclareExportAllDeclaration(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("DeclareExportAllDeclaration", node, opts); -} - -function assertDeclaredPredicate(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("DeclaredPredicate", node, opts); -} - -function assertExistsTypeAnnotation(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ExistsTypeAnnotation", node, opts); -} - -function assertFunctionTypeAnnotation(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("FunctionTypeAnnotation", node, opts); -} - -function assertFunctionTypeParam(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("FunctionTypeParam", node, opts); -} - -function assertGenericTypeAnnotation(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("GenericTypeAnnotation", node, opts); -} - -function assertInferredPredicate(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("InferredPredicate", node, opts); -} - -function assertInterfaceExtends(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("InterfaceExtends", node, opts); -} - -function assertInterfaceDeclaration(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("InterfaceDeclaration", node, opts); -} - -function assertIntersectionTypeAnnotation(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("IntersectionTypeAnnotation", node, opts); -} - -function assertMixedTypeAnnotation(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("MixedTypeAnnotation", node, opts); -} - -function assertEmptyTypeAnnotation(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("EmptyTypeAnnotation", node, opts); -} - -function assertNullableTypeAnnotation(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("NullableTypeAnnotation", node, opts); -} - -function assertNumberLiteralTypeAnnotation(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("NumberLiteralTypeAnnotation", node, opts); -} - -function assertNumberTypeAnnotation(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("NumberTypeAnnotation", node, opts); -} - -function assertObjectTypeAnnotation(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ObjectTypeAnnotation", node, opts); -} - -function assertObjectTypeCallProperty(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ObjectTypeCallProperty", node, opts); -} - -function assertObjectTypeIndexer(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ObjectTypeIndexer", node, opts); -} - -function assertObjectTypeProperty(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ObjectTypeProperty", node, opts); -} - -function assertObjectTypeSpreadProperty(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ObjectTypeSpreadProperty", node, opts); -} - -function assertOpaqueType(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("OpaqueType", node, opts); -} - -function assertQualifiedTypeIdentifier(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("QualifiedTypeIdentifier", node, opts); -} - -function assertStringLiteralTypeAnnotation(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("StringLiteralTypeAnnotation", node, opts); -} - -function assertStringTypeAnnotation(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("StringTypeAnnotation", node, opts); -} - -function assertThisTypeAnnotation(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ThisTypeAnnotation", node, opts); -} - -function assertTupleTypeAnnotation(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TupleTypeAnnotation", node, opts); -} - -function assertTypeofTypeAnnotation(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TypeofTypeAnnotation", node, opts); -} - -function assertTypeAlias(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TypeAlias", node, opts); -} - -function assertTypeAnnotation(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TypeAnnotation", node, opts); -} - -function assertTypeCastExpression(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TypeCastExpression", node, opts); -} - -function assertTypeParameter(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TypeParameter", node, opts); -} - -function assertTypeParameterDeclaration(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TypeParameterDeclaration", node, opts); -} - -function assertTypeParameterInstantiation(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TypeParameterInstantiation", node, opts); -} - -function assertUnionTypeAnnotation(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("UnionTypeAnnotation", node, opts); -} - -function assertVoidTypeAnnotation(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("VoidTypeAnnotation", node, opts); -} - -function assertJSXAttribute(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("JSXAttribute", node, opts); -} - -function assertJSXClosingElement(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("JSXClosingElement", node, opts); -} - -function assertJSXElement(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("JSXElement", node, opts); -} - -function assertJSXEmptyExpression(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("JSXEmptyExpression", node, opts); -} - -function assertJSXExpressionContainer(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("JSXExpressionContainer", node, opts); -} - -function assertJSXSpreadChild(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("JSXSpreadChild", node, opts); -} - -function assertJSXIdentifier(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("JSXIdentifier", node, opts); -} - -function assertJSXMemberExpression(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("JSXMemberExpression", node, opts); -} - -function assertJSXNamespacedName(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("JSXNamespacedName", node, opts); -} - -function assertJSXOpeningElement(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("JSXOpeningElement", node, opts); -} - -function assertJSXSpreadAttribute(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("JSXSpreadAttribute", node, opts); -} - -function assertJSXText(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("JSXText", node, opts); -} - -function assertJSXFragment(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("JSXFragment", node, opts); -} - -function assertJSXOpeningFragment(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("JSXOpeningFragment", node, opts); -} - -function assertJSXClosingFragment(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("JSXClosingFragment", node, opts); -} - -function assertNoop(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("Noop", node, opts); -} - -function assertParenthesizedExpression(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ParenthesizedExpression", node, opts); -} - -function assertAwaitExpression(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("AwaitExpression", node, opts); -} - -function assertBindExpression(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("BindExpression", node, opts); -} - -function assertClassProperty(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ClassProperty", node, opts); -} - -function assertImport(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("Import", node, opts); -} - -function assertDecorator(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("Decorator", node, opts); -} - -function assertDoExpression(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("DoExpression", node, opts); -} - -function assertExportDefaultSpecifier(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ExportDefaultSpecifier", node, opts); -} - -function assertExportNamespaceSpecifier(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ExportNamespaceSpecifier", node, opts); -} - -function assertTSParameterProperty(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSParameterProperty", node, opts); -} - -function assertTSDeclareFunction(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSDeclareFunction", node, opts); -} - -function assertTSDeclareMethod(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSDeclareMethod", node, opts); -} - -function assertTSQualifiedName(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSQualifiedName", node, opts); -} - -function assertTSCallSignatureDeclaration(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSCallSignatureDeclaration", node, opts); -} - -function assertTSConstructSignatureDeclaration(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSConstructSignatureDeclaration", node, opts); -} - -function assertTSPropertySignature(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSPropertySignature", node, opts); -} - -function assertTSMethodSignature(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSMethodSignature", node, opts); -} - -function assertTSIndexSignature(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSIndexSignature", node, opts); -} - -function assertTSAnyKeyword(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSAnyKeyword", node, opts); -} - -function assertTSNumberKeyword(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSNumberKeyword", node, opts); -} - -function assertTSObjectKeyword(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSObjectKeyword", node, opts); -} - -function assertTSBooleanKeyword(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSBooleanKeyword", node, opts); -} - -function assertTSStringKeyword(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSStringKeyword", node, opts); -} - -function assertTSSymbolKeyword(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSSymbolKeyword", node, opts); -} - -function assertTSVoidKeyword(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSVoidKeyword", node, opts); -} - -function assertTSUndefinedKeyword(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSUndefinedKeyword", node, opts); -} - -function assertTSNullKeyword(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSNullKeyword", node, opts); -} - -function assertTSNeverKeyword(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSNeverKeyword", node, opts); -} - -function assertTSThisType(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSThisType", node, opts); -} - -function assertTSFunctionType(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSFunctionType", node, opts); -} - -function assertTSConstructorType(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSConstructorType", node, opts); -} - -function assertTSTypeReference(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSTypeReference", node, opts); -} - -function assertTSTypePredicate(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSTypePredicate", node, opts); -} - -function assertTSTypeQuery(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSTypeQuery", node, opts); -} - -function assertTSTypeLiteral(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSTypeLiteral", node, opts); -} - -function assertTSArrayType(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSArrayType", node, opts); -} - -function assertTSTupleType(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSTupleType", node, opts); -} - -function assertTSUnionType(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSUnionType", node, opts); -} - -function assertTSIntersectionType(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSIntersectionType", node, opts); -} - -function assertTSParenthesizedType(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSParenthesizedType", node, opts); -} - -function assertTSTypeOperator(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSTypeOperator", node, opts); -} - -function assertTSIndexedAccessType(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSIndexedAccessType", node, opts); -} - -function assertTSMappedType(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSMappedType", node, opts); -} - -function assertTSLiteralType(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSLiteralType", node, opts); -} - -function assertTSExpressionWithTypeArguments(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSExpressionWithTypeArguments", node, opts); -} - -function assertTSInterfaceDeclaration(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSInterfaceDeclaration", node, opts); -} - -function assertTSInterfaceBody(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSInterfaceBody", node, opts); -} - -function assertTSTypeAliasDeclaration(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSTypeAliasDeclaration", node, opts); -} - -function assertTSAsExpression(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSAsExpression", node, opts); -} - -function assertTSTypeAssertion(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSTypeAssertion", node, opts); -} - -function assertTSEnumDeclaration(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSEnumDeclaration", node, opts); -} - -function assertTSEnumMember(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSEnumMember", node, opts); -} - -function assertTSModuleDeclaration(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSModuleDeclaration", node, opts); -} - -function assertTSModuleBlock(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSModuleBlock", node, opts); -} - -function assertTSImportEqualsDeclaration(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSImportEqualsDeclaration", node, opts); -} - -function assertTSExternalModuleReference(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSExternalModuleReference", node, opts); -} - -function assertTSNonNullExpression(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSNonNullExpression", node, opts); -} - -function assertTSExportAssignment(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSExportAssignment", node, opts); -} - -function assertTSNamespaceExportDeclaration(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSNamespaceExportDeclaration", node, opts); -} - -function assertTSTypeAnnotation(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSTypeAnnotation", node, opts); -} - -function assertTSTypeParameterInstantiation(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSTypeParameterInstantiation", node, opts); -} - -function assertTSTypeParameterDeclaration(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSTypeParameterDeclaration", node, opts); -} - -function assertTSTypeParameter(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSTypeParameter", node, opts); -} - -function assertExpression(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("Expression", node, opts); -} - -function assertBinary(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("Binary", node, opts); -} - -function assertScopable(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("Scopable", node, opts); -} - -function assertBlockParent(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("BlockParent", node, opts); -} - -function assertBlock(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("Block", node, opts); -} - -function assertStatement(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("Statement", node, opts); -} - -function assertTerminatorless(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("Terminatorless", node, opts); -} - -function assertCompletionStatement(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("CompletionStatement", node, opts); -} - -function assertConditional(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("Conditional", node, opts); -} - -function assertLoop(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("Loop", node, opts); -} - -function assertWhile(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("While", node, opts); -} - -function assertExpressionWrapper(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ExpressionWrapper", node, opts); -} - -function assertFor(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("For", node, opts); -} - -function assertForXStatement(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ForXStatement", node, opts); -} - -function assertFunction(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("Function", node, opts); -} - -function assertFunctionParent(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("FunctionParent", node, opts); -} - -function assertPureish(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("Pureish", node, opts); -} - -function assertDeclaration(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("Declaration", node, opts); -} - -function assertPatternLike(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("PatternLike", node, opts); -} - -function assertLVal(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("LVal", node, opts); -} - -function assertTSEntityName(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSEntityName", node, opts); -} - -function assertLiteral(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("Literal", node, opts); -} - -function assertImmutable(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("Immutable", node, opts); -} - -function assertUserWhitespacable(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("UserWhitespacable", node, opts); -} - -function assertMethod(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("Method", node, opts); -} - -function assertObjectMember(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ObjectMember", node, opts); -} - -function assertProperty(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("Property", node, opts); -} - -function assertUnaryLike(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("UnaryLike", node, opts); -} - -function assertPattern(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("Pattern", node, opts); -} - -function assertClass(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("Class", node, opts); -} - -function assertModuleDeclaration(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ModuleDeclaration", node, opts); -} - -function assertExportDeclaration(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ExportDeclaration", node, opts); -} - -function assertModuleSpecifier(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("ModuleSpecifier", node, opts); -} - -function assertFlow(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("Flow", node, opts); -} - -function assertFlowBaseAnnotation(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("FlowBaseAnnotation", node, opts); -} - -function assertFlowDeclaration(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("FlowDeclaration", node, opts); -} - -function assertFlowPredicate(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("FlowPredicate", node, opts); -} - -function assertJSX(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("JSX", node, opts); -} - -function assertTSTypeElement(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSTypeElement", node, opts); -} - -function assertTSType(node, opts) { - if (opts === void 0) { - opts = {}; - } - - assert("TSType", node, opts); -} - -function assertNumberLiteral(node, opts) { - console.trace("The node type NumberLiteral has been renamed to NumericLiteral"); - assert("NumberLiteral", node, opts); -} - -function assertRegexLiteral(node, opts) { - console.trace("The node type RegexLiteral has been renamed to RegExpLiteral"); - assert("RegexLiteral", node, opts); -} - -function assertRestProperty(node, opts) { - console.trace("The node type RestProperty has been renamed to RestElement"); - assert("RestProperty", node, opts); -} - -function assertSpreadProperty(node, opts) { - console.trace("The node type SpreadProperty has been renamed to SpreadElement"); - assert("SpreadProperty", node, opts); -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/builders/builder.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/builders/builder.js deleted file mode 100644 index 4adf87032d41f1..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/builders/builder.js +++ /dev/null @@ -1,44 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = builder; - -var _clone = _interopRequireDefault(require("lodash/clone")); - -var _definitions = require("../definitions"); - -var _validate = _interopRequireDefault(require("../validators/validate")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function builder(type) { - for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - - var keys = _definitions.BUILDER_KEYS[type]; - var countArgs = args.length; - - if (countArgs > keys.length) { - throw new Error(type + ": Too many arguments passed. Received " + countArgs + " but can receive no more than " + keys.length); - } - - var node = { - type: type - }; - var i = 0; - keys.forEach(function (key) { - var field = _definitions.NODE_FIELDS[type][key]; - var arg; - if (i < countArgs) arg = args[i]; - if (arg === undefined) arg = (0, _clone.default)(field.default); - node[key] = arg; - i++; - }); - - for (var key in node) { - (0, _validate.default)(node, key, node[key]); - } - - return node; -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/builders/flow/createTypeAnnotationBasedOnTypeof.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/builders/flow/createTypeAnnotationBasedOnTypeof.js deleted file mode 100644 index bff3b99b3f62e5..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/builders/flow/createTypeAnnotationBasedOnTypeof.js +++ /dev/null @@ -1,26 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = createTypeAnnotationBasedOnTypeof; - -var _generated = require("../generated"); - -function createTypeAnnotationBasedOnTypeof(type) { - if (type === "string") { - return (0, _generated.stringTypeAnnotation)(); - } else if (type === "number") { - return (0, _generated.numberTypeAnnotation)(); - } else if (type === "undefined") { - return (0, _generated.voidTypeAnnotation)(); - } else if (type === "boolean") { - return (0, _generated.booleanTypeAnnotation)(); - } else if (type === "function") { - return (0, _generated.genericTypeAnnotation)((0, _generated.identifier)("Function")); - } else if (type === "object") { - return (0, _generated.genericTypeAnnotation)((0, _generated.identifier)("Object")); - } else if (type === "symbol") { - return (0, _generated.genericTypeAnnotation)((0, _generated.identifier)("Symbol")); - } else { - throw new Error("Invalid typeof value"); - } -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/builders/flow/createUnionTypeAnnotation.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/builders/flow/createUnionTypeAnnotation.js deleted file mode 100644 index 932e45972962ce..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/builders/flow/createUnionTypeAnnotation.js +++ /dev/null @@ -1,20 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = createUnionTypeAnnotation; - -var _generated = require("../generated"); - -var _removeTypeDuplicates = _interopRequireDefault(require("../../modifications/flow/removeTypeDuplicates")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function createUnionTypeAnnotation(types) { - var flattened = (0, _removeTypeDuplicates.default)(types); - - if (flattened.length === 1) { - return flattened[0]; - } else { - return (0, _generated.unionTypeAnnotation)(flattened); - } -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/builders/generated/index.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/builders/generated/index.js deleted file mode 100644 index 632b628f8dd6bb..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/builders/generated/index.js +++ /dev/null @@ -1,1869 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.arrayExpression = exports.ArrayExpression = ArrayExpression; -exports.assignmentExpression = exports.AssignmentExpression = AssignmentExpression; -exports.binaryExpression = exports.BinaryExpression = BinaryExpression; -exports.directive = exports.Directive = Directive; -exports.directiveLiteral = exports.DirectiveLiteral = DirectiveLiteral; -exports.blockStatement = exports.BlockStatement = BlockStatement; -exports.breakStatement = exports.BreakStatement = BreakStatement; -exports.callExpression = exports.CallExpression = CallExpression; -exports.catchClause = exports.CatchClause = CatchClause; -exports.conditionalExpression = exports.ConditionalExpression = ConditionalExpression; -exports.continueStatement = exports.ContinueStatement = ContinueStatement; -exports.debuggerStatement = exports.DebuggerStatement = DebuggerStatement; -exports.doWhileStatement = exports.DoWhileStatement = DoWhileStatement; -exports.emptyStatement = exports.EmptyStatement = EmptyStatement; -exports.expressionStatement = exports.ExpressionStatement = ExpressionStatement; -exports.file = exports.File = File; -exports.forInStatement = exports.ForInStatement = ForInStatement; -exports.forStatement = exports.ForStatement = ForStatement; -exports.functionDeclaration = exports.FunctionDeclaration = FunctionDeclaration; -exports.functionExpression = exports.FunctionExpression = FunctionExpression; -exports.identifier = exports.Identifier = Identifier; -exports.ifStatement = exports.IfStatement = IfStatement; -exports.labeledStatement = exports.LabeledStatement = LabeledStatement; -exports.stringLiteral = exports.StringLiteral = StringLiteral; -exports.numericLiteral = exports.NumericLiteral = NumericLiteral; -exports.nullLiteral = exports.NullLiteral = NullLiteral; -exports.booleanLiteral = exports.BooleanLiteral = BooleanLiteral; -exports.regExpLiteral = exports.RegExpLiteral = RegExpLiteral; -exports.logicalExpression = exports.LogicalExpression = LogicalExpression; -exports.memberExpression = exports.MemberExpression = MemberExpression; -exports.newExpression = exports.NewExpression = NewExpression; -exports.program = exports.Program = Program; -exports.objectExpression = exports.ObjectExpression = ObjectExpression; -exports.objectMethod = exports.ObjectMethod = ObjectMethod; -exports.objectProperty = exports.ObjectProperty = ObjectProperty; -exports.restElement = exports.RestElement = RestElement; -exports.returnStatement = exports.ReturnStatement = ReturnStatement; -exports.sequenceExpression = exports.SequenceExpression = SequenceExpression; -exports.switchCase = exports.SwitchCase = SwitchCase; -exports.switchStatement = exports.SwitchStatement = SwitchStatement; -exports.thisExpression = exports.ThisExpression = ThisExpression; -exports.throwStatement = exports.ThrowStatement = ThrowStatement; -exports.tryStatement = exports.TryStatement = TryStatement; -exports.unaryExpression = exports.UnaryExpression = UnaryExpression; -exports.updateExpression = exports.UpdateExpression = UpdateExpression; -exports.variableDeclaration = exports.VariableDeclaration = VariableDeclaration; -exports.variableDeclarator = exports.VariableDeclarator = VariableDeclarator; -exports.whileStatement = exports.WhileStatement = WhileStatement; -exports.withStatement = exports.WithStatement = WithStatement; -exports.assignmentPattern = exports.AssignmentPattern = AssignmentPattern; -exports.arrayPattern = exports.ArrayPattern = ArrayPattern; -exports.arrowFunctionExpression = exports.ArrowFunctionExpression = ArrowFunctionExpression; -exports.classBody = exports.ClassBody = ClassBody; -exports.classDeclaration = exports.ClassDeclaration = ClassDeclaration; -exports.classExpression = exports.ClassExpression = ClassExpression; -exports.exportAllDeclaration = exports.ExportAllDeclaration = ExportAllDeclaration; -exports.exportDefaultDeclaration = exports.ExportDefaultDeclaration = ExportDefaultDeclaration; -exports.exportNamedDeclaration = exports.ExportNamedDeclaration = ExportNamedDeclaration; -exports.exportSpecifier = exports.ExportSpecifier = ExportSpecifier; -exports.forOfStatement = exports.ForOfStatement = ForOfStatement; -exports.importDeclaration = exports.ImportDeclaration = ImportDeclaration; -exports.importDefaultSpecifier = exports.ImportDefaultSpecifier = ImportDefaultSpecifier; -exports.importNamespaceSpecifier = exports.ImportNamespaceSpecifier = ImportNamespaceSpecifier; -exports.importSpecifier = exports.ImportSpecifier = ImportSpecifier; -exports.metaProperty = exports.MetaProperty = MetaProperty; -exports.classMethod = exports.ClassMethod = ClassMethod; -exports.objectPattern = exports.ObjectPattern = ObjectPattern; -exports.spreadElement = exports.SpreadElement = SpreadElement; -exports.super = exports.Super = Super; -exports.taggedTemplateExpression = exports.TaggedTemplateExpression = TaggedTemplateExpression; -exports.templateElement = exports.TemplateElement = TemplateElement; -exports.templateLiteral = exports.TemplateLiteral = TemplateLiteral; -exports.yieldExpression = exports.YieldExpression = YieldExpression; -exports.anyTypeAnnotation = exports.AnyTypeAnnotation = AnyTypeAnnotation; -exports.arrayTypeAnnotation = exports.ArrayTypeAnnotation = ArrayTypeAnnotation; -exports.booleanTypeAnnotation = exports.BooleanTypeAnnotation = BooleanTypeAnnotation; -exports.booleanLiteralTypeAnnotation = exports.BooleanLiteralTypeAnnotation = BooleanLiteralTypeAnnotation; -exports.nullLiteralTypeAnnotation = exports.NullLiteralTypeAnnotation = NullLiteralTypeAnnotation; -exports.classImplements = exports.ClassImplements = ClassImplements; -exports.declareClass = exports.DeclareClass = DeclareClass; -exports.declareFunction = exports.DeclareFunction = DeclareFunction; -exports.declareInterface = exports.DeclareInterface = DeclareInterface; -exports.declareModule = exports.DeclareModule = DeclareModule; -exports.declareModuleExports = exports.DeclareModuleExports = DeclareModuleExports; -exports.declareTypeAlias = exports.DeclareTypeAlias = DeclareTypeAlias; -exports.declareOpaqueType = exports.DeclareOpaqueType = DeclareOpaqueType; -exports.declareVariable = exports.DeclareVariable = DeclareVariable; -exports.declareExportDeclaration = exports.DeclareExportDeclaration = DeclareExportDeclaration; -exports.declareExportAllDeclaration = exports.DeclareExportAllDeclaration = DeclareExportAllDeclaration; -exports.declaredPredicate = exports.DeclaredPredicate = DeclaredPredicate; -exports.existsTypeAnnotation = exports.ExistsTypeAnnotation = ExistsTypeAnnotation; -exports.functionTypeAnnotation = exports.FunctionTypeAnnotation = FunctionTypeAnnotation; -exports.functionTypeParam = exports.FunctionTypeParam = FunctionTypeParam; -exports.genericTypeAnnotation = exports.GenericTypeAnnotation = GenericTypeAnnotation; -exports.inferredPredicate = exports.InferredPredicate = InferredPredicate; -exports.interfaceExtends = exports.InterfaceExtends = InterfaceExtends; -exports.interfaceDeclaration = exports.InterfaceDeclaration = InterfaceDeclaration; -exports.intersectionTypeAnnotation = exports.IntersectionTypeAnnotation = IntersectionTypeAnnotation; -exports.mixedTypeAnnotation = exports.MixedTypeAnnotation = MixedTypeAnnotation; -exports.emptyTypeAnnotation = exports.EmptyTypeAnnotation = EmptyTypeAnnotation; -exports.nullableTypeAnnotation = exports.NullableTypeAnnotation = NullableTypeAnnotation; -exports.numberLiteralTypeAnnotation = exports.NumberLiteralTypeAnnotation = NumberLiteralTypeAnnotation; -exports.numberTypeAnnotation = exports.NumberTypeAnnotation = NumberTypeAnnotation; -exports.objectTypeAnnotation = exports.ObjectTypeAnnotation = ObjectTypeAnnotation; -exports.objectTypeCallProperty = exports.ObjectTypeCallProperty = ObjectTypeCallProperty; -exports.objectTypeIndexer = exports.ObjectTypeIndexer = ObjectTypeIndexer; -exports.objectTypeProperty = exports.ObjectTypeProperty = ObjectTypeProperty; -exports.objectTypeSpreadProperty = exports.ObjectTypeSpreadProperty = ObjectTypeSpreadProperty; -exports.opaqueType = exports.OpaqueType = OpaqueType; -exports.qualifiedTypeIdentifier = exports.QualifiedTypeIdentifier = QualifiedTypeIdentifier; -exports.stringLiteralTypeAnnotation = exports.StringLiteralTypeAnnotation = StringLiteralTypeAnnotation; -exports.stringTypeAnnotation = exports.StringTypeAnnotation = StringTypeAnnotation; -exports.thisTypeAnnotation = exports.ThisTypeAnnotation = ThisTypeAnnotation; -exports.tupleTypeAnnotation = exports.TupleTypeAnnotation = TupleTypeAnnotation; -exports.typeofTypeAnnotation = exports.TypeofTypeAnnotation = TypeofTypeAnnotation; -exports.typeAlias = exports.TypeAlias = TypeAlias; -exports.typeAnnotation = exports.TypeAnnotation = TypeAnnotation; -exports.typeCastExpression = exports.TypeCastExpression = TypeCastExpression; -exports.typeParameter = exports.TypeParameter = TypeParameter; -exports.typeParameterDeclaration = exports.TypeParameterDeclaration = TypeParameterDeclaration; -exports.typeParameterInstantiation = exports.TypeParameterInstantiation = TypeParameterInstantiation; -exports.unionTypeAnnotation = exports.UnionTypeAnnotation = UnionTypeAnnotation; -exports.voidTypeAnnotation = exports.VoidTypeAnnotation = VoidTypeAnnotation; -exports.jSXAttribute = exports.jsxAttribute = exports.JSXAttribute = JSXAttribute; -exports.jSXClosingElement = exports.jsxClosingElement = exports.JSXClosingElement = JSXClosingElement; -exports.jSXElement = exports.jsxElement = exports.JSXElement = JSXElement; -exports.jSXEmptyExpression = exports.jsxEmptyExpression = exports.JSXEmptyExpression = JSXEmptyExpression; -exports.jSXExpressionContainer = exports.jsxExpressionContainer = exports.JSXExpressionContainer = JSXExpressionContainer; -exports.jSXSpreadChild = exports.jsxSpreadChild = exports.JSXSpreadChild = JSXSpreadChild; -exports.jSXIdentifier = exports.jsxIdentifier = exports.JSXIdentifier = JSXIdentifier; -exports.jSXMemberExpression = exports.jsxMemberExpression = exports.JSXMemberExpression = JSXMemberExpression; -exports.jSXNamespacedName = exports.jsxNamespacedName = exports.JSXNamespacedName = JSXNamespacedName; -exports.jSXOpeningElement = exports.jsxOpeningElement = exports.JSXOpeningElement = JSXOpeningElement; -exports.jSXSpreadAttribute = exports.jsxSpreadAttribute = exports.JSXSpreadAttribute = JSXSpreadAttribute; -exports.jSXText = exports.jsxText = exports.JSXText = JSXText; -exports.jSXFragment = exports.jsxFragment = exports.JSXFragment = JSXFragment; -exports.jSXOpeningFragment = exports.jsxOpeningFragment = exports.JSXOpeningFragment = JSXOpeningFragment; -exports.jSXClosingFragment = exports.jsxClosingFragment = exports.JSXClosingFragment = JSXClosingFragment; -exports.noop = exports.Noop = Noop; -exports.parenthesizedExpression = exports.ParenthesizedExpression = ParenthesizedExpression; -exports.awaitExpression = exports.AwaitExpression = AwaitExpression; -exports.bindExpression = exports.BindExpression = BindExpression; -exports.classProperty = exports.ClassProperty = ClassProperty; -exports.import = exports.Import = Import; -exports.decorator = exports.Decorator = Decorator; -exports.doExpression = exports.DoExpression = DoExpression; -exports.exportDefaultSpecifier = exports.ExportDefaultSpecifier = ExportDefaultSpecifier; -exports.exportNamespaceSpecifier = exports.ExportNamespaceSpecifier = ExportNamespaceSpecifier; -exports.tSParameterProperty = exports.tsParameterProperty = exports.TSParameterProperty = TSParameterProperty; -exports.tSDeclareFunction = exports.tsDeclareFunction = exports.TSDeclareFunction = TSDeclareFunction; -exports.tSDeclareMethod = exports.tsDeclareMethod = exports.TSDeclareMethod = TSDeclareMethod; -exports.tSQualifiedName = exports.tsQualifiedName = exports.TSQualifiedName = TSQualifiedName; -exports.tSCallSignatureDeclaration = exports.tsCallSignatureDeclaration = exports.TSCallSignatureDeclaration = TSCallSignatureDeclaration; -exports.tSConstructSignatureDeclaration = exports.tsConstructSignatureDeclaration = exports.TSConstructSignatureDeclaration = TSConstructSignatureDeclaration; -exports.tSPropertySignature = exports.tsPropertySignature = exports.TSPropertySignature = TSPropertySignature; -exports.tSMethodSignature = exports.tsMethodSignature = exports.TSMethodSignature = TSMethodSignature; -exports.tSIndexSignature = exports.tsIndexSignature = exports.TSIndexSignature = TSIndexSignature; -exports.tSAnyKeyword = exports.tsAnyKeyword = exports.TSAnyKeyword = TSAnyKeyword; -exports.tSNumberKeyword = exports.tsNumberKeyword = exports.TSNumberKeyword = TSNumberKeyword; -exports.tSObjectKeyword = exports.tsObjectKeyword = exports.TSObjectKeyword = TSObjectKeyword; -exports.tSBooleanKeyword = exports.tsBooleanKeyword = exports.TSBooleanKeyword = TSBooleanKeyword; -exports.tSStringKeyword = exports.tsStringKeyword = exports.TSStringKeyword = TSStringKeyword; -exports.tSSymbolKeyword = exports.tsSymbolKeyword = exports.TSSymbolKeyword = TSSymbolKeyword; -exports.tSVoidKeyword = exports.tsVoidKeyword = exports.TSVoidKeyword = TSVoidKeyword; -exports.tSUndefinedKeyword = exports.tsUndefinedKeyword = exports.TSUndefinedKeyword = TSUndefinedKeyword; -exports.tSNullKeyword = exports.tsNullKeyword = exports.TSNullKeyword = TSNullKeyword; -exports.tSNeverKeyword = exports.tsNeverKeyword = exports.TSNeverKeyword = TSNeverKeyword; -exports.tSThisType = exports.tsThisType = exports.TSThisType = TSThisType; -exports.tSFunctionType = exports.tsFunctionType = exports.TSFunctionType = TSFunctionType; -exports.tSConstructorType = exports.tsConstructorType = exports.TSConstructorType = TSConstructorType; -exports.tSTypeReference = exports.tsTypeReference = exports.TSTypeReference = TSTypeReference; -exports.tSTypePredicate = exports.tsTypePredicate = exports.TSTypePredicate = TSTypePredicate; -exports.tSTypeQuery = exports.tsTypeQuery = exports.TSTypeQuery = TSTypeQuery; -exports.tSTypeLiteral = exports.tsTypeLiteral = exports.TSTypeLiteral = TSTypeLiteral; -exports.tSArrayType = exports.tsArrayType = exports.TSArrayType = TSArrayType; -exports.tSTupleType = exports.tsTupleType = exports.TSTupleType = TSTupleType; -exports.tSUnionType = exports.tsUnionType = exports.TSUnionType = TSUnionType; -exports.tSIntersectionType = exports.tsIntersectionType = exports.TSIntersectionType = TSIntersectionType; -exports.tSParenthesizedType = exports.tsParenthesizedType = exports.TSParenthesizedType = TSParenthesizedType; -exports.tSTypeOperator = exports.tsTypeOperator = exports.TSTypeOperator = TSTypeOperator; -exports.tSIndexedAccessType = exports.tsIndexedAccessType = exports.TSIndexedAccessType = TSIndexedAccessType; -exports.tSMappedType = exports.tsMappedType = exports.TSMappedType = TSMappedType; -exports.tSLiteralType = exports.tsLiteralType = exports.TSLiteralType = TSLiteralType; -exports.tSExpressionWithTypeArguments = exports.tsExpressionWithTypeArguments = exports.TSExpressionWithTypeArguments = TSExpressionWithTypeArguments; -exports.tSInterfaceDeclaration = exports.tsInterfaceDeclaration = exports.TSInterfaceDeclaration = TSInterfaceDeclaration; -exports.tSInterfaceBody = exports.tsInterfaceBody = exports.TSInterfaceBody = TSInterfaceBody; -exports.tSTypeAliasDeclaration = exports.tsTypeAliasDeclaration = exports.TSTypeAliasDeclaration = TSTypeAliasDeclaration; -exports.tSAsExpression = exports.tsAsExpression = exports.TSAsExpression = TSAsExpression; -exports.tSTypeAssertion = exports.tsTypeAssertion = exports.TSTypeAssertion = TSTypeAssertion; -exports.tSEnumDeclaration = exports.tsEnumDeclaration = exports.TSEnumDeclaration = TSEnumDeclaration; -exports.tSEnumMember = exports.tsEnumMember = exports.TSEnumMember = TSEnumMember; -exports.tSModuleDeclaration = exports.tsModuleDeclaration = exports.TSModuleDeclaration = TSModuleDeclaration; -exports.tSModuleBlock = exports.tsModuleBlock = exports.TSModuleBlock = TSModuleBlock; -exports.tSImportEqualsDeclaration = exports.tsImportEqualsDeclaration = exports.TSImportEqualsDeclaration = TSImportEqualsDeclaration; -exports.tSExternalModuleReference = exports.tsExternalModuleReference = exports.TSExternalModuleReference = TSExternalModuleReference; -exports.tSNonNullExpression = exports.tsNonNullExpression = exports.TSNonNullExpression = TSNonNullExpression; -exports.tSExportAssignment = exports.tsExportAssignment = exports.TSExportAssignment = TSExportAssignment; -exports.tSNamespaceExportDeclaration = exports.tsNamespaceExportDeclaration = exports.TSNamespaceExportDeclaration = TSNamespaceExportDeclaration; -exports.tSTypeAnnotation = exports.tsTypeAnnotation = exports.TSTypeAnnotation = TSTypeAnnotation; -exports.tSTypeParameterInstantiation = exports.tsTypeParameterInstantiation = exports.TSTypeParameterInstantiation = TSTypeParameterInstantiation; -exports.tSTypeParameterDeclaration = exports.tsTypeParameterDeclaration = exports.TSTypeParameterDeclaration = TSTypeParameterDeclaration; -exports.tSTypeParameter = exports.tsTypeParameter = exports.TSTypeParameter = TSTypeParameter; -exports.numberLiteral = exports.NumberLiteral = NumberLiteral; -exports.regexLiteral = exports.RegexLiteral = RegexLiteral; -exports.restProperty = exports.RestProperty = RestProperty; -exports.spreadProperty = exports.SpreadProperty = SpreadProperty; - -var _builder = _interopRequireDefault(require("../builder")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function ArrayExpression() { - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - return _builder.default.apply(void 0, ["ArrayExpression"].concat(args)); -} - -function AssignmentExpression() { - for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - args[_key2] = arguments[_key2]; - } - - return _builder.default.apply(void 0, ["AssignmentExpression"].concat(args)); -} - -function BinaryExpression() { - for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { - args[_key3] = arguments[_key3]; - } - - return _builder.default.apply(void 0, ["BinaryExpression"].concat(args)); -} - -function Directive() { - for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { - args[_key4] = arguments[_key4]; - } - - return _builder.default.apply(void 0, ["Directive"].concat(args)); -} - -function DirectiveLiteral() { - for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { - args[_key5] = arguments[_key5]; - } - - return _builder.default.apply(void 0, ["DirectiveLiteral"].concat(args)); -} - -function BlockStatement() { - for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { - args[_key6] = arguments[_key6]; - } - - return _builder.default.apply(void 0, ["BlockStatement"].concat(args)); -} - -function BreakStatement() { - for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) { - args[_key7] = arguments[_key7]; - } - - return _builder.default.apply(void 0, ["BreakStatement"].concat(args)); -} - -function CallExpression() { - for (var _len8 = arguments.length, args = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) { - args[_key8] = arguments[_key8]; - } - - return _builder.default.apply(void 0, ["CallExpression"].concat(args)); -} - -function CatchClause() { - for (var _len9 = arguments.length, args = new Array(_len9), _key9 = 0; _key9 < _len9; _key9++) { - args[_key9] = arguments[_key9]; - } - - return _builder.default.apply(void 0, ["CatchClause"].concat(args)); -} - -function ConditionalExpression() { - for (var _len10 = arguments.length, args = new Array(_len10), _key10 = 0; _key10 < _len10; _key10++) { - args[_key10] = arguments[_key10]; - } - - return _builder.default.apply(void 0, ["ConditionalExpression"].concat(args)); -} - -function ContinueStatement() { - for (var _len11 = arguments.length, args = new Array(_len11), _key11 = 0; _key11 < _len11; _key11++) { - args[_key11] = arguments[_key11]; - } - - return _builder.default.apply(void 0, ["ContinueStatement"].concat(args)); -} - -function DebuggerStatement() { - for (var _len12 = arguments.length, args = new Array(_len12), _key12 = 0; _key12 < _len12; _key12++) { - args[_key12] = arguments[_key12]; - } - - return _builder.default.apply(void 0, ["DebuggerStatement"].concat(args)); -} - -function DoWhileStatement() { - for (var _len13 = arguments.length, args = new Array(_len13), _key13 = 0; _key13 < _len13; _key13++) { - args[_key13] = arguments[_key13]; - } - - return _builder.default.apply(void 0, ["DoWhileStatement"].concat(args)); -} - -function EmptyStatement() { - for (var _len14 = arguments.length, args = new Array(_len14), _key14 = 0; _key14 < _len14; _key14++) { - args[_key14] = arguments[_key14]; - } - - return _builder.default.apply(void 0, ["EmptyStatement"].concat(args)); -} - -function ExpressionStatement() { - for (var _len15 = arguments.length, args = new Array(_len15), _key15 = 0; _key15 < _len15; _key15++) { - args[_key15] = arguments[_key15]; - } - - return _builder.default.apply(void 0, ["ExpressionStatement"].concat(args)); -} - -function File() { - for (var _len16 = arguments.length, args = new Array(_len16), _key16 = 0; _key16 < _len16; _key16++) { - args[_key16] = arguments[_key16]; - } - - return _builder.default.apply(void 0, ["File"].concat(args)); -} - -function ForInStatement() { - for (var _len17 = arguments.length, args = new Array(_len17), _key17 = 0; _key17 < _len17; _key17++) { - args[_key17] = arguments[_key17]; - } - - return _builder.default.apply(void 0, ["ForInStatement"].concat(args)); -} - -function ForStatement() { - for (var _len18 = arguments.length, args = new Array(_len18), _key18 = 0; _key18 < _len18; _key18++) { - args[_key18] = arguments[_key18]; - } - - return _builder.default.apply(void 0, ["ForStatement"].concat(args)); -} - -function FunctionDeclaration() { - for (var _len19 = arguments.length, args = new Array(_len19), _key19 = 0; _key19 < _len19; _key19++) { - args[_key19] = arguments[_key19]; - } - - return _builder.default.apply(void 0, ["FunctionDeclaration"].concat(args)); -} - -function FunctionExpression() { - for (var _len20 = arguments.length, args = new Array(_len20), _key20 = 0; _key20 < _len20; _key20++) { - args[_key20] = arguments[_key20]; - } - - return _builder.default.apply(void 0, ["FunctionExpression"].concat(args)); -} - -function Identifier() { - for (var _len21 = arguments.length, args = new Array(_len21), _key21 = 0; _key21 < _len21; _key21++) { - args[_key21] = arguments[_key21]; - } - - return _builder.default.apply(void 0, ["Identifier"].concat(args)); -} - -function IfStatement() { - for (var _len22 = arguments.length, args = new Array(_len22), _key22 = 0; _key22 < _len22; _key22++) { - args[_key22] = arguments[_key22]; - } - - return _builder.default.apply(void 0, ["IfStatement"].concat(args)); -} - -function LabeledStatement() { - for (var _len23 = arguments.length, args = new Array(_len23), _key23 = 0; _key23 < _len23; _key23++) { - args[_key23] = arguments[_key23]; - } - - return _builder.default.apply(void 0, ["LabeledStatement"].concat(args)); -} - -function StringLiteral() { - for (var _len24 = arguments.length, args = new Array(_len24), _key24 = 0; _key24 < _len24; _key24++) { - args[_key24] = arguments[_key24]; - } - - return _builder.default.apply(void 0, ["StringLiteral"].concat(args)); -} - -function NumericLiteral() { - for (var _len25 = arguments.length, args = new Array(_len25), _key25 = 0; _key25 < _len25; _key25++) { - args[_key25] = arguments[_key25]; - } - - return _builder.default.apply(void 0, ["NumericLiteral"].concat(args)); -} - -function NullLiteral() { - for (var _len26 = arguments.length, args = new Array(_len26), _key26 = 0; _key26 < _len26; _key26++) { - args[_key26] = arguments[_key26]; - } - - return _builder.default.apply(void 0, ["NullLiteral"].concat(args)); -} - -function BooleanLiteral() { - for (var _len27 = arguments.length, args = new Array(_len27), _key27 = 0; _key27 < _len27; _key27++) { - args[_key27] = arguments[_key27]; - } - - return _builder.default.apply(void 0, ["BooleanLiteral"].concat(args)); -} - -function RegExpLiteral() { - for (var _len28 = arguments.length, args = new Array(_len28), _key28 = 0; _key28 < _len28; _key28++) { - args[_key28] = arguments[_key28]; - } - - return _builder.default.apply(void 0, ["RegExpLiteral"].concat(args)); -} - -function LogicalExpression() { - for (var _len29 = arguments.length, args = new Array(_len29), _key29 = 0; _key29 < _len29; _key29++) { - args[_key29] = arguments[_key29]; - } - - return _builder.default.apply(void 0, ["LogicalExpression"].concat(args)); -} - -function MemberExpression() { - for (var _len30 = arguments.length, args = new Array(_len30), _key30 = 0; _key30 < _len30; _key30++) { - args[_key30] = arguments[_key30]; - } - - return _builder.default.apply(void 0, ["MemberExpression"].concat(args)); -} - -function NewExpression() { - for (var _len31 = arguments.length, args = new Array(_len31), _key31 = 0; _key31 < _len31; _key31++) { - args[_key31] = arguments[_key31]; - } - - return _builder.default.apply(void 0, ["NewExpression"].concat(args)); -} - -function Program() { - for (var _len32 = arguments.length, args = new Array(_len32), _key32 = 0; _key32 < _len32; _key32++) { - args[_key32] = arguments[_key32]; - } - - return _builder.default.apply(void 0, ["Program"].concat(args)); -} - -function ObjectExpression() { - for (var _len33 = arguments.length, args = new Array(_len33), _key33 = 0; _key33 < _len33; _key33++) { - args[_key33] = arguments[_key33]; - } - - return _builder.default.apply(void 0, ["ObjectExpression"].concat(args)); -} - -function ObjectMethod() { - for (var _len34 = arguments.length, args = new Array(_len34), _key34 = 0; _key34 < _len34; _key34++) { - args[_key34] = arguments[_key34]; - } - - return _builder.default.apply(void 0, ["ObjectMethod"].concat(args)); -} - -function ObjectProperty() { - for (var _len35 = arguments.length, args = new Array(_len35), _key35 = 0; _key35 < _len35; _key35++) { - args[_key35] = arguments[_key35]; - } - - return _builder.default.apply(void 0, ["ObjectProperty"].concat(args)); -} - -function RestElement() { - for (var _len36 = arguments.length, args = new Array(_len36), _key36 = 0; _key36 < _len36; _key36++) { - args[_key36] = arguments[_key36]; - } - - return _builder.default.apply(void 0, ["RestElement"].concat(args)); -} - -function ReturnStatement() { - for (var _len37 = arguments.length, args = new Array(_len37), _key37 = 0; _key37 < _len37; _key37++) { - args[_key37] = arguments[_key37]; - } - - return _builder.default.apply(void 0, ["ReturnStatement"].concat(args)); -} - -function SequenceExpression() { - for (var _len38 = arguments.length, args = new Array(_len38), _key38 = 0; _key38 < _len38; _key38++) { - args[_key38] = arguments[_key38]; - } - - return _builder.default.apply(void 0, ["SequenceExpression"].concat(args)); -} - -function SwitchCase() { - for (var _len39 = arguments.length, args = new Array(_len39), _key39 = 0; _key39 < _len39; _key39++) { - args[_key39] = arguments[_key39]; - } - - return _builder.default.apply(void 0, ["SwitchCase"].concat(args)); -} - -function SwitchStatement() { - for (var _len40 = arguments.length, args = new Array(_len40), _key40 = 0; _key40 < _len40; _key40++) { - args[_key40] = arguments[_key40]; - } - - return _builder.default.apply(void 0, ["SwitchStatement"].concat(args)); -} - -function ThisExpression() { - for (var _len41 = arguments.length, args = new Array(_len41), _key41 = 0; _key41 < _len41; _key41++) { - args[_key41] = arguments[_key41]; - } - - return _builder.default.apply(void 0, ["ThisExpression"].concat(args)); -} - -function ThrowStatement() { - for (var _len42 = arguments.length, args = new Array(_len42), _key42 = 0; _key42 < _len42; _key42++) { - args[_key42] = arguments[_key42]; - } - - return _builder.default.apply(void 0, ["ThrowStatement"].concat(args)); -} - -function TryStatement() { - for (var _len43 = arguments.length, args = new Array(_len43), _key43 = 0; _key43 < _len43; _key43++) { - args[_key43] = arguments[_key43]; - } - - return _builder.default.apply(void 0, ["TryStatement"].concat(args)); -} - -function UnaryExpression() { - for (var _len44 = arguments.length, args = new Array(_len44), _key44 = 0; _key44 < _len44; _key44++) { - args[_key44] = arguments[_key44]; - } - - return _builder.default.apply(void 0, ["UnaryExpression"].concat(args)); -} - -function UpdateExpression() { - for (var _len45 = arguments.length, args = new Array(_len45), _key45 = 0; _key45 < _len45; _key45++) { - args[_key45] = arguments[_key45]; - } - - return _builder.default.apply(void 0, ["UpdateExpression"].concat(args)); -} - -function VariableDeclaration() { - for (var _len46 = arguments.length, args = new Array(_len46), _key46 = 0; _key46 < _len46; _key46++) { - args[_key46] = arguments[_key46]; - } - - return _builder.default.apply(void 0, ["VariableDeclaration"].concat(args)); -} - -function VariableDeclarator() { - for (var _len47 = arguments.length, args = new Array(_len47), _key47 = 0; _key47 < _len47; _key47++) { - args[_key47] = arguments[_key47]; - } - - return _builder.default.apply(void 0, ["VariableDeclarator"].concat(args)); -} - -function WhileStatement() { - for (var _len48 = arguments.length, args = new Array(_len48), _key48 = 0; _key48 < _len48; _key48++) { - args[_key48] = arguments[_key48]; - } - - return _builder.default.apply(void 0, ["WhileStatement"].concat(args)); -} - -function WithStatement() { - for (var _len49 = arguments.length, args = new Array(_len49), _key49 = 0; _key49 < _len49; _key49++) { - args[_key49] = arguments[_key49]; - } - - return _builder.default.apply(void 0, ["WithStatement"].concat(args)); -} - -function AssignmentPattern() { - for (var _len50 = arguments.length, args = new Array(_len50), _key50 = 0; _key50 < _len50; _key50++) { - args[_key50] = arguments[_key50]; - } - - return _builder.default.apply(void 0, ["AssignmentPattern"].concat(args)); -} - -function ArrayPattern() { - for (var _len51 = arguments.length, args = new Array(_len51), _key51 = 0; _key51 < _len51; _key51++) { - args[_key51] = arguments[_key51]; - } - - return _builder.default.apply(void 0, ["ArrayPattern"].concat(args)); -} - -function ArrowFunctionExpression() { - for (var _len52 = arguments.length, args = new Array(_len52), _key52 = 0; _key52 < _len52; _key52++) { - args[_key52] = arguments[_key52]; - } - - return _builder.default.apply(void 0, ["ArrowFunctionExpression"].concat(args)); -} - -function ClassBody() { - for (var _len53 = arguments.length, args = new Array(_len53), _key53 = 0; _key53 < _len53; _key53++) { - args[_key53] = arguments[_key53]; - } - - return _builder.default.apply(void 0, ["ClassBody"].concat(args)); -} - -function ClassDeclaration() { - for (var _len54 = arguments.length, args = new Array(_len54), _key54 = 0; _key54 < _len54; _key54++) { - args[_key54] = arguments[_key54]; - } - - return _builder.default.apply(void 0, ["ClassDeclaration"].concat(args)); -} - -function ClassExpression() { - for (var _len55 = arguments.length, args = new Array(_len55), _key55 = 0; _key55 < _len55; _key55++) { - args[_key55] = arguments[_key55]; - } - - return _builder.default.apply(void 0, ["ClassExpression"].concat(args)); -} - -function ExportAllDeclaration() { - for (var _len56 = arguments.length, args = new Array(_len56), _key56 = 0; _key56 < _len56; _key56++) { - args[_key56] = arguments[_key56]; - } - - return _builder.default.apply(void 0, ["ExportAllDeclaration"].concat(args)); -} - -function ExportDefaultDeclaration() { - for (var _len57 = arguments.length, args = new Array(_len57), _key57 = 0; _key57 < _len57; _key57++) { - args[_key57] = arguments[_key57]; - } - - return _builder.default.apply(void 0, ["ExportDefaultDeclaration"].concat(args)); -} - -function ExportNamedDeclaration() { - for (var _len58 = arguments.length, args = new Array(_len58), _key58 = 0; _key58 < _len58; _key58++) { - args[_key58] = arguments[_key58]; - } - - return _builder.default.apply(void 0, ["ExportNamedDeclaration"].concat(args)); -} - -function ExportSpecifier() { - for (var _len59 = arguments.length, args = new Array(_len59), _key59 = 0; _key59 < _len59; _key59++) { - args[_key59] = arguments[_key59]; - } - - return _builder.default.apply(void 0, ["ExportSpecifier"].concat(args)); -} - -function ForOfStatement() { - for (var _len60 = arguments.length, args = new Array(_len60), _key60 = 0; _key60 < _len60; _key60++) { - args[_key60] = arguments[_key60]; - } - - return _builder.default.apply(void 0, ["ForOfStatement"].concat(args)); -} - -function ImportDeclaration() { - for (var _len61 = arguments.length, args = new Array(_len61), _key61 = 0; _key61 < _len61; _key61++) { - args[_key61] = arguments[_key61]; - } - - return _builder.default.apply(void 0, ["ImportDeclaration"].concat(args)); -} - -function ImportDefaultSpecifier() { - for (var _len62 = arguments.length, args = new Array(_len62), _key62 = 0; _key62 < _len62; _key62++) { - args[_key62] = arguments[_key62]; - } - - return _builder.default.apply(void 0, ["ImportDefaultSpecifier"].concat(args)); -} - -function ImportNamespaceSpecifier() { - for (var _len63 = arguments.length, args = new Array(_len63), _key63 = 0; _key63 < _len63; _key63++) { - args[_key63] = arguments[_key63]; - } - - return _builder.default.apply(void 0, ["ImportNamespaceSpecifier"].concat(args)); -} - -function ImportSpecifier() { - for (var _len64 = arguments.length, args = new Array(_len64), _key64 = 0; _key64 < _len64; _key64++) { - args[_key64] = arguments[_key64]; - } - - return _builder.default.apply(void 0, ["ImportSpecifier"].concat(args)); -} - -function MetaProperty() { - for (var _len65 = arguments.length, args = new Array(_len65), _key65 = 0; _key65 < _len65; _key65++) { - args[_key65] = arguments[_key65]; - } - - return _builder.default.apply(void 0, ["MetaProperty"].concat(args)); -} - -function ClassMethod() { - for (var _len66 = arguments.length, args = new Array(_len66), _key66 = 0; _key66 < _len66; _key66++) { - args[_key66] = arguments[_key66]; - } - - return _builder.default.apply(void 0, ["ClassMethod"].concat(args)); -} - -function ObjectPattern() { - for (var _len67 = arguments.length, args = new Array(_len67), _key67 = 0; _key67 < _len67; _key67++) { - args[_key67] = arguments[_key67]; - } - - return _builder.default.apply(void 0, ["ObjectPattern"].concat(args)); -} - -function SpreadElement() { - for (var _len68 = arguments.length, args = new Array(_len68), _key68 = 0; _key68 < _len68; _key68++) { - args[_key68] = arguments[_key68]; - } - - return _builder.default.apply(void 0, ["SpreadElement"].concat(args)); -} - -function Super() { - for (var _len69 = arguments.length, args = new Array(_len69), _key69 = 0; _key69 < _len69; _key69++) { - args[_key69] = arguments[_key69]; - } - - return _builder.default.apply(void 0, ["Super"].concat(args)); -} - -function TaggedTemplateExpression() { - for (var _len70 = arguments.length, args = new Array(_len70), _key70 = 0; _key70 < _len70; _key70++) { - args[_key70] = arguments[_key70]; - } - - return _builder.default.apply(void 0, ["TaggedTemplateExpression"].concat(args)); -} - -function TemplateElement() { - for (var _len71 = arguments.length, args = new Array(_len71), _key71 = 0; _key71 < _len71; _key71++) { - args[_key71] = arguments[_key71]; - } - - return _builder.default.apply(void 0, ["TemplateElement"].concat(args)); -} - -function TemplateLiteral() { - for (var _len72 = arguments.length, args = new Array(_len72), _key72 = 0; _key72 < _len72; _key72++) { - args[_key72] = arguments[_key72]; - } - - return _builder.default.apply(void 0, ["TemplateLiteral"].concat(args)); -} - -function YieldExpression() { - for (var _len73 = arguments.length, args = new Array(_len73), _key73 = 0; _key73 < _len73; _key73++) { - args[_key73] = arguments[_key73]; - } - - return _builder.default.apply(void 0, ["YieldExpression"].concat(args)); -} - -function AnyTypeAnnotation() { - for (var _len74 = arguments.length, args = new Array(_len74), _key74 = 0; _key74 < _len74; _key74++) { - args[_key74] = arguments[_key74]; - } - - return _builder.default.apply(void 0, ["AnyTypeAnnotation"].concat(args)); -} - -function ArrayTypeAnnotation() { - for (var _len75 = arguments.length, args = new Array(_len75), _key75 = 0; _key75 < _len75; _key75++) { - args[_key75] = arguments[_key75]; - } - - return _builder.default.apply(void 0, ["ArrayTypeAnnotation"].concat(args)); -} - -function BooleanTypeAnnotation() { - for (var _len76 = arguments.length, args = new Array(_len76), _key76 = 0; _key76 < _len76; _key76++) { - args[_key76] = arguments[_key76]; - } - - return _builder.default.apply(void 0, ["BooleanTypeAnnotation"].concat(args)); -} - -function BooleanLiteralTypeAnnotation() { - for (var _len77 = arguments.length, args = new Array(_len77), _key77 = 0; _key77 < _len77; _key77++) { - args[_key77] = arguments[_key77]; - } - - return _builder.default.apply(void 0, ["BooleanLiteralTypeAnnotation"].concat(args)); -} - -function NullLiteralTypeAnnotation() { - for (var _len78 = arguments.length, args = new Array(_len78), _key78 = 0; _key78 < _len78; _key78++) { - args[_key78] = arguments[_key78]; - } - - return _builder.default.apply(void 0, ["NullLiteralTypeAnnotation"].concat(args)); -} - -function ClassImplements() { - for (var _len79 = arguments.length, args = new Array(_len79), _key79 = 0; _key79 < _len79; _key79++) { - args[_key79] = arguments[_key79]; - } - - return _builder.default.apply(void 0, ["ClassImplements"].concat(args)); -} - -function DeclareClass() { - for (var _len80 = arguments.length, args = new Array(_len80), _key80 = 0; _key80 < _len80; _key80++) { - args[_key80] = arguments[_key80]; - } - - return _builder.default.apply(void 0, ["DeclareClass"].concat(args)); -} - -function DeclareFunction() { - for (var _len81 = arguments.length, args = new Array(_len81), _key81 = 0; _key81 < _len81; _key81++) { - args[_key81] = arguments[_key81]; - } - - return _builder.default.apply(void 0, ["DeclareFunction"].concat(args)); -} - -function DeclareInterface() { - for (var _len82 = arguments.length, args = new Array(_len82), _key82 = 0; _key82 < _len82; _key82++) { - args[_key82] = arguments[_key82]; - } - - return _builder.default.apply(void 0, ["DeclareInterface"].concat(args)); -} - -function DeclareModule() { - for (var _len83 = arguments.length, args = new Array(_len83), _key83 = 0; _key83 < _len83; _key83++) { - args[_key83] = arguments[_key83]; - } - - return _builder.default.apply(void 0, ["DeclareModule"].concat(args)); -} - -function DeclareModuleExports() { - for (var _len84 = arguments.length, args = new Array(_len84), _key84 = 0; _key84 < _len84; _key84++) { - args[_key84] = arguments[_key84]; - } - - return _builder.default.apply(void 0, ["DeclareModuleExports"].concat(args)); -} - -function DeclareTypeAlias() { - for (var _len85 = arguments.length, args = new Array(_len85), _key85 = 0; _key85 < _len85; _key85++) { - args[_key85] = arguments[_key85]; - } - - return _builder.default.apply(void 0, ["DeclareTypeAlias"].concat(args)); -} - -function DeclareOpaqueType() { - for (var _len86 = arguments.length, args = new Array(_len86), _key86 = 0; _key86 < _len86; _key86++) { - args[_key86] = arguments[_key86]; - } - - return _builder.default.apply(void 0, ["DeclareOpaqueType"].concat(args)); -} - -function DeclareVariable() { - for (var _len87 = arguments.length, args = new Array(_len87), _key87 = 0; _key87 < _len87; _key87++) { - args[_key87] = arguments[_key87]; - } - - return _builder.default.apply(void 0, ["DeclareVariable"].concat(args)); -} - -function DeclareExportDeclaration() { - for (var _len88 = arguments.length, args = new Array(_len88), _key88 = 0; _key88 < _len88; _key88++) { - args[_key88] = arguments[_key88]; - } - - return _builder.default.apply(void 0, ["DeclareExportDeclaration"].concat(args)); -} - -function DeclareExportAllDeclaration() { - for (var _len89 = arguments.length, args = new Array(_len89), _key89 = 0; _key89 < _len89; _key89++) { - args[_key89] = arguments[_key89]; - } - - return _builder.default.apply(void 0, ["DeclareExportAllDeclaration"].concat(args)); -} - -function DeclaredPredicate() { - for (var _len90 = arguments.length, args = new Array(_len90), _key90 = 0; _key90 < _len90; _key90++) { - args[_key90] = arguments[_key90]; - } - - return _builder.default.apply(void 0, ["DeclaredPredicate"].concat(args)); -} - -function ExistsTypeAnnotation() { - for (var _len91 = arguments.length, args = new Array(_len91), _key91 = 0; _key91 < _len91; _key91++) { - args[_key91] = arguments[_key91]; - } - - return _builder.default.apply(void 0, ["ExistsTypeAnnotation"].concat(args)); -} - -function FunctionTypeAnnotation() { - for (var _len92 = arguments.length, args = new Array(_len92), _key92 = 0; _key92 < _len92; _key92++) { - args[_key92] = arguments[_key92]; - } - - return _builder.default.apply(void 0, ["FunctionTypeAnnotation"].concat(args)); -} - -function FunctionTypeParam() { - for (var _len93 = arguments.length, args = new Array(_len93), _key93 = 0; _key93 < _len93; _key93++) { - args[_key93] = arguments[_key93]; - } - - return _builder.default.apply(void 0, ["FunctionTypeParam"].concat(args)); -} - -function GenericTypeAnnotation() { - for (var _len94 = arguments.length, args = new Array(_len94), _key94 = 0; _key94 < _len94; _key94++) { - args[_key94] = arguments[_key94]; - } - - return _builder.default.apply(void 0, ["GenericTypeAnnotation"].concat(args)); -} - -function InferredPredicate() { - for (var _len95 = arguments.length, args = new Array(_len95), _key95 = 0; _key95 < _len95; _key95++) { - args[_key95] = arguments[_key95]; - } - - return _builder.default.apply(void 0, ["InferredPredicate"].concat(args)); -} - -function InterfaceExtends() { - for (var _len96 = arguments.length, args = new Array(_len96), _key96 = 0; _key96 < _len96; _key96++) { - args[_key96] = arguments[_key96]; - } - - return _builder.default.apply(void 0, ["InterfaceExtends"].concat(args)); -} - -function InterfaceDeclaration() { - for (var _len97 = arguments.length, args = new Array(_len97), _key97 = 0; _key97 < _len97; _key97++) { - args[_key97] = arguments[_key97]; - } - - return _builder.default.apply(void 0, ["InterfaceDeclaration"].concat(args)); -} - -function IntersectionTypeAnnotation() { - for (var _len98 = arguments.length, args = new Array(_len98), _key98 = 0; _key98 < _len98; _key98++) { - args[_key98] = arguments[_key98]; - } - - return _builder.default.apply(void 0, ["IntersectionTypeAnnotation"].concat(args)); -} - -function MixedTypeAnnotation() { - for (var _len99 = arguments.length, args = new Array(_len99), _key99 = 0; _key99 < _len99; _key99++) { - args[_key99] = arguments[_key99]; - } - - return _builder.default.apply(void 0, ["MixedTypeAnnotation"].concat(args)); -} - -function EmptyTypeAnnotation() { - for (var _len100 = arguments.length, args = new Array(_len100), _key100 = 0; _key100 < _len100; _key100++) { - args[_key100] = arguments[_key100]; - } - - return _builder.default.apply(void 0, ["EmptyTypeAnnotation"].concat(args)); -} - -function NullableTypeAnnotation() { - for (var _len101 = arguments.length, args = new Array(_len101), _key101 = 0; _key101 < _len101; _key101++) { - args[_key101] = arguments[_key101]; - } - - return _builder.default.apply(void 0, ["NullableTypeAnnotation"].concat(args)); -} - -function NumberLiteralTypeAnnotation() { - for (var _len102 = arguments.length, args = new Array(_len102), _key102 = 0; _key102 < _len102; _key102++) { - args[_key102] = arguments[_key102]; - } - - return _builder.default.apply(void 0, ["NumberLiteralTypeAnnotation"].concat(args)); -} - -function NumberTypeAnnotation() { - for (var _len103 = arguments.length, args = new Array(_len103), _key103 = 0; _key103 < _len103; _key103++) { - args[_key103] = arguments[_key103]; - } - - return _builder.default.apply(void 0, ["NumberTypeAnnotation"].concat(args)); -} - -function ObjectTypeAnnotation() { - for (var _len104 = arguments.length, args = new Array(_len104), _key104 = 0; _key104 < _len104; _key104++) { - args[_key104] = arguments[_key104]; - } - - return _builder.default.apply(void 0, ["ObjectTypeAnnotation"].concat(args)); -} - -function ObjectTypeCallProperty() { - for (var _len105 = arguments.length, args = new Array(_len105), _key105 = 0; _key105 < _len105; _key105++) { - args[_key105] = arguments[_key105]; - } - - return _builder.default.apply(void 0, ["ObjectTypeCallProperty"].concat(args)); -} - -function ObjectTypeIndexer() { - for (var _len106 = arguments.length, args = new Array(_len106), _key106 = 0; _key106 < _len106; _key106++) { - args[_key106] = arguments[_key106]; - } - - return _builder.default.apply(void 0, ["ObjectTypeIndexer"].concat(args)); -} - -function ObjectTypeProperty() { - for (var _len107 = arguments.length, args = new Array(_len107), _key107 = 0; _key107 < _len107; _key107++) { - args[_key107] = arguments[_key107]; - } - - return _builder.default.apply(void 0, ["ObjectTypeProperty"].concat(args)); -} - -function ObjectTypeSpreadProperty() { - for (var _len108 = arguments.length, args = new Array(_len108), _key108 = 0; _key108 < _len108; _key108++) { - args[_key108] = arguments[_key108]; - } - - return _builder.default.apply(void 0, ["ObjectTypeSpreadProperty"].concat(args)); -} - -function OpaqueType() { - for (var _len109 = arguments.length, args = new Array(_len109), _key109 = 0; _key109 < _len109; _key109++) { - args[_key109] = arguments[_key109]; - } - - return _builder.default.apply(void 0, ["OpaqueType"].concat(args)); -} - -function QualifiedTypeIdentifier() { - for (var _len110 = arguments.length, args = new Array(_len110), _key110 = 0; _key110 < _len110; _key110++) { - args[_key110] = arguments[_key110]; - } - - return _builder.default.apply(void 0, ["QualifiedTypeIdentifier"].concat(args)); -} - -function StringLiteralTypeAnnotation() { - for (var _len111 = arguments.length, args = new Array(_len111), _key111 = 0; _key111 < _len111; _key111++) { - args[_key111] = arguments[_key111]; - } - - return _builder.default.apply(void 0, ["StringLiteralTypeAnnotation"].concat(args)); -} - -function StringTypeAnnotation() { - for (var _len112 = arguments.length, args = new Array(_len112), _key112 = 0; _key112 < _len112; _key112++) { - args[_key112] = arguments[_key112]; - } - - return _builder.default.apply(void 0, ["StringTypeAnnotation"].concat(args)); -} - -function ThisTypeAnnotation() { - for (var _len113 = arguments.length, args = new Array(_len113), _key113 = 0; _key113 < _len113; _key113++) { - args[_key113] = arguments[_key113]; - } - - return _builder.default.apply(void 0, ["ThisTypeAnnotation"].concat(args)); -} - -function TupleTypeAnnotation() { - for (var _len114 = arguments.length, args = new Array(_len114), _key114 = 0; _key114 < _len114; _key114++) { - args[_key114] = arguments[_key114]; - } - - return _builder.default.apply(void 0, ["TupleTypeAnnotation"].concat(args)); -} - -function TypeofTypeAnnotation() { - for (var _len115 = arguments.length, args = new Array(_len115), _key115 = 0; _key115 < _len115; _key115++) { - args[_key115] = arguments[_key115]; - } - - return _builder.default.apply(void 0, ["TypeofTypeAnnotation"].concat(args)); -} - -function TypeAlias() { - for (var _len116 = arguments.length, args = new Array(_len116), _key116 = 0; _key116 < _len116; _key116++) { - args[_key116] = arguments[_key116]; - } - - return _builder.default.apply(void 0, ["TypeAlias"].concat(args)); -} - -function TypeAnnotation() { - for (var _len117 = arguments.length, args = new Array(_len117), _key117 = 0; _key117 < _len117; _key117++) { - args[_key117] = arguments[_key117]; - } - - return _builder.default.apply(void 0, ["TypeAnnotation"].concat(args)); -} - -function TypeCastExpression() { - for (var _len118 = arguments.length, args = new Array(_len118), _key118 = 0; _key118 < _len118; _key118++) { - args[_key118] = arguments[_key118]; - } - - return _builder.default.apply(void 0, ["TypeCastExpression"].concat(args)); -} - -function TypeParameter() { - for (var _len119 = arguments.length, args = new Array(_len119), _key119 = 0; _key119 < _len119; _key119++) { - args[_key119] = arguments[_key119]; - } - - return _builder.default.apply(void 0, ["TypeParameter"].concat(args)); -} - -function TypeParameterDeclaration() { - for (var _len120 = arguments.length, args = new Array(_len120), _key120 = 0; _key120 < _len120; _key120++) { - args[_key120] = arguments[_key120]; - } - - return _builder.default.apply(void 0, ["TypeParameterDeclaration"].concat(args)); -} - -function TypeParameterInstantiation() { - for (var _len121 = arguments.length, args = new Array(_len121), _key121 = 0; _key121 < _len121; _key121++) { - args[_key121] = arguments[_key121]; - } - - return _builder.default.apply(void 0, ["TypeParameterInstantiation"].concat(args)); -} - -function UnionTypeAnnotation() { - for (var _len122 = arguments.length, args = new Array(_len122), _key122 = 0; _key122 < _len122; _key122++) { - args[_key122] = arguments[_key122]; - } - - return _builder.default.apply(void 0, ["UnionTypeAnnotation"].concat(args)); -} - -function VoidTypeAnnotation() { - for (var _len123 = arguments.length, args = new Array(_len123), _key123 = 0; _key123 < _len123; _key123++) { - args[_key123] = arguments[_key123]; - } - - return _builder.default.apply(void 0, ["VoidTypeAnnotation"].concat(args)); -} - -function JSXAttribute() { - for (var _len124 = arguments.length, args = new Array(_len124), _key124 = 0; _key124 < _len124; _key124++) { - args[_key124] = arguments[_key124]; - } - - return _builder.default.apply(void 0, ["JSXAttribute"].concat(args)); -} - -function JSXClosingElement() { - for (var _len125 = arguments.length, args = new Array(_len125), _key125 = 0; _key125 < _len125; _key125++) { - args[_key125] = arguments[_key125]; - } - - return _builder.default.apply(void 0, ["JSXClosingElement"].concat(args)); -} - -function JSXElement() { - for (var _len126 = arguments.length, args = new Array(_len126), _key126 = 0; _key126 < _len126; _key126++) { - args[_key126] = arguments[_key126]; - } - - return _builder.default.apply(void 0, ["JSXElement"].concat(args)); -} - -function JSXEmptyExpression() { - for (var _len127 = arguments.length, args = new Array(_len127), _key127 = 0; _key127 < _len127; _key127++) { - args[_key127] = arguments[_key127]; - } - - return _builder.default.apply(void 0, ["JSXEmptyExpression"].concat(args)); -} - -function JSXExpressionContainer() { - for (var _len128 = arguments.length, args = new Array(_len128), _key128 = 0; _key128 < _len128; _key128++) { - args[_key128] = arguments[_key128]; - } - - return _builder.default.apply(void 0, ["JSXExpressionContainer"].concat(args)); -} - -function JSXSpreadChild() { - for (var _len129 = arguments.length, args = new Array(_len129), _key129 = 0; _key129 < _len129; _key129++) { - args[_key129] = arguments[_key129]; - } - - return _builder.default.apply(void 0, ["JSXSpreadChild"].concat(args)); -} - -function JSXIdentifier() { - for (var _len130 = arguments.length, args = new Array(_len130), _key130 = 0; _key130 < _len130; _key130++) { - args[_key130] = arguments[_key130]; - } - - return _builder.default.apply(void 0, ["JSXIdentifier"].concat(args)); -} - -function JSXMemberExpression() { - for (var _len131 = arguments.length, args = new Array(_len131), _key131 = 0; _key131 < _len131; _key131++) { - args[_key131] = arguments[_key131]; - } - - return _builder.default.apply(void 0, ["JSXMemberExpression"].concat(args)); -} - -function JSXNamespacedName() { - for (var _len132 = arguments.length, args = new Array(_len132), _key132 = 0; _key132 < _len132; _key132++) { - args[_key132] = arguments[_key132]; - } - - return _builder.default.apply(void 0, ["JSXNamespacedName"].concat(args)); -} - -function JSXOpeningElement() { - for (var _len133 = arguments.length, args = new Array(_len133), _key133 = 0; _key133 < _len133; _key133++) { - args[_key133] = arguments[_key133]; - } - - return _builder.default.apply(void 0, ["JSXOpeningElement"].concat(args)); -} - -function JSXSpreadAttribute() { - for (var _len134 = arguments.length, args = new Array(_len134), _key134 = 0; _key134 < _len134; _key134++) { - args[_key134] = arguments[_key134]; - } - - return _builder.default.apply(void 0, ["JSXSpreadAttribute"].concat(args)); -} - -function JSXText() { - for (var _len135 = arguments.length, args = new Array(_len135), _key135 = 0; _key135 < _len135; _key135++) { - args[_key135] = arguments[_key135]; - } - - return _builder.default.apply(void 0, ["JSXText"].concat(args)); -} - -function JSXFragment() { - for (var _len136 = arguments.length, args = new Array(_len136), _key136 = 0; _key136 < _len136; _key136++) { - args[_key136] = arguments[_key136]; - } - - return _builder.default.apply(void 0, ["JSXFragment"].concat(args)); -} - -function JSXOpeningFragment() { - for (var _len137 = arguments.length, args = new Array(_len137), _key137 = 0; _key137 < _len137; _key137++) { - args[_key137] = arguments[_key137]; - } - - return _builder.default.apply(void 0, ["JSXOpeningFragment"].concat(args)); -} - -function JSXClosingFragment() { - for (var _len138 = arguments.length, args = new Array(_len138), _key138 = 0; _key138 < _len138; _key138++) { - args[_key138] = arguments[_key138]; - } - - return _builder.default.apply(void 0, ["JSXClosingFragment"].concat(args)); -} - -function Noop() { - for (var _len139 = arguments.length, args = new Array(_len139), _key139 = 0; _key139 < _len139; _key139++) { - args[_key139] = arguments[_key139]; - } - - return _builder.default.apply(void 0, ["Noop"].concat(args)); -} - -function ParenthesizedExpression() { - for (var _len140 = arguments.length, args = new Array(_len140), _key140 = 0; _key140 < _len140; _key140++) { - args[_key140] = arguments[_key140]; - } - - return _builder.default.apply(void 0, ["ParenthesizedExpression"].concat(args)); -} - -function AwaitExpression() { - for (var _len141 = arguments.length, args = new Array(_len141), _key141 = 0; _key141 < _len141; _key141++) { - args[_key141] = arguments[_key141]; - } - - return _builder.default.apply(void 0, ["AwaitExpression"].concat(args)); -} - -function BindExpression() { - for (var _len142 = arguments.length, args = new Array(_len142), _key142 = 0; _key142 < _len142; _key142++) { - args[_key142] = arguments[_key142]; - } - - return _builder.default.apply(void 0, ["BindExpression"].concat(args)); -} - -function ClassProperty() { - for (var _len143 = arguments.length, args = new Array(_len143), _key143 = 0; _key143 < _len143; _key143++) { - args[_key143] = arguments[_key143]; - } - - return _builder.default.apply(void 0, ["ClassProperty"].concat(args)); -} - -function Import() { - for (var _len144 = arguments.length, args = new Array(_len144), _key144 = 0; _key144 < _len144; _key144++) { - args[_key144] = arguments[_key144]; - } - - return _builder.default.apply(void 0, ["Import"].concat(args)); -} - -function Decorator() { - for (var _len145 = arguments.length, args = new Array(_len145), _key145 = 0; _key145 < _len145; _key145++) { - args[_key145] = arguments[_key145]; - } - - return _builder.default.apply(void 0, ["Decorator"].concat(args)); -} - -function DoExpression() { - for (var _len146 = arguments.length, args = new Array(_len146), _key146 = 0; _key146 < _len146; _key146++) { - args[_key146] = arguments[_key146]; - } - - return _builder.default.apply(void 0, ["DoExpression"].concat(args)); -} - -function ExportDefaultSpecifier() { - for (var _len147 = arguments.length, args = new Array(_len147), _key147 = 0; _key147 < _len147; _key147++) { - args[_key147] = arguments[_key147]; - } - - return _builder.default.apply(void 0, ["ExportDefaultSpecifier"].concat(args)); -} - -function ExportNamespaceSpecifier() { - for (var _len148 = arguments.length, args = new Array(_len148), _key148 = 0; _key148 < _len148; _key148++) { - args[_key148] = arguments[_key148]; - } - - return _builder.default.apply(void 0, ["ExportNamespaceSpecifier"].concat(args)); -} - -function TSParameterProperty() { - for (var _len149 = arguments.length, args = new Array(_len149), _key149 = 0; _key149 < _len149; _key149++) { - args[_key149] = arguments[_key149]; - } - - return _builder.default.apply(void 0, ["TSParameterProperty"].concat(args)); -} - -function TSDeclareFunction() { - for (var _len150 = arguments.length, args = new Array(_len150), _key150 = 0; _key150 < _len150; _key150++) { - args[_key150] = arguments[_key150]; - } - - return _builder.default.apply(void 0, ["TSDeclareFunction"].concat(args)); -} - -function TSDeclareMethod() { - for (var _len151 = arguments.length, args = new Array(_len151), _key151 = 0; _key151 < _len151; _key151++) { - args[_key151] = arguments[_key151]; - } - - return _builder.default.apply(void 0, ["TSDeclareMethod"].concat(args)); -} - -function TSQualifiedName() { - for (var _len152 = arguments.length, args = new Array(_len152), _key152 = 0; _key152 < _len152; _key152++) { - args[_key152] = arguments[_key152]; - } - - return _builder.default.apply(void 0, ["TSQualifiedName"].concat(args)); -} - -function TSCallSignatureDeclaration() { - for (var _len153 = arguments.length, args = new Array(_len153), _key153 = 0; _key153 < _len153; _key153++) { - args[_key153] = arguments[_key153]; - } - - return _builder.default.apply(void 0, ["TSCallSignatureDeclaration"].concat(args)); -} - -function TSConstructSignatureDeclaration() { - for (var _len154 = arguments.length, args = new Array(_len154), _key154 = 0; _key154 < _len154; _key154++) { - args[_key154] = arguments[_key154]; - } - - return _builder.default.apply(void 0, ["TSConstructSignatureDeclaration"].concat(args)); -} - -function TSPropertySignature() { - for (var _len155 = arguments.length, args = new Array(_len155), _key155 = 0; _key155 < _len155; _key155++) { - args[_key155] = arguments[_key155]; - } - - return _builder.default.apply(void 0, ["TSPropertySignature"].concat(args)); -} - -function TSMethodSignature() { - for (var _len156 = arguments.length, args = new Array(_len156), _key156 = 0; _key156 < _len156; _key156++) { - args[_key156] = arguments[_key156]; - } - - return _builder.default.apply(void 0, ["TSMethodSignature"].concat(args)); -} - -function TSIndexSignature() { - for (var _len157 = arguments.length, args = new Array(_len157), _key157 = 0; _key157 < _len157; _key157++) { - args[_key157] = arguments[_key157]; - } - - return _builder.default.apply(void 0, ["TSIndexSignature"].concat(args)); -} - -function TSAnyKeyword() { - for (var _len158 = arguments.length, args = new Array(_len158), _key158 = 0; _key158 < _len158; _key158++) { - args[_key158] = arguments[_key158]; - } - - return _builder.default.apply(void 0, ["TSAnyKeyword"].concat(args)); -} - -function TSNumberKeyword() { - for (var _len159 = arguments.length, args = new Array(_len159), _key159 = 0; _key159 < _len159; _key159++) { - args[_key159] = arguments[_key159]; - } - - return _builder.default.apply(void 0, ["TSNumberKeyword"].concat(args)); -} - -function TSObjectKeyword() { - for (var _len160 = arguments.length, args = new Array(_len160), _key160 = 0; _key160 < _len160; _key160++) { - args[_key160] = arguments[_key160]; - } - - return _builder.default.apply(void 0, ["TSObjectKeyword"].concat(args)); -} - -function TSBooleanKeyword() { - for (var _len161 = arguments.length, args = new Array(_len161), _key161 = 0; _key161 < _len161; _key161++) { - args[_key161] = arguments[_key161]; - } - - return _builder.default.apply(void 0, ["TSBooleanKeyword"].concat(args)); -} - -function TSStringKeyword() { - for (var _len162 = arguments.length, args = new Array(_len162), _key162 = 0; _key162 < _len162; _key162++) { - args[_key162] = arguments[_key162]; - } - - return _builder.default.apply(void 0, ["TSStringKeyword"].concat(args)); -} - -function TSSymbolKeyword() { - for (var _len163 = arguments.length, args = new Array(_len163), _key163 = 0; _key163 < _len163; _key163++) { - args[_key163] = arguments[_key163]; - } - - return _builder.default.apply(void 0, ["TSSymbolKeyword"].concat(args)); -} - -function TSVoidKeyword() { - for (var _len164 = arguments.length, args = new Array(_len164), _key164 = 0; _key164 < _len164; _key164++) { - args[_key164] = arguments[_key164]; - } - - return _builder.default.apply(void 0, ["TSVoidKeyword"].concat(args)); -} - -function TSUndefinedKeyword() { - for (var _len165 = arguments.length, args = new Array(_len165), _key165 = 0; _key165 < _len165; _key165++) { - args[_key165] = arguments[_key165]; - } - - return _builder.default.apply(void 0, ["TSUndefinedKeyword"].concat(args)); -} - -function TSNullKeyword() { - for (var _len166 = arguments.length, args = new Array(_len166), _key166 = 0; _key166 < _len166; _key166++) { - args[_key166] = arguments[_key166]; - } - - return _builder.default.apply(void 0, ["TSNullKeyword"].concat(args)); -} - -function TSNeverKeyword() { - for (var _len167 = arguments.length, args = new Array(_len167), _key167 = 0; _key167 < _len167; _key167++) { - args[_key167] = arguments[_key167]; - } - - return _builder.default.apply(void 0, ["TSNeverKeyword"].concat(args)); -} - -function TSThisType() { - for (var _len168 = arguments.length, args = new Array(_len168), _key168 = 0; _key168 < _len168; _key168++) { - args[_key168] = arguments[_key168]; - } - - return _builder.default.apply(void 0, ["TSThisType"].concat(args)); -} - -function TSFunctionType() { - for (var _len169 = arguments.length, args = new Array(_len169), _key169 = 0; _key169 < _len169; _key169++) { - args[_key169] = arguments[_key169]; - } - - return _builder.default.apply(void 0, ["TSFunctionType"].concat(args)); -} - -function TSConstructorType() { - for (var _len170 = arguments.length, args = new Array(_len170), _key170 = 0; _key170 < _len170; _key170++) { - args[_key170] = arguments[_key170]; - } - - return _builder.default.apply(void 0, ["TSConstructorType"].concat(args)); -} - -function TSTypeReference() { - for (var _len171 = arguments.length, args = new Array(_len171), _key171 = 0; _key171 < _len171; _key171++) { - args[_key171] = arguments[_key171]; - } - - return _builder.default.apply(void 0, ["TSTypeReference"].concat(args)); -} - -function TSTypePredicate() { - for (var _len172 = arguments.length, args = new Array(_len172), _key172 = 0; _key172 < _len172; _key172++) { - args[_key172] = arguments[_key172]; - } - - return _builder.default.apply(void 0, ["TSTypePredicate"].concat(args)); -} - -function TSTypeQuery() { - for (var _len173 = arguments.length, args = new Array(_len173), _key173 = 0; _key173 < _len173; _key173++) { - args[_key173] = arguments[_key173]; - } - - return _builder.default.apply(void 0, ["TSTypeQuery"].concat(args)); -} - -function TSTypeLiteral() { - for (var _len174 = arguments.length, args = new Array(_len174), _key174 = 0; _key174 < _len174; _key174++) { - args[_key174] = arguments[_key174]; - } - - return _builder.default.apply(void 0, ["TSTypeLiteral"].concat(args)); -} - -function TSArrayType() { - for (var _len175 = arguments.length, args = new Array(_len175), _key175 = 0; _key175 < _len175; _key175++) { - args[_key175] = arguments[_key175]; - } - - return _builder.default.apply(void 0, ["TSArrayType"].concat(args)); -} - -function TSTupleType() { - for (var _len176 = arguments.length, args = new Array(_len176), _key176 = 0; _key176 < _len176; _key176++) { - args[_key176] = arguments[_key176]; - } - - return _builder.default.apply(void 0, ["TSTupleType"].concat(args)); -} - -function TSUnionType() { - for (var _len177 = arguments.length, args = new Array(_len177), _key177 = 0; _key177 < _len177; _key177++) { - args[_key177] = arguments[_key177]; - } - - return _builder.default.apply(void 0, ["TSUnionType"].concat(args)); -} - -function TSIntersectionType() { - for (var _len178 = arguments.length, args = new Array(_len178), _key178 = 0; _key178 < _len178; _key178++) { - args[_key178] = arguments[_key178]; - } - - return _builder.default.apply(void 0, ["TSIntersectionType"].concat(args)); -} - -function TSParenthesizedType() { - for (var _len179 = arguments.length, args = new Array(_len179), _key179 = 0; _key179 < _len179; _key179++) { - args[_key179] = arguments[_key179]; - } - - return _builder.default.apply(void 0, ["TSParenthesizedType"].concat(args)); -} - -function TSTypeOperator() { - for (var _len180 = arguments.length, args = new Array(_len180), _key180 = 0; _key180 < _len180; _key180++) { - args[_key180] = arguments[_key180]; - } - - return _builder.default.apply(void 0, ["TSTypeOperator"].concat(args)); -} - -function TSIndexedAccessType() { - for (var _len181 = arguments.length, args = new Array(_len181), _key181 = 0; _key181 < _len181; _key181++) { - args[_key181] = arguments[_key181]; - } - - return _builder.default.apply(void 0, ["TSIndexedAccessType"].concat(args)); -} - -function TSMappedType() { - for (var _len182 = arguments.length, args = new Array(_len182), _key182 = 0; _key182 < _len182; _key182++) { - args[_key182] = arguments[_key182]; - } - - return _builder.default.apply(void 0, ["TSMappedType"].concat(args)); -} - -function TSLiteralType() { - for (var _len183 = arguments.length, args = new Array(_len183), _key183 = 0; _key183 < _len183; _key183++) { - args[_key183] = arguments[_key183]; - } - - return _builder.default.apply(void 0, ["TSLiteralType"].concat(args)); -} - -function TSExpressionWithTypeArguments() { - for (var _len184 = arguments.length, args = new Array(_len184), _key184 = 0; _key184 < _len184; _key184++) { - args[_key184] = arguments[_key184]; - } - - return _builder.default.apply(void 0, ["TSExpressionWithTypeArguments"].concat(args)); -} - -function TSInterfaceDeclaration() { - for (var _len185 = arguments.length, args = new Array(_len185), _key185 = 0; _key185 < _len185; _key185++) { - args[_key185] = arguments[_key185]; - } - - return _builder.default.apply(void 0, ["TSInterfaceDeclaration"].concat(args)); -} - -function TSInterfaceBody() { - for (var _len186 = arguments.length, args = new Array(_len186), _key186 = 0; _key186 < _len186; _key186++) { - args[_key186] = arguments[_key186]; - } - - return _builder.default.apply(void 0, ["TSInterfaceBody"].concat(args)); -} - -function TSTypeAliasDeclaration() { - for (var _len187 = arguments.length, args = new Array(_len187), _key187 = 0; _key187 < _len187; _key187++) { - args[_key187] = arguments[_key187]; - } - - return _builder.default.apply(void 0, ["TSTypeAliasDeclaration"].concat(args)); -} - -function TSAsExpression() { - for (var _len188 = arguments.length, args = new Array(_len188), _key188 = 0; _key188 < _len188; _key188++) { - args[_key188] = arguments[_key188]; - } - - return _builder.default.apply(void 0, ["TSAsExpression"].concat(args)); -} - -function TSTypeAssertion() { - for (var _len189 = arguments.length, args = new Array(_len189), _key189 = 0; _key189 < _len189; _key189++) { - args[_key189] = arguments[_key189]; - } - - return _builder.default.apply(void 0, ["TSTypeAssertion"].concat(args)); -} - -function TSEnumDeclaration() { - for (var _len190 = arguments.length, args = new Array(_len190), _key190 = 0; _key190 < _len190; _key190++) { - args[_key190] = arguments[_key190]; - } - - return _builder.default.apply(void 0, ["TSEnumDeclaration"].concat(args)); -} - -function TSEnumMember() { - for (var _len191 = arguments.length, args = new Array(_len191), _key191 = 0; _key191 < _len191; _key191++) { - args[_key191] = arguments[_key191]; - } - - return _builder.default.apply(void 0, ["TSEnumMember"].concat(args)); -} - -function TSModuleDeclaration() { - for (var _len192 = arguments.length, args = new Array(_len192), _key192 = 0; _key192 < _len192; _key192++) { - args[_key192] = arguments[_key192]; - } - - return _builder.default.apply(void 0, ["TSModuleDeclaration"].concat(args)); -} - -function TSModuleBlock() { - for (var _len193 = arguments.length, args = new Array(_len193), _key193 = 0; _key193 < _len193; _key193++) { - args[_key193] = arguments[_key193]; - } - - return _builder.default.apply(void 0, ["TSModuleBlock"].concat(args)); -} - -function TSImportEqualsDeclaration() { - for (var _len194 = arguments.length, args = new Array(_len194), _key194 = 0; _key194 < _len194; _key194++) { - args[_key194] = arguments[_key194]; - } - - return _builder.default.apply(void 0, ["TSImportEqualsDeclaration"].concat(args)); -} - -function TSExternalModuleReference() { - for (var _len195 = arguments.length, args = new Array(_len195), _key195 = 0; _key195 < _len195; _key195++) { - args[_key195] = arguments[_key195]; - } - - return _builder.default.apply(void 0, ["TSExternalModuleReference"].concat(args)); -} - -function TSNonNullExpression() { - for (var _len196 = arguments.length, args = new Array(_len196), _key196 = 0; _key196 < _len196; _key196++) { - args[_key196] = arguments[_key196]; - } - - return _builder.default.apply(void 0, ["TSNonNullExpression"].concat(args)); -} - -function TSExportAssignment() { - for (var _len197 = arguments.length, args = new Array(_len197), _key197 = 0; _key197 < _len197; _key197++) { - args[_key197] = arguments[_key197]; - } - - return _builder.default.apply(void 0, ["TSExportAssignment"].concat(args)); -} - -function TSNamespaceExportDeclaration() { - for (var _len198 = arguments.length, args = new Array(_len198), _key198 = 0; _key198 < _len198; _key198++) { - args[_key198] = arguments[_key198]; - } - - return _builder.default.apply(void 0, ["TSNamespaceExportDeclaration"].concat(args)); -} - -function TSTypeAnnotation() { - for (var _len199 = arguments.length, args = new Array(_len199), _key199 = 0; _key199 < _len199; _key199++) { - args[_key199] = arguments[_key199]; - } - - return _builder.default.apply(void 0, ["TSTypeAnnotation"].concat(args)); -} - -function TSTypeParameterInstantiation() { - for (var _len200 = arguments.length, args = new Array(_len200), _key200 = 0; _key200 < _len200; _key200++) { - args[_key200] = arguments[_key200]; - } - - return _builder.default.apply(void 0, ["TSTypeParameterInstantiation"].concat(args)); -} - -function TSTypeParameterDeclaration() { - for (var _len201 = arguments.length, args = new Array(_len201), _key201 = 0; _key201 < _len201; _key201++) { - args[_key201] = arguments[_key201]; - } - - return _builder.default.apply(void 0, ["TSTypeParameterDeclaration"].concat(args)); -} - -function TSTypeParameter() { - for (var _len202 = arguments.length, args = new Array(_len202), _key202 = 0; _key202 < _len202; _key202++) { - args[_key202] = arguments[_key202]; - } - - return _builder.default.apply(void 0, ["TSTypeParameter"].concat(args)); -} - -function NumberLiteral() { - console.trace("The node type NumberLiteral has been renamed to NumericLiteral"); - - for (var _len203 = arguments.length, args = new Array(_len203), _key203 = 0; _key203 < _len203; _key203++) { - args[_key203] = arguments[_key203]; - } - - return NumberLiteral.apply(void 0, ["NumberLiteral"].concat(args)); -} - -function RegexLiteral() { - console.trace("The node type RegexLiteral has been renamed to RegExpLiteral"); - - for (var _len204 = arguments.length, args = new Array(_len204), _key204 = 0; _key204 < _len204; _key204++) { - args[_key204] = arguments[_key204]; - } - - return RegexLiteral.apply(void 0, ["RegexLiteral"].concat(args)); -} - -function RestProperty() { - console.trace("The node type RestProperty has been renamed to RestElement"); - - for (var _len205 = arguments.length, args = new Array(_len205), _key205 = 0; _key205 < _len205; _key205++) { - args[_key205] = arguments[_key205]; - } - - return RestProperty.apply(void 0, ["RestProperty"].concat(args)); -} - -function SpreadProperty() { - console.trace("The node type SpreadProperty has been renamed to SpreadElement"); - - for (var _len206 = arguments.length, args = new Array(_len206), _key206 = 0; _key206 < _len206; _key206++) { - args[_key206] = arguments[_key206]; - } - - return SpreadProperty.apply(void 0, ["SpreadProperty"].concat(args)); -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/builders/react/buildChildren.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/builders/react/buildChildren.js deleted file mode 100644 index 26c3068fd38658..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/builders/react/buildChildren.js +++ /dev/null @@ -1,29 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = buildChildren; - -var _generated = require("../../validators/generated"); - -var _cleanJSXElementLiteralChild = _interopRequireDefault(require("../../utils/react/cleanJSXElementLiteralChild")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function buildChildren(node) { - var elements = []; - - for (var i = 0; i < node.children.length; i++) { - var child = node.children[i]; - - if ((0, _generated.isJSXText)(child)) { - (0, _cleanJSXElementLiteralChild.default)(child, elements); - continue; - } - - if ((0, _generated.isJSXExpressionContainer)(child)) child = child.expression; - if ((0, _generated.isJSXEmptyExpression)(child)) continue; - elements.push(child); - } - - return elements; -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/clone/clone.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/clone/clone.js deleted file mode 100644 index 2677f9023a063d..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/clone/clone.js +++ /dev/null @@ -1,14 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = clone; - -function clone(node) { - if (!node) return node; - var newNode = {}; - Object.keys(node).forEach(function (key) { - if (key[0] === "_") return; - newNode[key] = node[key]; - }); - return newNode; -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/clone/cloneDeep.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/clone/cloneDeep.js deleted file mode 100644 index 4212edd2bc7482..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/clone/cloneDeep.js +++ /dev/null @@ -1,24 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = cloneDeep; - -function cloneDeep(node) { - if (!node) return node; - var newNode = {}; - Object.keys(node).forEach(function (key) { - if (key[0] === "_") return; - var val = node[key]; - - if (val) { - if (val.type) { - val = cloneDeep(val); - } else if (Array.isArray(val)) { - val = val.map(cloneDeep); - } - } - - newNode[key] = val; - }); - return newNode; -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/clone/cloneWithoutLoc.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/clone/cloneWithoutLoc.js deleted file mode 100644 index a32214294208dc..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/clone/cloneWithoutLoc.js +++ /dev/null @@ -1,14 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = cloneWithoutLoc; - -var _clone = _interopRequireDefault(require("./clone")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function cloneWithoutLoc(node) { - var newNode = (0, _clone.default)(node); - newNode.loc = null; - return newNode; -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/comments/addComment.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/comments/addComment.js deleted file mode 100644 index bbe3c969549b34..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/comments/addComment.js +++ /dev/null @@ -1,15 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = addComment; - -var _addComments = _interopRequireDefault(require("./addComments")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function addComment(node, type, content, line) { - return (0, _addComments.default)(node, type, [{ - type: line ? "CommentLine" : "CommentBlock", - value: content - }]); -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/comments/addComments.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/comments/addComments.js deleted file mode 100644 index 1f7c52931da182..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/comments/addComments.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = addComments; - -function addComments(node, type, comments) { - if (!comments || !node) return node; - var key = type + "Comments"; - - if (node[key]) { - if (type === "leading") { - node[key] = comments.concat(node[key]); - } else { - node[key] = node[key].concat(comments); - } - } else { - node[key] = comments; - } - - return node; -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/comments/inheritInnerComments.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/comments/inheritInnerComments.js deleted file mode 100644 index 02f1ad5092e29e..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/comments/inheritInnerComments.js +++ /dev/null @@ -1,12 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = inheritInnerComments; - -var _inherit = _interopRequireDefault(require("../utils/inherit")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function inheritInnerComments(child, parent) { - (0, _inherit.default)("innerComments", child, parent); -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/comments/inheritLeadingComments.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/comments/inheritLeadingComments.js deleted file mode 100644 index f5c213be1fcddd..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/comments/inheritLeadingComments.js +++ /dev/null @@ -1,12 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = inheritLeadingComments; - -var _inherit = _interopRequireDefault(require("../utils/inherit")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function inheritLeadingComments(child, parent) { - (0, _inherit.default)("leadingComments", child, parent); -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/comments/inheritTrailingComments.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/comments/inheritTrailingComments.js deleted file mode 100644 index 81d60f74148d4e..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/comments/inheritTrailingComments.js +++ /dev/null @@ -1,12 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = inheritTrailingComments; - -var _inherit = _interopRequireDefault(require("../utils/inherit")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function inheritTrailingComments(child, parent) { - (0, _inherit.default)("trailingComments", child, parent); -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/comments/inheritsComments.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/comments/inheritsComments.js deleted file mode 100644 index f0446776df81ac..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/comments/inheritsComments.js +++ /dev/null @@ -1,19 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = inheritsComments; - -var _inheritTrailingComments = _interopRequireDefault(require("./inheritTrailingComments")); - -var _inheritLeadingComments = _interopRequireDefault(require("./inheritLeadingComments")); - -var _inheritInnerComments = _interopRequireDefault(require("./inheritInnerComments")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function inheritsComments(child, parent) { - (0, _inheritTrailingComments.default)(child, parent); - (0, _inheritLeadingComments.default)(child, parent); - (0, _inheritInnerComments.default)(child, parent); - return child; -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/comments/removeComments.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/comments/removeComments.js deleted file mode 100644 index 30319b1c9c5144..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/comments/removeComments.js +++ /dev/null @@ -1,14 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = removeComments; - -var _constants = require("../constants"); - -function removeComments(node) { - _constants.COMMENT_KEYS.forEach(function (key) { - node[key] = null; - }); - - return node; -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/constants/generated/index.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/constants/generated/index.js deleted file mode 100644 index 20f182ed1def1f..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/constants/generated/index.js +++ /dev/null @@ -1,87 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.TSTYPE_TYPES = exports.TSTYPEELEMENT_TYPES = exports.JSX_TYPES = exports.FLOWPREDICATE_TYPES = exports.FLOWDECLARATION_TYPES = exports.FLOWBASEANNOTATION_TYPES = exports.FLOW_TYPES = exports.MODULESPECIFIER_TYPES = exports.EXPORTDECLARATION_TYPES = exports.MODULEDECLARATION_TYPES = exports.CLASS_TYPES = exports.PATTERN_TYPES = exports.UNARYLIKE_TYPES = exports.PROPERTY_TYPES = exports.OBJECTMEMBER_TYPES = exports.METHOD_TYPES = exports.USERWHITESPACABLE_TYPES = exports.IMMUTABLE_TYPES = exports.LITERAL_TYPES = exports.TSENTITYNAME_TYPES = exports.LVAL_TYPES = exports.PATTERNLIKE_TYPES = exports.DECLARATION_TYPES = exports.PUREISH_TYPES = exports.FUNCTIONPARENT_TYPES = exports.FUNCTION_TYPES = exports.FORXSTATEMENT_TYPES = exports.FOR_TYPES = exports.EXPRESSIONWRAPPER_TYPES = exports.WHILE_TYPES = exports.LOOP_TYPES = exports.CONDITIONAL_TYPES = exports.COMPLETIONSTATEMENT_TYPES = exports.TERMINATORLESS_TYPES = exports.STATEMENT_TYPES = exports.BLOCK_TYPES = exports.BLOCKPARENT_TYPES = exports.SCOPABLE_TYPES = exports.BINARY_TYPES = exports.EXPRESSION_TYPES = void 0; - -var _definitions = require("../../definitions"); - -var EXPRESSION_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Expression"]; -exports.EXPRESSION_TYPES = EXPRESSION_TYPES; -var BINARY_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Binary"]; -exports.BINARY_TYPES = BINARY_TYPES; -var SCOPABLE_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Scopable"]; -exports.SCOPABLE_TYPES = SCOPABLE_TYPES; -var BLOCKPARENT_TYPES = _definitions.FLIPPED_ALIAS_KEYS["BlockParent"]; -exports.BLOCKPARENT_TYPES = BLOCKPARENT_TYPES; -var BLOCK_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Block"]; -exports.BLOCK_TYPES = BLOCK_TYPES; -var STATEMENT_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Statement"]; -exports.STATEMENT_TYPES = STATEMENT_TYPES; -var TERMINATORLESS_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Terminatorless"]; -exports.TERMINATORLESS_TYPES = TERMINATORLESS_TYPES; -var COMPLETIONSTATEMENT_TYPES = _definitions.FLIPPED_ALIAS_KEYS["CompletionStatement"]; -exports.COMPLETIONSTATEMENT_TYPES = COMPLETIONSTATEMENT_TYPES; -var CONDITIONAL_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Conditional"]; -exports.CONDITIONAL_TYPES = CONDITIONAL_TYPES; -var LOOP_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Loop"]; -exports.LOOP_TYPES = LOOP_TYPES; -var WHILE_TYPES = _definitions.FLIPPED_ALIAS_KEYS["While"]; -exports.WHILE_TYPES = WHILE_TYPES; -var EXPRESSIONWRAPPER_TYPES = _definitions.FLIPPED_ALIAS_KEYS["ExpressionWrapper"]; -exports.EXPRESSIONWRAPPER_TYPES = EXPRESSIONWRAPPER_TYPES; -var FOR_TYPES = _definitions.FLIPPED_ALIAS_KEYS["For"]; -exports.FOR_TYPES = FOR_TYPES; -var FORXSTATEMENT_TYPES = _definitions.FLIPPED_ALIAS_KEYS["ForXStatement"]; -exports.FORXSTATEMENT_TYPES = FORXSTATEMENT_TYPES; -var FUNCTION_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Function"]; -exports.FUNCTION_TYPES = FUNCTION_TYPES; -var FUNCTIONPARENT_TYPES = _definitions.FLIPPED_ALIAS_KEYS["FunctionParent"]; -exports.FUNCTIONPARENT_TYPES = FUNCTIONPARENT_TYPES; -var PUREISH_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Pureish"]; -exports.PUREISH_TYPES = PUREISH_TYPES; -var DECLARATION_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Declaration"]; -exports.DECLARATION_TYPES = DECLARATION_TYPES; -var PATTERNLIKE_TYPES = _definitions.FLIPPED_ALIAS_KEYS["PatternLike"]; -exports.PATTERNLIKE_TYPES = PATTERNLIKE_TYPES; -var LVAL_TYPES = _definitions.FLIPPED_ALIAS_KEYS["LVal"]; -exports.LVAL_TYPES = LVAL_TYPES; -var TSENTITYNAME_TYPES = _definitions.FLIPPED_ALIAS_KEYS["TSEntityName"]; -exports.TSENTITYNAME_TYPES = TSENTITYNAME_TYPES; -var LITERAL_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Literal"]; -exports.LITERAL_TYPES = LITERAL_TYPES; -var IMMUTABLE_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Immutable"]; -exports.IMMUTABLE_TYPES = IMMUTABLE_TYPES; -var USERWHITESPACABLE_TYPES = _definitions.FLIPPED_ALIAS_KEYS["UserWhitespacable"]; -exports.USERWHITESPACABLE_TYPES = USERWHITESPACABLE_TYPES; -var METHOD_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Method"]; -exports.METHOD_TYPES = METHOD_TYPES; -var OBJECTMEMBER_TYPES = _definitions.FLIPPED_ALIAS_KEYS["ObjectMember"]; -exports.OBJECTMEMBER_TYPES = OBJECTMEMBER_TYPES; -var PROPERTY_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Property"]; -exports.PROPERTY_TYPES = PROPERTY_TYPES; -var UNARYLIKE_TYPES = _definitions.FLIPPED_ALIAS_KEYS["UnaryLike"]; -exports.UNARYLIKE_TYPES = UNARYLIKE_TYPES; -var PATTERN_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Pattern"]; -exports.PATTERN_TYPES = PATTERN_TYPES; -var CLASS_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Class"]; -exports.CLASS_TYPES = CLASS_TYPES; -var MODULEDECLARATION_TYPES = _definitions.FLIPPED_ALIAS_KEYS["ModuleDeclaration"]; -exports.MODULEDECLARATION_TYPES = MODULEDECLARATION_TYPES; -var EXPORTDECLARATION_TYPES = _definitions.FLIPPED_ALIAS_KEYS["ExportDeclaration"]; -exports.EXPORTDECLARATION_TYPES = EXPORTDECLARATION_TYPES; -var MODULESPECIFIER_TYPES = _definitions.FLIPPED_ALIAS_KEYS["ModuleSpecifier"]; -exports.MODULESPECIFIER_TYPES = MODULESPECIFIER_TYPES; -var FLOW_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Flow"]; -exports.FLOW_TYPES = FLOW_TYPES; -var FLOWBASEANNOTATION_TYPES = _definitions.FLIPPED_ALIAS_KEYS["FlowBaseAnnotation"]; -exports.FLOWBASEANNOTATION_TYPES = FLOWBASEANNOTATION_TYPES; -var FLOWDECLARATION_TYPES = _definitions.FLIPPED_ALIAS_KEYS["FlowDeclaration"]; -exports.FLOWDECLARATION_TYPES = FLOWDECLARATION_TYPES; -var FLOWPREDICATE_TYPES = _definitions.FLIPPED_ALIAS_KEYS["FlowPredicate"]; -exports.FLOWPREDICATE_TYPES = FLOWPREDICATE_TYPES; -var JSX_TYPES = _definitions.FLIPPED_ALIAS_KEYS["JSX"]; -exports.JSX_TYPES = JSX_TYPES; -var TSTYPEELEMENT_TYPES = _definitions.FLIPPED_ALIAS_KEYS["TSTypeElement"]; -exports.TSTYPEELEMENT_TYPES = TSTYPEELEMENT_TYPES; -var TSTYPE_TYPES = _definitions.FLIPPED_ALIAS_KEYS["TSType"]; -exports.TSTYPE_TYPES = TSTYPE_TYPES; \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/constants/index.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/constants/index.js deleted file mode 100644 index f8eb31b9eed64c..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/constants/index.js +++ /dev/null @@ -1,45 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.NOT_LOCAL_BINDING = exports.BLOCK_SCOPED_SYMBOL = exports.INHERIT_KEYS = exports.UNARY_OPERATORS = exports.STRING_UNARY_OPERATORS = exports.NUMBER_UNARY_OPERATORS = exports.BOOLEAN_UNARY_OPERATORS = exports.BINARY_OPERATORS = exports.NUMBER_BINARY_OPERATORS = exports.BOOLEAN_BINARY_OPERATORS = exports.COMPARISON_BINARY_OPERATORS = exports.EQUALITY_BINARY_OPERATORS = exports.BOOLEAN_NUMBER_BINARY_OPERATORS = exports.UPDATE_OPERATORS = exports.LOGICAL_OPERATORS = exports.COMMENT_KEYS = exports.FOR_INIT_KEYS = exports.FLATTENABLE_KEYS = exports.STATEMENT_OR_BLOCK_KEYS = void 0; -var STATEMENT_OR_BLOCK_KEYS = ["consequent", "body", "alternate"]; -exports.STATEMENT_OR_BLOCK_KEYS = STATEMENT_OR_BLOCK_KEYS; -var FLATTENABLE_KEYS = ["body", "expressions"]; -exports.FLATTENABLE_KEYS = FLATTENABLE_KEYS; -var FOR_INIT_KEYS = ["left", "init"]; -exports.FOR_INIT_KEYS = FOR_INIT_KEYS; -var COMMENT_KEYS = ["leadingComments", "trailingComments", "innerComments"]; -exports.COMMENT_KEYS = COMMENT_KEYS; -var LOGICAL_OPERATORS = ["||", "&&", "??"]; -exports.LOGICAL_OPERATORS = LOGICAL_OPERATORS; -var UPDATE_OPERATORS = ["++", "--"]; -exports.UPDATE_OPERATORS = UPDATE_OPERATORS; -var BOOLEAN_NUMBER_BINARY_OPERATORS = [">", "<", ">=", "<="]; -exports.BOOLEAN_NUMBER_BINARY_OPERATORS = BOOLEAN_NUMBER_BINARY_OPERATORS; -var EQUALITY_BINARY_OPERATORS = ["==", "===", "!=", "!=="]; -exports.EQUALITY_BINARY_OPERATORS = EQUALITY_BINARY_OPERATORS; -var COMPARISON_BINARY_OPERATORS = EQUALITY_BINARY_OPERATORS.concat(["in", "instanceof"]); -exports.COMPARISON_BINARY_OPERATORS = COMPARISON_BINARY_OPERATORS; -var BOOLEAN_BINARY_OPERATORS = COMPARISON_BINARY_OPERATORS.concat(BOOLEAN_NUMBER_BINARY_OPERATORS); -exports.BOOLEAN_BINARY_OPERATORS = BOOLEAN_BINARY_OPERATORS; -var NUMBER_BINARY_OPERATORS = ["-", "/", "%", "*", "**", "&", "|", ">>", ">>>", "<<", "^"]; -exports.NUMBER_BINARY_OPERATORS = NUMBER_BINARY_OPERATORS; -var BINARY_OPERATORS = ["+"].concat(NUMBER_BINARY_OPERATORS, BOOLEAN_BINARY_OPERATORS); -exports.BINARY_OPERATORS = BINARY_OPERATORS; -var BOOLEAN_UNARY_OPERATORS = ["delete", "!"]; -exports.BOOLEAN_UNARY_OPERATORS = BOOLEAN_UNARY_OPERATORS; -var NUMBER_UNARY_OPERATORS = ["+", "-", "~"]; -exports.NUMBER_UNARY_OPERATORS = NUMBER_UNARY_OPERATORS; -var STRING_UNARY_OPERATORS = ["typeof"]; -exports.STRING_UNARY_OPERATORS = STRING_UNARY_OPERATORS; -var UNARY_OPERATORS = ["void", "throw"].concat(BOOLEAN_UNARY_OPERATORS, NUMBER_UNARY_OPERATORS, STRING_UNARY_OPERATORS); -exports.UNARY_OPERATORS = UNARY_OPERATORS; -var INHERIT_KEYS = { - optional: ["typeAnnotation", "typeParameters", "returnType"], - force: ["start", "loc", "end"] -}; -exports.INHERIT_KEYS = INHERIT_KEYS; -var BLOCK_SCOPED_SYMBOL = Symbol.for("var used to be block scoped"); -exports.BLOCK_SCOPED_SYMBOL = BLOCK_SCOPED_SYMBOL; -var NOT_LOCAL_BINDING = Symbol.for("should not be considered a local binding"); -exports.NOT_LOCAL_BINDING = NOT_LOCAL_BINDING; \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/converters/ensureBlock.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/converters/ensureBlock.js deleted file mode 100644 index da69103d9ef20b..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/converters/ensureBlock.js +++ /dev/null @@ -1,16 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = ensureBlock; - -var _toBlock = _interopRequireDefault(require("./toBlock")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function ensureBlock(node, key) { - if (key === void 0) { - key = "body"; - } - - return node[key] = (0, _toBlock.default)(node[key], node); -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/converters/gatherSequenceExpressions.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/converters/gatherSequenceExpressions.js deleted file mode 100644 index 0e07cbe18f0e3e..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/converters/gatherSequenceExpressions.js +++ /dev/null @@ -1,83 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = gatherSequenceExpressions; - -var _getBindingIdentifiers = _interopRequireDefault(require("../retrievers/getBindingIdentifiers")); - -var _generated = require("../validators/generated"); - -var _generated2 = require("../builders/generated"); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function gatherSequenceExpressions(nodes, scope, declars) { - var exprs = []; - var ensureLastUndefined = true; - - for (var _iterator = nodes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var _node = _ref; - ensureLastUndefined = false; - - if ((0, _generated.isExpression)(_node)) { - exprs.push(_node); - } else if ((0, _generated.isExpressionStatement)(_node)) { - exprs.push(_node.expression); - } else if ((0, _generated.isVariableDeclaration)(_node)) { - if (_node.kind !== "var") return; - var _arr = _node.declarations; - - for (var _i2 = 0; _i2 < _arr.length; _i2++) { - var declar = _arr[_i2]; - var bindings = (0, _getBindingIdentifiers.default)(declar); - - for (var key in bindings) { - declars.push({ - kind: _node.kind, - id: bindings[key] - }); - } - - if (declar.init) { - exprs.push((0, _generated2.assignmentExpression)("=", declar.id, declar.init)); - } - } - - ensureLastUndefined = true; - } else if ((0, _generated.isIfStatement)(_node)) { - var consequent = _node.consequent ? gatherSequenceExpressions([_node.consequent], scope, declars) : scope.buildUndefinedNode(); - var alternate = _node.alternate ? gatherSequenceExpressions([_node.alternate], scope, declars) : scope.buildUndefinedNode(); - if (!consequent || !alternate) return; - exprs.push((0, _generated2.conditionalExpression)(_node.test, consequent, alternate)); - } else if ((0, _generated.isBlockStatement)(_node)) { - var body = gatherSequenceExpressions(_node.body, scope, declars); - if (!body) return; - exprs.push(body); - } else if ((0, _generated.isEmptyStatement)(_node)) { - ensureLastUndefined = true; - } else { - return; - } - } - - if (ensureLastUndefined) { - exprs.push(scope.buildUndefinedNode()); - } - - if (exprs.length === 1) { - return exprs[0]; - } else { - return (0, _generated2.sequenceExpression)(exprs); - } -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/converters/toBindingIdentifierName.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/converters/toBindingIdentifierName.js deleted file mode 100644 index 3bda98aa834e10..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/converters/toBindingIdentifierName.js +++ /dev/null @@ -1,14 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = toBindingIdentifierName; - -var _toIdentifier = _interopRequireDefault(require("./toIdentifier")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function toBindingIdentifierName(name) { - name = (0, _toIdentifier.default)(name); - if (name === "eval" || name === "arguments") name = "_" + name; - return name; -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/converters/toBlock.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/converters/toBlock.js deleted file mode 100644 index 542ff552103516..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/converters/toBlock.js +++ /dev/null @@ -1,32 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = toBlock; - -var _generated = require("../validators/generated"); - -var _generated2 = require("../builders/generated"); - -function toBlock(node, parent) { - if ((0, _generated.isBlockStatement)(node)) { - return node; - } - - var blockNodes = []; - - if ((0, _generated.isEmptyStatement)(node)) { - blockNodes = []; - } else { - if (!(0, _generated.isStatement)(node)) { - if ((0, _generated.isFunction)(parent)) { - node = (0, _generated2.returnStatement)(node); - } else { - node = (0, _generated2.expressionStatement)(node); - } - } - - blockNodes = [node]; - } - - return (0, _generated2.blockStatement)(blockNodes); -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/converters/toComputedKey.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/converters/toComputedKey.js deleted file mode 100644 index 71bd8e4a6628cb..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/converters/toComputedKey.js +++ /dev/null @@ -1,17 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = toComputedKey; - -var _generated = require("../validators/generated"); - -var _generated2 = require("../builders/generated"); - -function toComputedKey(node, key) { - if (key === void 0) { - key = node.key || node.property; - } - - if (!node.computed && (0, _generated.isIdentifier)(key)) key = (0, _generated2.stringLiteral)(key.name); - return key; -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/converters/toExpression.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/converters/toExpression.js deleted file mode 100644 index dfb5bb87b84743..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/converters/toExpression.js +++ /dev/null @@ -1,28 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = toExpression; - -var _generated = require("../validators/generated"); - -function toExpression(node) { - if ((0, _generated.isExpressionStatement)(node)) { - node = node.expression; - } - - if ((0, _generated.isExpression)(node)) { - return node; - } - - if ((0, _generated.isClass)(node)) { - node.type = "ClassExpression"; - } else if ((0, _generated.isFunction)(node)) { - node.type = "FunctionExpression"; - } - - if (!(0, _generated.isExpression)(node)) { - throw new Error("cannot turn " + node.type + " to an expression"); - } - - return node; -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/converters/toIdentifier.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/converters/toIdentifier.js deleted file mode 100644 index d929872af5e553..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/converters/toIdentifier.js +++ /dev/null @@ -1,23 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = toIdentifier; - -var _isValidIdentifier = _interopRequireDefault(require("../validators/isValidIdentifier")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function toIdentifier(name) { - name = name + ""; - name = name.replace(/[^a-zA-Z0-9$_]/g, "-"); - name = name.replace(/^[-0-9]+/, ""); - name = name.replace(/[-\s]+(.)?/g, function (match, c) { - return c ? c.toUpperCase() : ""; - }); - - if (!(0, _isValidIdentifier.default)(name)) { - name = "_" + name; - } - - return name || "_"; -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/converters/toKeyAlias.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/converters/toKeyAlias.js deleted file mode 100644 index 88aa30ed979b77..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/converters/toKeyAlias.js +++ /dev/null @@ -1,50 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = toKeyAlias; - -var _generated = require("../validators/generated"); - -var _cloneDeep = _interopRequireDefault(require("../clone/cloneDeep")); - -var _removePropertiesDeep = _interopRequireDefault(require("../modifications/removePropertiesDeep")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function toKeyAlias(node, key) { - if (key === void 0) { - key = node.key; - } - - var alias; - - if (node.kind === "method") { - return toKeyAlias.increment() + ""; - } else if ((0, _generated.isIdentifier)(key)) { - alias = key.name; - } else if ((0, _generated.isStringLiteral)(key)) { - alias = JSON.stringify(key.value); - } else { - alias = JSON.stringify((0, _removePropertiesDeep.default)((0, _cloneDeep.default)(key))); - } - - if (node.computed) { - alias = "[" + alias + "]"; - } - - if (node.static) { - alias = "static:" + alias; - } - - return alias; -} - -toKeyAlias.uid = 0; - -toKeyAlias.increment = function () { - if (toKeyAlias.uid >= Number.MAX_SAFE_INTEGER) { - return toKeyAlias.uid = 0; - } else { - return toKeyAlias.uid++; - } -}; \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/converters/toSequenceExpression.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/converters/toSequenceExpression.js deleted file mode 100644 index c5488ef9d5526f..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/converters/toSequenceExpression.js +++ /dev/null @@ -1,22 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = toSequenceExpression; - -var _gatherSequenceExpressions = _interopRequireDefault(require("./gatherSequenceExpressions")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function toSequenceExpression(nodes, scope) { - if (!nodes || !nodes.length) return; - var declars = []; - var result = (0, _gatherSequenceExpressions.default)(nodes, scope, declars); - if (!result) return; - - for (var _i = 0; _i < declars.length; _i++) { - var declar = declars[_i]; - scope.push(declar); - } - - return result; -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/converters/toStatement.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/converters/toStatement.js deleted file mode 100644 index 8fa5a97e20d9cc..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/converters/toStatement.js +++ /dev/null @@ -1,42 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = toStatement; - -var _generated = require("../validators/generated"); - -var _generated2 = require("../builders/generated"); - -function toStatement(node, ignore) { - if ((0, _generated.isStatement)(node)) { - return node; - } - - var mustHaveId = false; - var newType; - - if ((0, _generated.isClass)(node)) { - mustHaveId = true; - newType = "ClassDeclaration"; - } else if ((0, _generated.isFunction)(node)) { - mustHaveId = true; - newType = "FunctionDeclaration"; - } else if ((0, _generated.isAssignmentExpression)(node)) { - return (0, _generated2.expressionStatement)(node); - } - - if (mustHaveId && !node.id) { - newType = false; - } - - if (!newType) { - if (ignore) { - return false; - } else { - throw new Error("cannot turn " + node.type + " to a statement"); - } - } - - node.type = newType; - return node; -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/converters/valueToNode.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/converters/valueToNode.js deleted file mode 100644 index d8f82ffd05e606..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/converters/valueToNode.js +++ /dev/null @@ -1,66 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = valueToNode; - -var _isPlainObject = _interopRequireDefault(require("lodash/isPlainObject")); - -var _isRegExp = _interopRequireDefault(require("lodash/isRegExp")); - -var _isValidIdentifier = _interopRequireDefault(require("../validators/isValidIdentifier")); - -var _generated = require("../builders/generated"); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function valueToNode(value) { - if (value === undefined) { - return (0, _generated.identifier)("undefined"); - } - - if (value === true || value === false) { - return (0, _generated.booleanLiteral)(value); - } - - if (value === null) { - return (0, _generated.nullLiteral)(); - } - - if (typeof value === "string") { - return (0, _generated.stringLiteral)(value); - } - - if (typeof value === "number") { - return (0, _generated.numericLiteral)(value); - } - - if ((0, _isRegExp.default)(value)) { - var pattern = value.source; - var flags = value.toString().match(/\/([a-z]+|)$/)[1]; - return (0, _generated.regExpLiteral)(pattern, flags); - } - - if (Array.isArray(value)) { - return (0, _generated.arrayExpression)(value.map(valueToNode)); - } - - if ((0, _isPlainObject.default)(value)) { - var props = []; - - for (var key in value) { - var nodeKey = void 0; - - if ((0, _isValidIdentifier.default)(key)) { - nodeKey = (0, _generated.identifier)(key); - } else { - nodeKey = (0, _generated.stringLiteral)(key); - } - - props.push((0, _generated.objectProperty)(nodeKey, valueToNode(value[key]))); - } - - return (0, _generated.objectExpression)(props); - } - - throw new Error("don't know how to turn this value into a node"); -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/definitions/core.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/definitions/core.js deleted file mode 100644 index d8abe51f151946..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/definitions/core.js +++ /dev/null @@ -1,693 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.patternLikeCommon = exports.functionDeclarationCommon = exports.functionTypeAnnotationCommon = exports.functionCommon = void 0; - -var _isValidIdentifier = _interopRequireDefault(require("../validators/isValidIdentifier")); - -var _constants = require("../constants"); - -var _utils = _interopRequireWildcard(require("./utils")); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -(0, _utils.default)("ArrayExpression", { - fields: { - elements: { - validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeOrValueType)("null", "Expression", "SpreadElement"))), - default: [] - } - }, - visitor: ["elements"], - aliases: ["Expression"] -}); -(0, _utils.default)("AssignmentExpression", { - fields: { - operator: { - validate: (0, _utils.assertValueType)("string") - }, - left: { - validate: (0, _utils.assertNodeType)("LVal") - }, - right: { - validate: (0, _utils.assertNodeType)("Expression") - } - }, - builder: ["operator", "left", "right"], - visitor: ["left", "right"], - aliases: ["Expression"] -}); -(0, _utils.default)("BinaryExpression", { - builder: ["operator", "left", "right"], - fields: { - operator: { - validate: _utils.assertOneOf.apply(void 0, _constants.BINARY_OPERATORS) - }, - left: { - validate: (0, _utils.assertNodeType)("Expression") - }, - right: { - validate: (0, _utils.assertNodeType)("Expression") - } - }, - visitor: ["left", "right"], - aliases: ["Binary", "Expression"] -}); -(0, _utils.default)("Directive", { - visitor: ["value"], - fields: { - value: { - validate: (0, _utils.assertNodeType)("DirectiveLiteral") - } - } -}); -(0, _utils.default)("DirectiveLiteral", { - builder: ["value"], - fields: { - value: { - validate: (0, _utils.assertValueType)("string") - } - } -}); -(0, _utils.default)("BlockStatement", { - builder: ["body", "directives"], - visitor: ["directives", "body"], - fields: { - directives: { - validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Directive"))), - default: [] - }, - body: { - validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Statement"))) - } - }, - aliases: ["Scopable", "BlockParent", "Block", "Statement"] -}); -(0, _utils.default)("BreakStatement", { - visitor: ["label"], - fields: { - label: { - validate: (0, _utils.assertNodeType)("Identifier"), - optional: true - } - }, - aliases: ["Statement", "Terminatorless", "CompletionStatement"] -}); -(0, _utils.default)("CallExpression", { - visitor: ["callee", "arguments", "typeParameters"], - builder: ["callee", "arguments"], - aliases: ["Expression"], - fields: { - callee: { - validate: (0, _utils.assertNodeType)("Expression") - }, - arguments: { - validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Expression", "SpreadElement", "JSXNamespacedName"))) - }, - optional: { - validate: (0, _utils.assertOneOf)(true, false), - optional: true - }, - typeParameters: { - validate: (0, _utils.assertNodeType)("TypeParameterInstantiation", "TSTypeParameterInstantiation"), - optional: true - } - } -}); -(0, _utils.default)("CatchClause", { - visitor: ["param", "body"], - fields: { - param: { - validate: (0, _utils.assertNodeType)("Identifier"), - optional: true - }, - body: { - validate: (0, _utils.assertNodeType)("BlockStatement") - } - }, - aliases: ["Scopable", "BlockParent"] -}); -(0, _utils.default)("ConditionalExpression", { - visitor: ["test", "consequent", "alternate"], - fields: { - test: { - validate: (0, _utils.assertNodeType)("Expression") - }, - consequent: { - validate: (0, _utils.assertNodeType)("Expression") - }, - alternate: { - validate: (0, _utils.assertNodeType)("Expression") - } - }, - aliases: ["Expression", "Conditional"] -}); -(0, _utils.default)("ContinueStatement", { - visitor: ["label"], - fields: { - label: { - validate: (0, _utils.assertNodeType)("Identifier"), - optional: true - } - }, - aliases: ["Statement", "Terminatorless", "CompletionStatement"] -}); -(0, _utils.default)("DebuggerStatement", { - aliases: ["Statement"] -}); -(0, _utils.default)("DoWhileStatement", { - visitor: ["test", "body"], - fields: { - test: { - validate: (0, _utils.assertNodeType)("Expression") - }, - body: { - validate: (0, _utils.assertNodeType)("Statement") - } - }, - aliases: ["Statement", "BlockParent", "Loop", "While", "Scopable"] -}); -(0, _utils.default)("EmptyStatement", { - aliases: ["Statement"] -}); -(0, _utils.default)("ExpressionStatement", { - visitor: ["expression"], - fields: { - expression: { - validate: (0, _utils.assertNodeType)("Expression") - } - }, - aliases: ["Statement", "ExpressionWrapper"] -}); -(0, _utils.default)("File", { - builder: ["program", "comments", "tokens"], - visitor: ["program"], - fields: { - program: { - validate: (0, _utils.assertNodeType)("Program") - } - } -}); -(0, _utils.default)("ForInStatement", { - visitor: ["left", "right", "body"], - aliases: ["Scopable", "Statement", "For", "BlockParent", "Loop", "ForXStatement"], - fields: { - left: { - validate: (0, _utils.assertNodeType)("VariableDeclaration", "LVal") - }, - right: { - validate: (0, _utils.assertNodeType)("Expression") - }, - body: { - validate: (0, _utils.assertNodeType)("Statement") - } - } -}); -(0, _utils.default)("ForStatement", { - visitor: ["init", "test", "update", "body"], - aliases: ["Scopable", "Statement", "For", "BlockParent", "Loop"], - fields: { - init: { - validate: (0, _utils.assertNodeType)("VariableDeclaration", "Expression"), - optional: true - }, - test: { - validate: (0, _utils.assertNodeType)("Expression"), - optional: true - }, - update: { - validate: (0, _utils.assertNodeType)("Expression"), - optional: true - }, - body: { - validate: (0, _utils.assertNodeType)("Statement") - } - } -}); -var functionCommon = { - params: { - validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("LVal"))) - }, - generator: { - default: false, - validate: (0, _utils.assertValueType)("boolean") - }, - async: { - validate: (0, _utils.assertValueType)("boolean"), - default: false - } -}; -exports.functionCommon = functionCommon; -var functionTypeAnnotationCommon = { - returnType: { - validate: (0, _utils.assertNodeType)("TypeAnnotation", "TSTypeAnnotation", "Noop"), - optional: true - }, - typeParameters: { - validate: (0, _utils.assertNodeType)("TypeParameterDeclaration", "TSTypeParameterDeclaration", "Noop"), - optional: true - } -}; -exports.functionTypeAnnotationCommon = functionTypeAnnotationCommon; -var functionDeclarationCommon = Object.assign({}, functionCommon, { - declare: { - validate: (0, _utils.assertValueType)("boolean"), - optional: true - }, - id: { - validate: (0, _utils.assertNodeType)("Identifier"), - optional: true - } -}); -exports.functionDeclarationCommon = functionDeclarationCommon; -(0, _utils.default)("FunctionDeclaration", { - builder: ["id", "params", "body", "generator", "async"], - visitor: ["id", "params", "body", "returnType", "typeParameters"], - fields: Object.assign({}, functionDeclarationCommon, functionTypeAnnotationCommon, { - body: { - validate: (0, _utils.assertNodeType)("BlockStatement") - } - }), - aliases: ["Scopable", "Function", "BlockParent", "FunctionParent", "Statement", "Pureish", "Declaration"] -}); -(0, _utils.default)("FunctionExpression", { - inherits: "FunctionDeclaration", - aliases: ["Scopable", "Function", "BlockParent", "FunctionParent", "Expression", "Pureish"], - fields: Object.assign({}, functionCommon, functionTypeAnnotationCommon, { - id: { - validate: (0, _utils.assertNodeType)("Identifier"), - optional: true - }, - body: { - validate: (0, _utils.assertNodeType)("BlockStatement") - } - }) -}); -var patternLikeCommon = { - typeAnnotation: { - validate: (0, _utils.assertNodeType)("TypeAnnotation", "TSTypeAnnotation", "Noop"), - optional: true - }, - decorators: { - validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator"))) - } -}; -exports.patternLikeCommon = patternLikeCommon; -(0, _utils.default)("Identifier", { - builder: ["name"], - visitor: ["typeAnnotation"], - aliases: ["Expression", "PatternLike", "LVal", "TSEntityName"], - fields: Object.assign({}, patternLikeCommon, { - name: { - validate: function validate(node, key, val) { - if (!(0, _isValidIdentifier.default)(val)) {} - } - }, - optional: { - validate: (0, _utils.assertValueType)("boolean"), - optional: true - } - }) -}); -(0, _utils.default)("IfStatement", { - visitor: ["test", "consequent", "alternate"], - aliases: ["Statement", "Conditional"], - fields: { - test: { - validate: (0, _utils.assertNodeType)("Expression") - }, - consequent: { - validate: (0, _utils.assertNodeType)("Statement") - }, - alternate: { - optional: true, - validate: (0, _utils.assertNodeType)("Statement") - } - } -}); -(0, _utils.default)("LabeledStatement", { - visitor: ["label", "body"], - aliases: ["Statement"], - fields: { - label: { - validate: (0, _utils.assertNodeType)("Identifier") - }, - body: { - validate: (0, _utils.assertNodeType)("Statement") - } - } -}); -(0, _utils.default)("StringLiteral", { - builder: ["value"], - fields: { - value: { - validate: (0, _utils.assertValueType)("string") - } - }, - aliases: ["Expression", "Pureish", "Literal", "Immutable"] -}); -(0, _utils.default)("NumericLiteral", { - builder: ["value"], - deprecatedAlias: "NumberLiteral", - fields: { - value: { - validate: (0, _utils.assertValueType)("number") - } - }, - aliases: ["Expression", "Pureish", "Literal", "Immutable"] -}); -(0, _utils.default)("NullLiteral", { - aliases: ["Expression", "Pureish", "Literal", "Immutable"] -}); -(0, _utils.default)("BooleanLiteral", { - builder: ["value"], - fields: { - value: { - validate: (0, _utils.assertValueType)("boolean") - } - }, - aliases: ["Expression", "Pureish", "Literal", "Immutable"] -}); -(0, _utils.default)("RegExpLiteral", { - builder: ["pattern", "flags"], - deprecatedAlias: "RegexLiteral", - aliases: ["Expression", "Literal"], - fields: { - pattern: { - validate: (0, _utils.assertValueType)("string") - }, - flags: { - validate: (0, _utils.assertValueType)("string"), - default: "" - } - } -}); -(0, _utils.default)("LogicalExpression", { - builder: ["operator", "left", "right"], - visitor: ["left", "right"], - aliases: ["Binary", "Expression"], - fields: { - operator: { - validate: _utils.assertOneOf.apply(void 0, _constants.LOGICAL_OPERATORS) - }, - left: { - validate: (0, _utils.assertNodeType)("Expression") - }, - right: { - validate: (0, _utils.assertNodeType)("Expression") - } - } -}); -(0, _utils.default)("MemberExpression", { - builder: ["object", "property", "computed", "optional"], - visitor: ["object", "property"], - aliases: ["Expression", "LVal"], - fields: { - object: { - validate: (0, _utils.assertNodeType)("Expression") - }, - property: { - validate: function () { - var normal = (0, _utils.assertNodeType)("Identifier"); - var computed = (0, _utils.assertNodeType)("Expression"); - return function (node, key, val) { - var validator = node.computed ? computed : normal; - validator(node, key, val); - }; - }() - }, - computed: { - default: false - }, - optional: { - validate: (0, _utils.assertOneOf)(true, false), - optional: true - } - } -}); -(0, _utils.default)("NewExpression", { - inherits: "CallExpression" -}); -(0, _utils.default)("Program", { - visitor: ["directives", "body"], - builder: ["body", "directives", "sourceType"], - fields: { - sourceFile: { - validate: (0, _utils.assertValueType)("string") - }, - sourceType: { - validate: (0, _utils.assertOneOf)("script", "module"), - default: "script" - }, - directives: { - validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Directive"))), - default: [] - }, - body: { - validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Statement"))) - } - }, - aliases: ["Scopable", "BlockParent", "Block"] -}); -(0, _utils.default)("ObjectExpression", { - visitor: ["properties"], - aliases: ["Expression"], - fields: { - properties: { - validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("ObjectMethod", "ObjectProperty", "SpreadElement"))) - } - } -}); -(0, _utils.default)("ObjectMethod", { - builder: ["kind", "key", "params", "body", "computed"], - fields: Object.assign({}, functionCommon, functionTypeAnnotationCommon, { - kind: { - validate: (0, _utils.chain)((0, _utils.assertValueType)("string"), (0, _utils.assertOneOf)("method", "get", "set")), - default: "method" - }, - computed: { - validate: (0, _utils.assertValueType)("boolean"), - default: false - }, - key: { - validate: function () { - var normal = (0, _utils.assertNodeType)("Identifier", "StringLiteral", "NumericLiteral"); - var computed = (0, _utils.assertNodeType)("Expression"); - return function (node, key, val) { - var validator = node.computed ? computed : normal; - validator(node, key, val); - }; - }() - }, - decorators: { - validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator"))) - }, - body: { - validate: (0, _utils.assertNodeType)("BlockStatement") - } - }), - visitor: ["key", "params", "body", "decorators", "returnType", "typeParameters"], - aliases: ["UserWhitespacable", "Function", "Scopable", "BlockParent", "FunctionParent", "Method", "ObjectMember"] -}); -(0, _utils.default)("ObjectProperty", { - builder: ["key", "value", "computed", "shorthand", "decorators"], - fields: { - computed: { - validate: (0, _utils.assertValueType)("boolean"), - default: false - }, - key: { - validate: function () { - var normal = (0, _utils.assertNodeType)("Identifier", "StringLiteral", "NumericLiteral"); - var computed = (0, _utils.assertNodeType)("Expression"); - return function (node, key, val) { - var validator = node.computed ? computed : normal; - validator(node, key, val); - }; - }() - }, - value: { - validate: (0, _utils.assertNodeType)("Expression", "PatternLike") - }, - shorthand: { - validate: (0, _utils.assertValueType)("boolean"), - default: false - }, - decorators: { - validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator"))), - optional: true - } - }, - visitor: ["key", "value", "decorators"], - aliases: ["UserWhitespacable", "Property", "ObjectMember"] -}); -(0, _utils.default)("RestElement", { - visitor: ["argument", "typeAnnotation"], - builder: ["argument"], - aliases: ["LVal", "PatternLike"], - deprecatedAlias: "RestProperty", - fields: Object.assign({}, patternLikeCommon, { - argument: { - validate: (0, _utils.assertNodeType)("LVal") - } - }) -}); -(0, _utils.default)("ReturnStatement", { - visitor: ["argument"], - aliases: ["Statement", "Terminatorless", "CompletionStatement"], - fields: { - argument: { - validate: (0, _utils.assertNodeType)("Expression"), - optional: true - } - } -}); -(0, _utils.default)("SequenceExpression", { - visitor: ["expressions"], - fields: { - expressions: { - validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Expression"))) - } - }, - aliases: ["Expression"] -}); -(0, _utils.default)("SwitchCase", { - visitor: ["test", "consequent"], - fields: { - test: { - validate: (0, _utils.assertNodeType)("Expression"), - optional: true - }, - consequent: { - validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Statement"))) - } - } -}); -(0, _utils.default)("SwitchStatement", { - visitor: ["discriminant", "cases"], - aliases: ["Statement", "BlockParent", "Scopable"], - fields: { - discriminant: { - validate: (0, _utils.assertNodeType)("Expression") - }, - cases: { - validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("SwitchCase"))) - } - } -}); -(0, _utils.default)("ThisExpression", { - aliases: ["Expression"] -}); -(0, _utils.default)("ThrowStatement", { - visitor: ["argument"], - aliases: ["Statement", "Terminatorless", "CompletionStatement"], - fields: { - argument: { - validate: (0, _utils.assertNodeType)("Expression") - } - } -}); -(0, _utils.default)("TryStatement", { - visitor: ["block", "handler", "finalizer"], - aliases: ["Statement"], - fields: { - block: { - validate: (0, _utils.assertNodeType)("BlockStatement") - }, - handler: { - optional: true, - validate: (0, _utils.assertNodeType)("CatchClause") - }, - finalizer: { - optional: true, - validate: (0, _utils.assertNodeType)("BlockStatement") - } - } -}); -(0, _utils.default)("UnaryExpression", { - builder: ["operator", "argument", "prefix"], - fields: { - prefix: { - default: true - }, - argument: { - validate: (0, _utils.assertNodeType)("Expression") - }, - operator: { - validate: _utils.assertOneOf.apply(void 0, _constants.UNARY_OPERATORS) - } - }, - visitor: ["argument"], - aliases: ["UnaryLike", "Expression"] -}); -(0, _utils.default)("UpdateExpression", { - builder: ["operator", "argument", "prefix"], - fields: { - prefix: { - default: false - }, - argument: { - validate: (0, _utils.assertNodeType)("Expression") - }, - operator: { - validate: _utils.assertOneOf.apply(void 0, _constants.UPDATE_OPERATORS) - } - }, - visitor: ["argument"], - aliases: ["Expression"] -}); -(0, _utils.default)("VariableDeclaration", { - builder: ["kind", "declarations"], - visitor: ["declarations"], - aliases: ["Statement", "Declaration"], - fields: { - declare: { - validate: (0, _utils.assertValueType)("boolean"), - optional: true - }, - kind: { - validate: (0, _utils.chain)((0, _utils.assertValueType)("string"), (0, _utils.assertOneOf)("var", "let", "const")) - }, - declarations: { - validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("VariableDeclarator"))) - } - } -}); -(0, _utils.default)("VariableDeclarator", { - visitor: ["id", "init"], - fields: { - id: { - validate: (0, _utils.assertNodeType)("LVal") - }, - init: { - optional: true, - validate: (0, _utils.assertNodeType)("Expression") - } - } -}); -(0, _utils.default)("WhileStatement", { - visitor: ["test", "body"], - aliases: ["Statement", "BlockParent", "Loop", "While", "Scopable"], - fields: { - test: { - validate: (0, _utils.assertNodeType)("Expression") - }, - body: { - validate: (0, _utils.assertNodeType)("BlockStatement", "Statement") - } - } -}); -(0, _utils.default)("WithStatement", { - visitor: ["object", "body"], - aliases: ["Statement"], - fields: { - object: { - validate: (0, _utils.assertNodeType)("Expression") - }, - body: { - validate: (0, _utils.assertNodeType)("BlockStatement", "Statement") - } - } -}); \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/definitions/es2015.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/definitions/es2015.js deleted file mode 100644 index 62e2b4b0c27848..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/definitions/es2015.js +++ /dev/null @@ -1,379 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.classMethodOrDeclareMethodCommon = exports.classMethodOrPropertyCommon = void 0; - -var _utils = _interopRequireWildcard(require("./utils")); - -var _core = require("./core"); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } - -(0, _utils.default)("AssignmentPattern", { - visitor: ["left", "right"], - builder: ["left", "right"], - aliases: ["Pattern", "PatternLike", "LVal"], - fields: Object.assign({}, _core.patternLikeCommon, { - left: { - validate: (0, _utils.assertNodeType)("Identifier", "ObjectPattern", "ArrayPattern") - }, - right: { - validate: (0, _utils.assertNodeType)("Expression") - }, - decorators: { - validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator"))) - } - }) -}); -(0, _utils.default)("ArrayPattern", { - visitor: ["elements", "typeAnnotation"], - builder: ["elements"], - aliases: ["Pattern", "PatternLike", "LVal"], - fields: Object.assign({}, _core.patternLikeCommon, { - elements: { - validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("PatternLike"))) - }, - decorators: { - validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator"))) - } - }) -}); -(0, _utils.default)("ArrowFunctionExpression", { - builder: ["params", "body", "async"], - visitor: ["params", "body", "returnType", "typeParameters"], - aliases: ["Scopable", "Function", "BlockParent", "FunctionParent", "Expression", "Pureish"], - fields: Object.assign({}, _core.functionCommon, _core.functionTypeAnnotationCommon, { - expression: { - validate: (0, _utils.assertValueType)("boolean") - }, - body: { - validate: (0, _utils.assertNodeType)("BlockStatement", "Expression") - } - }) -}); -(0, _utils.default)("ClassBody", { - visitor: ["body"], - fields: { - body: { - validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("ClassMethod", "ClassProperty", "TSDeclareMethod", "TSIndexSignature"))) - } - } -}); -var classCommon = { - typeParameters: { - validate: (0, _utils.assertNodeType)("TypeParameterDeclaration", "TSTypeParameterDeclaration", "Noop"), - optional: true - }, - body: { - validate: (0, _utils.assertNodeType)("ClassBody") - }, - superClass: { - optional: true, - validate: (0, _utils.assertNodeType)("Expression") - }, - superTypeParameters: { - validate: (0, _utils.assertNodeType)("TypeParameterInstantiation", "TSTypeParameterInstantiation"), - optional: true - }, - implements: { - validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("TSExpressionWithTypeArguments", "FlowClassImplements"))), - optional: true - } -}; -(0, _utils.default)("ClassDeclaration", { - builder: ["id", "superClass", "body", "decorators"], - visitor: ["id", "body", "superClass", "mixins", "typeParameters", "superTypeParameters", "implements", "decorators"], - aliases: ["Scopable", "Class", "Statement", "Declaration", "Pureish"], - fields: Object.assign({}, classCommon, { - declare: { - validate: (0, _utils.assertValueType)("boolean"), - optional: true - }, - abstract: { - validate: (0, _utils.assertValueType)("boolean"), - optional: true - }, - id: { - validate: (0, _utils.assertNodeType)("Identifier"), - optional: true - }, - decorators: { - validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator"))), - optional: true - } - }) -}); -(0, _utils.default)("ClassExpression", { - inherits: "ClassDeclaration", - aliases: ["Scopable", "Class", "Expression", "Pureish"], - fields: Object.assign({}, classCommon, { - id: { - optional: true, - validate: (0, _utils.assertNodeType)("Identifier") - }, - body: { - validate: (0, _utils.assertNodeType)("ClassBody") - }, - superClass: { - optional: true, - validate: (0, _utils.assertNodeType)("Expression") - }, - decorators: { - validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator"))), - optional: true - } - }) -}); -(0, _utils.default)("ExportAllDeclaration", { - visitor: ["source"], - aliases: ["Statement", "Declaration", "ModuleDeclaration", "ExportDeclaration"], - fields: { - source: { - validate: (0, _utils.assertNodeType)("StringLiteral") - } - } -}); -(0, _utils.default)("ExportDefaultDeclaration", { - visitor: ["declaration"], - aliases: ["Statement", "Declaration", "ModuleDeclaration", "ExportDeclaration"], - fields: { - declaration: { - validate: (0, _utils.assertNodeType)("FunctionDeclaration", "TSDeclareFunction", "ClassDeclaration", "Expression") - } - } -}); -(0, _utils.default)("ExportNamedDeclaration", { - visitor: ["declaration", "specifiers", "source"], - aliases: ["Statement", "Declaration", "ModuleDeclaration", "ExportDeclaration"], - fields: { - declaration: { - validate: (0, _utils.assertNodeType)("Declaration"), - optional: true - }, - specifiers: { - validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("ExportSpecifier", "ExportDefaultSpecifier", "ExportNamespaceSpecifier"))) - }, - source: { - validate: (0, _utils.assertNodeType)("StringLiteral"), - optional: true - } - } -}); -(0, _utils.default)("ExportSpecifier", { - visitor: ["local", "exported"], - aliases: ["ModuleSpecifier"], - fields: { - local: { - validate: (0, _utils.assertNodeType)("Identifier") - }, - exported: { - validate: (0, _utils.assertNodeType)("Identifier") - } - } -}); -(0, _utils.default)("ForOfStatement", { - visitor: ["left", "right", "body"], - aliases: ["Scopable", "Statement", "For", "BlockParent", "Loop", "ForXStatement"], - fields: { - left: { - validate: (0, _utils.assertNodeType)("VariableDeclaration", "LVal") - }, - right: { - validate: (0, _utils.assertNodeType)("Expression") - }, - body: { - validate: (0, _utils.assertNodeType)("Statement") - }, - await: { - default: false, - validate: (0, _utils.assertValueType)("boolean") - } - } -}); -(0, _utils.default)("ImportDeclaration", { - visitor: ["specifiers", "source"], - aliases: ["Statement", "Declaration", "ModuleDeclaration"], - fields: { - specifiers: { - validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("ImportSpecifier", "ImportDefaultSpecifier", "ImportNamespaceSpecifier"))) - }, - source: { - validate: (0, _utils.assertNodeType)("StringLiteral") - } - } -}); -(0, _utils.default)("ImportDefaultSpecifier", { - visitor: ["local"], - aliases: ["ModuleSpecifier"], - fields: { - local: { - validate: (0, _utils.assertNodeType)("Identifier") - } - } -}); -(0, _utils.default)("ImportNamespaceSpecifier", { - visitor: ["local"], - aliases: ["ModuleSpecifier"], - fields: { - local: { - validate: (0, _utils.assertNodeType)("Identifier") - } - } -}); -(0, _utils.default)("ImportSpecifier", { - visitor: ["local", "imported"], - aliases: ["ModuleSpecifier"], - fields: { - local: { - validate: (0, _utils.assertNodeType)("Identifier") - }, - imported: { - validate: (0, _utils.assertNodeType)("Identifier") - }, - importKind: { - validate: (0, _utils.assertOneOf)(null, "type", "typeof") - } - } -}); -(0, _utils.default)("MetaProperty", { - visitor: ["meta", "property"], - aliases: ["Expression"], - fields: { - meta: { - validate: (0, _utils.assertNodeType)("Identifier") - }, - property: { - validate: (0, _utils.assertNodeType)("Identifier") - } - } -}); -var classMethodOrPropertyCommon = { - abstract: { - validate: (0, _utils.assertValueType)("boolean"), - optional: true - }, - accessibility: { - validate: (0, _utils.chain)((0, _utils.assertValueType)("string"), (0, _utils.assertOneOf)("public", "private", "protected")), - optional: true - }, - static: { - validate: (0, _utils.assertValueType)("boolean"), - optional: true - }, - computed: { - default: false, - validate: (0, _utils.assertValueType)("boolean") - }, - optional: { - validate: (0, _utils.assertValueType)("boolean"), - optional: true - }, - key: { - validate: function () { - var normal = (0, _utils.assertNodeType)("Identifier", "StringLiteral", "NumericLiteral"); - var computed = (0, _utils.assertNodeType)("Expression"); - return function (node, key, val) { - var validator = node.computed ? computed : normal; - validator(node, key, val); - }; - }() - } -}; -exports.classMethodOrPropertyCommon = classMethodOrPropertyCommon; -var classMethodOrDeclareMethodCommon = Object.assign({}, _core.functionCommon, classMethodOrPropertyCommon, { - kind: { - validate: (0, _utils.chain)((0, _utils.assertValueType)("string"), (0, _utils.assertOneOf)("get", "set", "method", "constructor")), - default: "method" - }, - access: { - validate: (0, _utils.chain)((0, _utils.assertValueType)("string"), (0, _utils.assertOneOf)("public", "private", "protected")), - optional: true - }, - decorators: { - validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator"))), - optional: true - } -}); -exports.classMethodOrDeclareMethodCommon = classMethodOrDeclareMethodCommon; -(0, _utils.default)("ClassMethod", { - aliases: ["Function", "Scopable", "BlockParent", "FunctionParent", "Method"], - builder: ["kind", "key", "params", "body", "computed", "static"], - visitor: ["key", "params", "body", "decorators", "returnType", "typeParameters"], - fields: Object.assign({}, classMethodOrDeclareMethodCommon, _core.functionTypeAnnotationCommon, { - body: { - validate: (0, _utils.assertNodeType)("BlockStatement") - } - }) -}); -(0, _utils.default)("ObjectPattern", { - visitor: ["properties", "typeAnnotation"], - builder: ["properties"], - aliases: ["Pattern", "PatternLike", "LVal"], - fields: Object.assign({}, _core.patternLikeCommon, { - properties: { - validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("RestElement", "ObjectProperty"))) - } - }) -}); -(0, _utils.default)("SpreadElement", { - visitor: ["argument"], - aliases: ["UnaryLike"], - deprecatedAlias: "SpreadProperty", - fields: { - argument: { - validate: (0, _utils.assertNodeType)("Expression") - } - } -}); -(0, _utils.default)("Super", { - aliases: ["Expression"] -}); -(0, _utils.default)("TaggedTemplateExpression", { - visitor: ["tag", "quasi"], - aliases: ["Expression"], - fields: { - tag: { - validate: (0, _utils.assertNodeType)("Expression") - }, - quasi: { - validate: (0, _utils.assertNodeType)("TemplateLiteral") - } - } -}); -(0, _utils.default)("TemplateElement", { - builder: ["value", "tail"], - fields: { - value: {}, - tail: { - validate: (0, _utils.assertValueType)("boolean"), - default: false - } - } -}); -(0, _utils.default)("TemplateLiteral", { - visitor: ["quasis", "expressions"], - aliases: ["Expression", "Literal"], - fields: { - quasis: { - validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("TemplateElement"))) - }, - expressions: { - validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Expression"))) - } - } -}); -(0, _utils.default)("YieldExpression", { - builder: ["argument", "delegate"], - visitor: ["argument"], - aliases: ["Expression", "Terminatorless"], - fields: { - delegate: { - validate: (0, _utils.assertValueType)("boolean"), - default: false - }, - argument: { - optional: true, - validate: (0, _utils.assertNodeType)("Expression") - } - } -}); \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/definitions/experimental.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/definitions/experimental.js deleted file mode 100644 index 968f3009d868b9..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/definitions/experimental.js +++ /dev/null @@ -1,84 +0,0 @@ -"use strict"; - -var _utils = _interopRequireWildcard(require("./utils")); - -var _es = require("./es2015"); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } - -(0, _utils.default)("AwaitExpression", { - builder: ["argument"], - visitor: ["argument"], - aliases: ["Expression", "Terminatorless"], - fields: { - argument: { - validate: (0, _utils.assertNodeType)("Expression") - } - } -}); -(0, _utils.default)("BindExpression", { - visitor: ["object", "callee"], - aliases: ["Expression"], - fields: {} -}); -(0, _utils.default)("ClassProperty", { - visitor: ["key", "value", "typeAnnotation", "decorators"], - builder: ["key", "value", "typeAnnotation", "decorators", "computed"], - aliases: ["Property"], - fields: Object.assign({}, _es.classMethodOrPropertyCommon, { - value: { - validate: (0, _utils.assertNodeType)("Expression"), - optional: true - }, - typeAnnotation: { - validate: (0, _utils.assertNodeType)("TypeAnnotation", "TSTypeAnnotation", "Noop"), - optional: true - }, - decorators: { - validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator"))), - optional: true - }, - readonly: { - validate: (0, _utils.assertValueType)("boolean"), - optional: true - } - }) -}); -(0, _utils.default)("Import", { - aliases: ["Expression"] -}); -(0, _utils.default)("Decorator", { - visitor: ["expression"], - fields: { - expression: { - validate: (0, _utils.assertNodeType)("Expression") - } - } -}); -(0, _utils.default)("DoExpression", { - visitor: ["body"], - aliases: ["Expression"], - fields: { - body: { - validate: (0, _utils.assertNodeType)("BlockStatement") - } - } -}); -(0, _utils.default)("ExportDefaultSpecifier", { - visitor: ["exported"], - aliases: ["ModuleSpecifier"], - fields: { - exported: { - validate: (0, _utils.assertNodeType)("Identifier") - } - } -}); -(0, _utils.default)("ExportNamespaceSpecifier", { - visitor: ["exported"], - aliases: ["ModuleSpecifier"], - fields: { - exported: { - validate: (0, _utils.assertNodeType)("Identifier") - } - } -}); \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/definitions/flow.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/definitions/flow.js deleted file mode 100644 index db54ee1a953b9e..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/definitions/flow.js +++ /dev/null @@ -1,263 +0,0 @@ -"use strict"; - -var _utils = _interopRequireWildcard(require("./utils")); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } - -(0, _utils.default)("AnyTypeAnnotation", { - aliases: ["Flow", "FlowBaseAnnotation"], - fields: {} -}); -(0, _utils.default)("ArrayTypeAnnotation", { - visitor: ["elementType"], - aliases: ["Flow"], - fields: {} -}); -(0, _utils.default)("BooleanTypeAnnotation", { - aliases: ["Flow", "FlowBaseAnnotation"], - fields: {} -}); -(0, _utils.default)("BooleanLiteralTypeAnnotation", { - aliases: ["Flow"], - fields: {} -}); -(0, _utils.default)("NullLiteralTypeAnnotation", { - aliases: ["Flow", "FlowBaseAnnotation"], - fields: {} -}); -(0, _utils.default)("ClassImplements", { - visitor: ["id", "typeParameters"], - aliases: ["Flow"], - fields: {} -}); -(0, _utils.default)("DeclareClass", { - visitor: ["id", "typeParameters", "extends", "body"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); -(0, _utils.default)("DeclareFunction", { - visitor: ["id"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); -(0, _utils.default)("DeclareInterface", { - visitor: ["id", "typeParameters", "extends", "body"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); -(0, _utils.default)("DeclareModule", { - visitor: ["id", "body"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); -(0, _utils.default)("DeclareModuleExports", { - visitor: ["typeAnnotation"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); -(0, _utils.default)("DeclareTypeAlias", { - visitor: ["id", "typeParameters", "right"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); -(0, _utils.default)("DeclareOpaqueType", { - visitor: ["id", "typeParameters", "supertype"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); -(0, _utils.default)("DeclareVariable", { - visitor: ["id"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); -(0, _utils.default)("DeclareExportDeclaration", { - visitor: ["declaration", "specifiers", "source"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); -(0, _utils.default)("DeclareExportAllDeclaration", { - visitor: ["source"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); -(0, _utils.default)("DeclaredPredicate", { - visitor: ["value"], - aliases: ["Flow", "FlowPredicate"], - fields: {} -}); -(0, _utils.default)("ExistsTypeAnnotation", { - aliases: ["Flow"] -}); -(0, _utils.default)("FunctionTypeAnnotation", { - visitor: ["typeParameters", "params", "rest", "returnType"], - aliases: ["Flow"], - fields: {} -}); -(0, _utils.default)("FunctionTypeParam", { - visitor: ["name", "typeAnnotation"], - aliases: ["Flow"], - fields: {} -}); -(0, _utils.default)("GenericTypeAnnotation", { - visitor: ["id", "typeParameters"], - aliases: ["Flow"], - fields: {} -}); -(0, _utils.default)("InferredPredicate", { - aliases: ["Flow", "FlowPredicate"], - fields: {} -}); -(0, _utils.default)("InterfaceExtends", { - visitor: ["id", "typeParameters"], - aliases: ["Flow"], - fields: {} -}); -(0, _utils.default)("InterfaceDeclaration", { - visitor: ["id", "typeParameters", "extends", "body"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); -(0, _utils.default)("IntersectionTypeAnnotation", { - visitor: ["types"], - aliases: ["Flow"], - fields: {} -}); -(0, _utils.default)("MixedTypeAnnotation", { - aliases: ["Flow", "FlowBaseAnnotation"] -}); -(0, _utils.default)("EmptyTypeAnnotation", { - aliases: ["Flow", "FlowBaseAnnotation"] -}); -(0, _utils.default)("NullableTypeAnnotation", { - visitor: ["typeAnnotation"], - aliases: ["Flow"], - fields: {} -}); -(0, _utils.default)("NumberLiteralTypeAnnotation", { - aliases: ["Flow"], - fields: {} -}); -(0, _utils.default)("NumberTypeAnnotation", { - aliases: ["Flow", "FlowBaseAnnotation"], - fields: {} -}); -(0, _utils.default)("ObjectTypeAnnotation", { - visitor: ["properties", "indexers", "callProperties"], - aliases: ["Flow"], - fields: {} -}); -(0, _utils.default)("ObjectTypeCallProperty", { - visitor: ["value"], - aliases: ["Flow", "UserWhitespacable"], - fields: {} -}); -(0, _utils.default)("ObjectTypeIndexer", { - visitor: ["id", "key", "value"], - aliases: ["Flow", "UserWhitespacable"], - fields: {} -}); -(0, _utils.default)("ObjectTypeProperty", { - visitor: ["key", "value"], - aliases: ["Flow", "UserWhitespacable"], - fields: {} -}); -(0, _utils.default)("ObjectTypeSpreadProperty", { - visitor: ["argument"], - aliases: ["Flow", "UserWhitespacable"], - fields: {} -}); -(0, _utils.default)("OpaqueType", { - visitor: ["id", "typeParameters", "supertype", "impltype"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); -(0, _utils.default)("QualifiedTypeIdentifier", { - visitor: ["id", "qualification"], - aliases: ["Flow"], - fields: {} -}); -(0, _utils.default)("StringLiteralTypeAnnotation", { - aliases: ["Flow"], - fields: {} -}); -(0, _utils.default)("StringTypeAnnotation", { - aliases: ["Flow", "FlowBaseAnnotation"], - fields: {} -}); -(0, _utils.default)("ThisTypeAnnotation", { - aliases: ["Flow", "FlowBaseAnnotation"], - fields: {} -}); -(0, _utils.default)("TupleTypeAnnotation", { - visitor: ["types"], - aliases: ["Flow"], - fields: {} -}); -(0, _utils.default)("TypeofTypeAnnotation", { - visitor: ["argument"], - aliases: ["Flow"], - fields: {} -}); -(0, _utils.default)("TypeAlias", { - visitor: ["id", "typeParameters", "right"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); -(0, _utils.default)("TypeAnnotation", { - aliases: ["Flow"], - visitor: ["typeAnnotation"], - fields: { - typeAnnotation: { - validate: (0, _utils.assertNodeType)("Flow") - } - } -}); -(0, _utils.default)("TypeCastExpression", { - visitor: ["expression", "typeAnnotation"], - aliases: ["Flow", "ExpressionWrapper", "Expression"], - fields: {} -}); -(0, _utils.default)("TypeParameter", { - aliases: ["Flow"], - visitor: ["bound", "default"], - fields: { - name: { - validate: (0, _utils.assertValueType)("string") - }, - bound: { - validate: (0, _utils.assertNodeType)("TypeAnnotation"), - optional: true - }, - default: { - validate: (0, _utils.assertNodeType)("Flow"), - optional: true - } - } -}); -(0, _utils.default)("TypeParameterDeclaration", { - aliases: ["Flow"], - visitor: ["params"], - fields: { - params: { - validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("TypeParameter"))) - } - } -}); -(0, _utils.default)("TypeParameterInstantiation", { - aliases: ["Flow"], - visitor: ["params"], - fields: { - params: { - validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Flow"))) - } - } -}); -(0, _utils.default)("UnionTypeAnnotation", { - visitor: ["types"], - aliases: ["Flow"], - fields: {} -}); -(0, _utils.default)("VoidTypeAnnotation", { - aliases: ["Flow", "FlowBaseAnnotation"], - fields: {} -}); \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/definitions/index.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/definitions/index.js deleted file mode 100644 index a0bbfb84678026..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/definitions/index.js +++ /dev/null @@ -1,40 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.TYPES = void 0; - -var _toFastProperties = _interopRequireDefault(require("to-fast-properties")); - -require("./core"); - -require("./es2015"); - -require("./flow"); - -require("./jsx"); - -require("./misc"); - -require("./experimental"); - -require("./typescript"); - -var _utils = require("./utils"); - -exports.VISITOR_KEYS = _utils.VISITOR_KEYS; -exports.ALIAS_KEYS = _utils.ALIAS_KEYS; -exports.FLIPPED_ALIAS_KEYS = _utils.FLIPPED_ALIAS_KEYS; -exports.NODE_FIELDS = _utils.NODE_FIELDS; -exports.BUILDER_KEYS = _utils.BUILDER_KEYS; -exports.DEPRECATED_KEYS = _utils.DEPRECATED_KEYS; - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -(0, _toFastProperties.default)(_utils.VISITOR_KEYS); -(0, _toFastProperties.default)(_utils.ALIAS_KEYS); -(0, _toFastProperties.default)(_utils.FLIPPED_ALIAS_KEYS); -(0, _toFastProperties.default)(_utils.NODE_FIELDS); -(0, _toFastProperties.default)(_utils.BUILDER_KEYS); -(0, _toFastProperties.default)(_utils.DEPRECATED_KEYS); -var TYPES = Object.keys(_utils.VISITOR_KEYS).concat(Object.keys(_utils.FLIPPED_ALIAS_KEYS)).concat(Object.keys(_utils.DEPRECATED_KEYS)); -exports.TYPES = TYPES; \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/definitions/jsx.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/definitions/jsx.js deleted file mode 100644 index 0ed8978b12e168..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/definitions/jsx.js +++ /dev/null @@ -1,156 +0,0 @@ -"use strict"; - -var _utils = _interopRequireWildcard(require("./utils")); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } - -(0, _utils.default)("JSXAttribute", { - visitor: ["name", "value"], - aliases: ["JSX", "Immutable"], - fields: { - name: { - validate: (0, _utils.assertNodeType)("JSXIdentifier", "JSXNamespacedName") - }, - value: { - optional: true, - validate: (0, _utils.assertNodeType)("JSXElement", "JSXFragment", "StringLiteral", "JSXExpressionContainer") - } - } -}); -(0, _utils.default)("JSXClosingElement", { - visitor: ["name"], - aliases: ["JSX", "Immutable"], - fields: { - name: { - validate: (0, _utils.assertNodeType)("JSXIdentifier", "JSXMemberExpression") - } - } -}); -(0, _utils.default)("JSXElement", { - builder: ["openingElement", "closingElement", "children", "selfClosing"], - visitor: ["openingElement", "children", "closingElement"], - aliases: ["JSX", "Immutable", "Expression"], - fields: { - openingElement: { - validate: (0, _utils.assertNodeType)("JSXOpeningElement") - }, - closingElement: { - optional: true, - validate: (0, _utils.assertNodeType)("JSXClosingElement") - }, - children: { - validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("JSXText", "JSXExpressionContainer", "JSXSpreadChild", "JSXElement", "JSXFragment"))) - } - } -}); -(0, _utils.default)("JSXEmptyExpression", { - aliases: ["JSX"] -}); -(0, _utils.default)("JSXExpressionContainer", { - visitor: ["expression"], - aliases: ["JSX", "Immutable"], - fields: { - expression: { - validate: (0, _utils.assertNodeType)("Expression") - } - } -}); -(0, _utils.default)("JSXSpreadChild", { - visitor: ["expression"], - aliases: ["JSX", "Immutable"], - fields: { - expression: { - validate: (0, _utils.assertNodeType)("Expression") - } - } -}); -(0, _utils.default)("JSXIdentifier", { - builder: ["name"], - aliases: ["JSX"], - fields: { - name: { - validate: (0, _utils.assertValueType)("string") - } - } -}); -(0, _utils.default)("JSXMemberExpression", { - visitor: ["object", "property"], - aliases: ["JSX"], - fields: { - object: { - validate: (0, _utils.assertNodeType)("JSXMemberExpression", "JSXIdentifier") - }, - property: { - validate: (0, _utils.assertNodeType)("JSXIdentifier") - } - } -}); -(0, _utils.default)("JSXNamespacedName", { - visitor: ["namespace", "name"], - aliases: ["JSX"], - fields: { - namespace: { - validate: (0, _utils.assertNodeType)("JSXIdentifier") - }, - name: { - validate: (0, _utils.assertNodeType)("JSXIdentifier") - } - } -}); -(0, _utils.default)("JSXOpeningElement", { - builder: ["name", "attributes", "selfClosing"], - visitor: ["name", "attributes"], - aliases: ["JSX", "Immutable"], - fields: { - name: { - validate: (0, _utils.assertNodeType)("JSXIdentifier", "JSXMemberExpression") - }, - selfClosing: { - default: false, - validate: (0, _utils.assertValueType)("boolean") - }, - attributes: { - validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("JSXAttribute", "JSXSpreadAttribute"))) - } - } -}); -(0, _utils.default)("JSXSpreadAttribute", { - visitor: ["argument"], - aliases: ["JSX"], - fields: { - argument: { - validate: (0, _utils.assertNodeType)("Expression") - } - } -}); -(0, _utils.default)("JSXText", { - aliases: ["JSX", "Immutable"], - builder: ["value"], - fields: { - value: { - validate: (0, _utils.assertValueType)("string") - } - } -}); -(0, _utils.default)("JSXFragment", { - builder: ["openingFragment", "closingFragment", "children"], - visitor: ["openingFragment", "children", "closingFragment"], - aliases: ["JSX", "Immutable", "Expression"], - fields: { - openingFragment: { - validate: (0, _utils.assertNodeType)("JSXOpeningFragment") - }, - closingFragment: { - validate: (0, _utils.assertNodeType)("JSXClosingFragment") - }, - children: { - validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("JSXText", "JSXExpressionContainer", "JSXSpreadChild", "JSXElement", "JSXFragment"))) - } - } -}); -(0, _utils.default)("JSXOpeningFragment", { - aliases: ["JSX", "Immutable"] -}); -(0, _utils.default)("JSXClosingFragment", { - aliases: ["JSX", "Immutable"] -}); \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/definitions/misc.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/definitions/misc.js deleted file mode 100644 index 714f2979447e2a..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/definitions/misc.js +++ /dev/null @@ -1,18 +0,0 @@ -"use strict"; - -var _utils = _interopRequireWildcard(require("./utils")); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } - -(0, _utils.default)("Noop", { - visitor: [] -}); -(0, _utils.default)("ParenthesizedExpression", { - visitor: ["expression"], - aliases: ["Expression", "ExpressionWrapper"], - fields: { - expression: { - validate: (0, _utils.assertNodeType)("Expression") - } - } -}); \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/definitions/typescript.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/definitions/typescript.js deleted file mode 100644 index 90dca181f26981..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/definitions/typescript.js +++ /dev/null @@ -1,413 +0,0 @@ -"use strict"; - -var _utils = _interopRequireWildcard(require("./utils")); - -var _core = require("./core"); - -var _es = require("./es2015"); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } - -var bool = (0, _utils.assertValueType)("boolean"); - -function validate(validate) { - return { - validate: validate - }; -} - -function typeIs(typeName) { - return typeof typeName === "string" ? (0, _utils.assertNodeType)(typeName) : _utils.assertNodeType.apply(void 0, typeName); -} - -function validateType(name) { - return validate(typeIs(name)); -} - -function validateOptional(validate) { - return { - validate: validate, - optional: true - }; -} - -function validateOptionalType(typeName) { - return { - validate: typeIs(typeName), - optional: true - }; -} - -function arrayOf(elementType) { - return (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)(elementType)); -} - -function arrayOfType(nodeTypeName) { - return arrayOf(typeIs(nodeTypeName)); -} - -function validateArrayOfType(nodeTypeName) { - return validate(arrayOfType(nodeTypeName)); -} - -var tSFunctionTypeAnnotationCommon = { - returnType: { - validate: (0, _utils.assertNodeType)("TSTypeAnnotation", "Noop"), - optional: true - }, - typeParameters: { - validate: (0, _utils.assertNodeType)("TSTypeParameterDeclaration", "Noop"), - optional: true - } -}; -(0, _utils.default)("TSParameterProperty", { - aliases: ["LVal"], - visitor: ["parameter"], - fields: { - accessibility: { - validate: (0, _utils.assertOneOf)("public", "private", "protected"), - optional: true - }, - readonly: { - validate: (0, _utils.assertValueType)("boolean"), - optional: true - }, - parameter: { - validate: (0, _utils.assertNodeType)("Identifier", "AssignmentPattern") - } - } -}); -(0, _utils.default)("TSDeclareFunction", { - aliases: ["Statement", "Declaration"], - visitor: ["id", "typeParameters", "params", "returnType"], - fields: Object.assign({}, _core.functionDeclarationCommon, tSFunctionTypeAnnotationCommon) -}); -(0, _utils.default)("TSDeclareMethod", { - visitor: ["decorators", "key", "typeParameters", "params", "returnType"], - fields: Object.assign({}, _es.classMethodOrDeclareMethodCommon, tSFunctionTypeAnnotationCommon) -}); -(0, _utils.default)("TSQualifiedName", { - aliases: ["TSEntityName"], - visitor: ["left", "right"], - fields: { - left: validateType("TSEntityName"), - right: validateType("Identifier") - } -}); -var signatureDeclarationCommon = { - typeParameters: validateOptionalType("TSTypeParameterDeclaration"), - parameters: validateArrayOfType(["Identifier", "RestElement"]), - typeAnnotation: validateOptionalType("TSTypeAnnotation") -}; -var callConstructSignatureDeclaration = { - aliases: ["TSTypeElement"], - visitor: ["typeParameters", "parameters", "typeAnnotation"], - fields: signatureDeclarationCommon -}; -(0, _utils.default)("TSCallSignatureDeclaration", callConstructSignatureDeclaration); -(0, _utils.default)("TSConstructSignatureDeclaration", callConstructSignatureDeclaration); -var namedTypeElementCommon = { - key: validateType("Expression"), - computed: validate(bool), - optional: validateOptional(bool) -}; -(0, _utils.default)("TSPropertySignature", { - aliases: ["TSTypeElement"], - visitor: ["key", "typeAnnotation", "initializer"], - fields: Object.assign({}, namedTypeElementCommon, { - readonly: validateOptional(bool), - typeAnnotation: validateOptionalType("TSTypeAnnotation"), - initializer: validateOptionalType("Expression") - }) -}); -(0, _utils.default)("TSMethodSignature", { - aliases: ["TSTypeElement"], - visitor: ["key", "typeParameters", "parameters", "typeAnnotation"], - fields: Object.assign({}, signatureDeclarationCommon, namedTypeElementCommon) -}); -(0, _utils.default)("TSIndexSignature", { - aliases: ["TSTypeElement"], - visitor: ["parameters", "typeAnnotation"], - fields: { - readonly: validateOptional(bool), - parameters: validateArrayOfType("Identifier"), - typeAnnotation: validateOptionalType("TSTypeAnnotation") - } -}); -var tsKeywordTypes = ["TSAnyKeyword", "TSNumberKeyword", "TSObjectKeyword", "TSBooleanKeyword", "TSStringKeyword", "TSSymbolKeyword", "TSVoidKeyword", "TSUndefinedKeyword", "TSNullKeyword", "TSNeverKeyword"]; - -for (var _i = 0; _i < tsKeywordTypes.length; _i++) { - var type = tsKeywordTypes[_i]; - (0, _utils.default)(type, { - aliases: ["TSType"], - visitor: [], - fields: {} - }); -} - -(0, _utils.default)("TSThisType", { - aliases: ["TSType"], - visitor: [], - fields: {} -}); -var fnOrCtr = { - aliases: ["TSType"], - visitor: ["typeParameters", "typeAnnotation"], - fields: signatureDeclarationCommon -}; -(0, _utils.default)("TSFunctionType", fnOrCtr); -(0, _utils.default)("TSConstructorType", fnOrCtr); -(0, _utils.default)("TSTypeReference", { - aliases: ["TSType"], - visitor: ["typeName", "typeParameters"], - fields: { - typeName: validateType("TSEntityName"), - typeParameters: validateOptionalType("TSTypeParameterInstantiation") - } -}); -(0, _utils.default)("TSTypePredicate", { - aliases: ["TSType"], - visitor: ["parameterName", "typeAnnotation"], - fields: { - parameterName: validateType(["Identifier", "TSThisType"]), - typeAnnotation: validateType("TSTypeAnnotation") - } -}); -(0, _utils.default)("TSTypeQuery", { - aliases: ["TSType"], - visitor: ["exprName"], - fields: { - exprName: validateType("TSEntityName") - } -}); -(0, _utils.default)("TSTypeLiteral", { - aliases: ["TSType"], - visitor: ["members"], - fields: { - members: validateArrayOfType("TSTypeElement") - } -}); -(0, _utils.default)("TSArrayType", { - aliases: ["TSType"], - visitor: ["elementType"], - fields: { - elementType: validateType("TSType") - } -}); -(0, _utils.default)("TSTupleType", { - aliases: ["TSType"], - visitor: ["elementTypes"], - fields: { - elementTypes: validateArrayOfType("TSType") - } -}); -var unionOrIntersection = { - aliases: ["TSType"], - visitor: ["types"], - fields: { - types: validateArrayOfType("TSType") - } -}; -(0, _utils.default)("TSUnionType", unionOrIntersection); -(0, _utils.default)("TSIntersectionType", unionOrIntersection); -(0, _utils.default)("TSParenthesizedType", { - aliases: ["TSType"], - visitor: ["typeAnnotation"], - fields: { - typeAnnotation: validateType("TSType") - } -}); -(0, _utils.default)("TSTypeOperator", { - aliases: ["TSType"], - visitor: ["typeAnnotation"], - fields: { - operator: validate((0, _utils.assertValueType)("string")), - typeAnnotation: validateType("TSType") - } -}); -(0, _utils.default)("TSIndexedAccessType", { - aliases: ["TSType"], - visitor: ["objectType", "indexType"], - fields: { - objectType: validateType("TSType"), - indexType: validateType("TSType") - } -}); -(0, _utils.default)("TSMappedType", { - aliases: ["TSType"], - visitor: ["typeParameter", "typeAnnotation"], - fields: { - readonly: validateOptional(bool), - typeParameter: validateType("TSTypeParameter"), - optional: validateOptional(bool), - typeAnnotation: validateOptionalType("TSType") - } -}); -(0, _utils.default)("TSLiteralType", { - aliases: ["TSType"], - visitor: ["literal"], - fields: { - literal: validateType(["NumericLiteral", "StringLiteral", "BooleanLiteral"]) - } -}); -(0, _utils.default)("TSExpressionWithTypeArguments", { - aliases: ["TSType"], - visitor: ["expression", "typeParameters"], - fields: { - expression: validateType("TSEntityName"), - typeParameters: validateOptionalType("TSTypeParameterInstantiation") - } -}); -(0, _utils.default)("TSInterfaceDeclaration", { - aliases: ["Statement", "Declaration"], - visitor: ["id", "typeParameters", "extends", "body"], - fields: { - declare: validateOptional(bool), - id: validateType("Identifier"), - typeParameters: validateOptionalType("TSTypeParameterDeclaration"), - extends: validateOptional(arrayOfType("TSExpressionWithTypeArguments")), - body: validateType("TSInterfaceBody") - } -}); -(0, _utils.default)("TSInterfaceBody", { - visitor: ["body"], - fields: { - body: validateArrayOfType("TSTypeElement") - } -}); -(0, _utils.default)("TSTypeAliasDeclaration", { - aliases: ["Statement", "Declaration"], - visitor: ["id", "typeParameters", "typeAnnotation"], - fields: { - declare: validateOptional(bool), - id: validateType("Identifier"), - typeParameters: validateOptionalType("TSTypeParameterDeclaration"), - typeAnnotation: validateType("TSType") - } -}); -(0, _utils.default)("TSAsExpression", { - aliases: ["Expression"], - visitor: ["expression", "typeAnnotation"], - fields: { - expression: validateType("Expression"), - typeAnnotation: validateType("TSType") - } -}); -(0, _utils.default)("TSTypeAssertion", { - aliases: ["Expression"], - visitor: ["typeAnnotation", "expression"], - fields: { - typeAnnotation: validateType("TSType"), - expression: validateType("Expression") - } -}); -(0, _utils.default)("TSEnumDeclaration", { - aliases: ["Statement", "Declaration"], - visitor: ["id", "members"], - fields: { - declare: validateOptional(bool), - const: validateOptional(bool), - id: validateType("Identifier"), - members: validateArrayOfType("TSEnumMember"), - initializer: validateOptionalType("Expression") - } -}); -(0, _utils.default)("TSEnumMember", { - visitor: ["id", "initializer"], - fields: { - id: validateType(["Identifier", "StringLiteral"]), - initializer: validateOptionalType("Expression") - } -}); -(0, _utils.default)("TSModuleDeclaration", { - aliases: ["Statement", "Declaration"], - visitor: ["id", "body"], - fields: { - declare: validateOptional(bool), - global: validateOptional(bool), - id: validateType(["Identifier", "StringLiteral"]), - body: validateType(["TSModuleBlock", "TSModuleDeclaration"]) - } -}); -(0, _utils.default)("TSModuleBlock", { - visitor: ["body"], - fields: { - body: validateArrayOfType("Statement") - } -}); -(0, _utils.default)("TSImportEqualsDeclaration", { - aliases: ["Statement"], - visitor: ["id", "moduleReference"], - fields: { - isExport: validate(bool), - id: validateType("Identifier"), - moduleReference: validateType(["TSEntityName", "TSExternalModuleReference"]) - } -}); -(0, _utils.default)("TSExternalModuleReference", { - visitor: ["expression"], - fields: { - expression: validateType("StringLiteral") - } -}); -(0, _utils.default)("TSNonNullExpression", { - aliases: ["Expression"], - visitor: ["expression"], - fields: { - expression: validateType("Expression") - } -}); -(0, _utils.default)("TSExportAssignment", { - aliases: ["Statement"], - visitor: ["expression"], - fields: { - expression: validateType("Expression") - } -}); -(0, _utils.default)("TSNamespaceExportDeclaration", { - aliases: ["Statement"], - visitor: ["id"], - fields: { - id: validateType("Identifier") - } -}); -(0, _utils.default)("TSTypeAnnotation", { - visitor: ["typeAnnotation"], - fields: { - typeAnnotation: { - validate: (0, _utils.assertNodeType)("TSType") - } - } -}); -(0, _utils.default)("TSTypeParameterInstantiation", { - visitor: ["params"], - fields: { - params: { - validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("TSType"))) - } - } -}); -(0, _utils.default)("TSTypeParameterDeclaration", { - visitor: ["params"], - fields: { - params: { - validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("TSTypeParameter"))) - } - } -}); -(0, _utils.default)("TSTypeParameter", { - visitor: ["constraint", "default"], - fields: { - name: { - validate: (0, _utils.assertValueType)("string") - }, - constraint: { - validate: (0, _utils.assertNodeType)("TSType"), - optional: true - }, - default: { - validate: (0, _utils.assertNodeType)("TSType"), - optional: true - } - } -}); \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/definitions/utils.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/definitions/utils.js deleted file mode 100644 index 6d323768cea5c0..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/definitions/utils.js +++ /dev/null @@ -1,198 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.assertEach = assertEach; -exports.assertOneOf = assertOneOf; -exports.assertNodeType = assertNodeType; -exports.assertNodeOrValueType = assertNodeOrValueType; -exports.assertValueType = assertValueType; -exports.chain = chain; -exports.default = defineType; -exports.DEPRECATED_KEYS = exports.BUILDER_KEYS = exports.NODE_FIELDS = exports.FLIPPED_ALIAS_KEYS = exports.ALIAS_KEYS = exports.VISITOR_KEYS = void 0; - -var _is = _interopRequireDefault(require("../validators/is")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var VISITOR_KEYS = {}; -exports.VISITOR_KEYS = VISITOR_KEYS; -var ALIAS_KEYS = {}; -exports.ALIAS_KEYS = ALIAS_KEYS; -var FLIPPED_ALIAS_KEYS = {}; -exports.FLIPPED_ALIAS_KEYS = FLIPPED_ALIAS_KEYS; -var NODE_FIELDS = {}; -exports.NODE_FIELDS = NODE_FIELDS; -var BUILDER_KEYS = {}; -exports.BUILDER_KEYS = BUILDER_KEYS; -var DEPRECATED_KEYS = {}; -exports.DEPRECATED_KEYS = DEPRECATED_KEYS; - -function getType(val) { - if (Array.isArray(val)) { - return "array"; - } else if (val === null) { - return "null"; - } else if (val === undefined) { - return "undefined"; - } else { - return typeof val; - } -} - -function assertEach(callback) { - function validator(node, key, val) { - if (!Array.isArray(val)) return; - - for (var i = 0; i < val.length; i++) { - callback(node, key + "[" + i + "]", val[i]); - } - } - - validator.each = callback; - return validator; -} - -function assertOneOf() { - for (var _len = arguments.length, values = new Array(_len), _key = 0; _key < _len; _key++) { - values[_key] = arguments[_key]; - } - - function validate(node, key, val) { - if (values.indexOf(val) < 0) { - throw new TypeError("Property " + key + " expected value to be one of " + JSON.stringify(values) + " but got " + JSON.stringify(val)); - } - } - - validate.oneOf = values; - return validate; -} - -function assertNodeType() { - for (var _len2 = arguments.length, types = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - types[_key2] = arguments[_key2]; - } - - function validate(node, key, val) { - var valid = false; - - for (var _i = 0; _i < types.length; _i++) { - var type = types[_i]; - - if ((0, _is.default)(type, val)) { - valid = true; - break; - } - } - - if (!valid) { - throw new TypeError("Property " + key + " of " + node.type + " expected node to be of a type " + JSON.stringify(types) + " " + ("but instead got " + JSON.stringify(val && val.type))); - } - } - - validate.oneOfNodeTypes = types; - return validate; -} - -function assertNodeOrValueType() { - for (var _len3 = arguments.length, types = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { - types[_key3] = arguments[_key3]; - } - - function validate(node, key, val) { - var valid = false; - - for (var _i2 = 0; _i2 < types.length; _i2++) { - var type = types[_i2]; - - if (getType(val) === type || (0, _is.default)(type, val)) { - valid = true; - break; - } - } - - if (!valid) { - throw new TypeError("Property " + key + " of " + node.type + " expected node to be of a type " + JSON.stringify(types) + " " + ("but instead got " + JSON.stringify(val && val.type))); - } - } - - validate.oneOfNodeOrValueTypes = types; - return validate; -} - -function assertValueType(type) { - function validate(node, key, val) { - var valid = getType(val) === type; - - if (!valid) { - throw new TypeError("Property " + key + " expected type of " + type + " but got " + getType(val)); - } - } - - validate.type = type; - return validate; -} - -function chain() { - for (var _len4 = arguments.length, fns = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { - fns[_key4] = arguments[_key4]; - } - - function validate() { - for (var _i3 = 0; _i3 < fns.length; _i3++) { - var fn = fns[_i3]; - fn.apply(void 0, arguments); - } - } - - validate.chainOf = fns; - return validate; -} - -function defineType(type, opts) { - if (opts === void 0) { - opts = {}; - } - - var inherits = opts.inherits && store[opts.inherits] || {}; - var fields = opts.fields || inherits.fields || {}; - var visitor = opts.visitor || inherits.visitor || []; - var aliases = opts.aliases || inherits.aliases || []; - var builder = opts.builder || inherits.builder || opts.visitor || []; - - if (opts.deprecatedAlias) { - DEPRECATED_KEYS[opts.deprecatedAlias] = type; - } - - var _arr = visitor.concat(builder); - - for (var _i4 = 0; _i4 < _arr.length; _i4++) { - var key = _arr[_i4]; - fields[key] = fields[key] || {}; - } - - for (var _key5 in fields) { - var field = fields[_key5]; - - if (builder.indexOf(_key5) === -1) { - field.optional = true; - } - - if (field.default === undefined) { - field.default = null; - } else if (!field.validate) { - field.validate = assertValueType(getType(field.default)); - } - } - - VISITOR_KEYS[type] = opts.visitor = visitor; - BUILDER_KEYS[type] = opts.builder = builder; - NODE_FIELDS[type] = opts.fields = fields; - ALIAS_KEYS[type] = opts.aliases = aliases; - aliases.forEach(function (alias) { - FLIPPED_ALIAS_KEYS[alias] = FLIPPED_ALIAS_KEYS[alias] || []; - FLIPPED_ALIAS_KEYS[alias].push(type); - }); - store[type] = opts; -} - -var store = {}; \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/index.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/index.js deleted file mode 100644 index dc6952d70657ab..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/index.js +++ /dev/null @@ -1,325 +0,0 @@ -"use strict"; - -exports.__esModule = true; -var _exportNames = { - assertNode: true, - createTypeAnnotationBasedOnTypeof: true, - createUnionTypeAnnotation: true, - clone: true, - cloneDeep: true, - cloneWithoutLoc: true, - addComment: true, - addComments: true, - inheritInnerComments: true, - inheritLeadingComments: true, - inheritsComments: true, - inheritTrailingComments: true, - removeComments: true, - ensureBlock: true, - toBindingIdentifierName: true, - toBlock: true, - toComputedKey: true, - toExpression: true, - toIdentifier: true, - toKeyAlias: true, - toSequenceExpression: true, - toStatement: true, - valueToNode: true, - appendToMemberExpression: true, - inherits: true, - prependToMemberExpression: true, - removeProperties: true, - removePropertiesDeep: true, - removeTypeDuplicates: true, - getBindingIdentifiers: true, - getOuterBindingIdentifiers: true, - traverse: true, - traverseFast: true, - shallowEqual: true, - is: true, - isBinding: true, - isBlockScoped: true, - isImmutable: true, - isLet: true, - isNode: true, - isNodesEquivalent: true, - isReferenced: true, - isScope: true, - isSpecifierDefault: true, - isType: true, - isValidES3Identifier: true, - isValidIdentifier: true, - isVar: true, - matchesPattern: true, - validate: true, - buildMatchMemberExpression: true, - react: true -}; -exports.react = exports.buildMatchMemberExpression = exports.validate = exports.matchesPattern = exports.isVar = exports.isValidIdentifier = exports.isValidES3Identifier = exports.isType = exports.isSpecifierDefault = exports.isScope = exports.isReferenced = exports.isNodesEquivalent = exports.isNode = exports.isLet = exports.isImmutable = exports.isBlockScoped = exports.isBinding = exports.is = exports.shallowEqual = exports.traverseFast = exports.traverse = exports.getOuterBindingIdentifiers = exports.getBindingIdentifiers = exports.removeTypeDuplicates = exports.removePropertiesDeep = exports.removeProperties = exports.prependToMemberExpression = exports.inherits = exports.appendToMemberExpression = exports.valueToNode = exports.toStatement = exports.toSequenceExpression = exports.toKeyAlias = exports.toIdentifier = exports.toExpression = exports.toComputedKey = exports.toBlock = exports.toBindingIdentifierName = exports.ensureBlock = exports.removeComments = exports.inheritTrailingComments = exports.inheritsComments = exports.inheritLeadingComments = exports.inheritInnerComments = exports.addComments = exports.addComment = exports.cloneWithoutLoc = exports.cloneDeep = exports.clone = exports.createUnionTypeAnnotation = exports.createTypeAnnotationBasedOnTypeof = exports.assertNode = void 0; - -var _isReactComponent = _interopRequireDefault(require("./validators/react/isReactComponent")); - -var _isCompatTag = _interopRequireDefault(require("./validators/react/isCompatTag")); - -var _buildChildren = _interopRequireDefault(require("./builders/react/buildChildren")); - -var _assertNode = _interopRequireDefault(require("./asserts/assertNode")); - -exports.assertNode = _assertNode.default; - -var _generated = require("./asserts/generated"); - -Object.keys(_generated).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; - exports[key] = _generated[key]; -}); - -var _createTypeAnnotationBasedOnTypeof = _interopRequireDefault(require("./builders/flow/createTypeAnnotationBasedOnTypeof")); - -exports.createTypeAnnotationBasedOnTypeof = _createTypeAnnotationBasedOnTypeof.default; - -var _createUnionTypeAnnotation = _interopRequireDefault(require("./builders/flow/createUnionTypeAnnotation")); - -exports.createUnionTypeAnnotation = _createUnionTypeAnnotation.default; - -var _generated2 = require("./builders/generated"); - -Object.keys(_generated2).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; - exports[key] = _generated2[key]; -}); - -var _clone = _interopRequireDefault(require("./clone/clone")); - -exports.clone = _clone.default; - -var _cloneDeep = _interopRequireDefault(require("./clone/cloneDeep")); - -exports.cloneDeep = _cloneDeep.default; - -var _cloneWithoutLoc = _interopRequireDefault(require("./clone/cloneWithoutLoc")); - -exports.cloneWithoutLoc = _cloneWithoutLoc.default; - -var _addComment = _interopRequireDefault(require("./comments/addComment")); - -exports.addComment = _addComment.default; - -var _addComments = _interopRequireDefault(require("./comments/addComments")); - -exports.addComments = _addComments.default; - -var _inheritInnerComments = _interopRequireDefault(require("./comments/inheritInnerComments")); - -exports.inheritInnerComments = _inheritInnerComments.default; - -var _inheritLeadingComments = _interopRequireDefault(require("./comments/inheritLeadingComments")); - -exports.inheritLeadingComments = _inheritLeadingComments.default; - -var _inheritsComments = _interopRequireDefault(require("./comments/inheritsComments")); - -exports.inheritsComments = _inheritsComments.default; - -var _inheritTrailingComments = _interopRequireDefault(require("./comments/inheritTrailingComments")); - -exports.inheritTrailingComments = _inheritTrailingComments.default; - -var _removeComments = _interopRequireDefault(require("./comments/removeComments")); - -exports.removeComments = _removeComments.default; - -var _generated3 = require("./constants/generated"); - -Object.keys(_generated3).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; - exports[key] = _generated3[key]; -}); - -var _constants = require("./constants"); - -Object.keys(_constants).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; - exports[key] = _constants[key]; -}); - -var _ensureBlock = _interopRequireDefault(require("./converters/ensureBlock")); - -exports.ensureBlock = _ensureBlock.default; - -var _toBindingIdentifierName = _interopRequireDefault(require("./converters/toBindingIdentifierName")); - -exports.toBindingIdentifierName = _toBindingIdentifierName.default; - -var _toBlock = _interopRequireDefault(require("./converters/toBlock")); - -exports.toBlock = _toBlock.default; - -var _toComputedKey = _interopRequireDefault(require("./converters/toComputedKey")); - -exports.toComputedKey = _toComputedKey.default; - -var _toExpression = _interopRequireDefault(require("./converters/toExpression")); - -exports.toExpression = _toExpression.default; - -var _toIdentifier = _interopRequireDefault(require("./converters/toIdentifier")); - -exports.toIdentifier = _toIdentifier.default; - -var _toKeyAlias = _interopRequireDefault(require("./converters/toKeyAlias")); - -exports.toKeyAlias = _toKeyAlias.default; - -var _toSequenceExpression = _interopRequireDefault(require("./converters/toSequenceExpression")); - -exports.toSequenceExpression = _toSequenceExpression.default; - -var _toStatement = _interopRequireDefault(require("./converters/toStatement")); - -exports.toStatement = _toStatement.default; - -var _valueToNode = _interopRequireDefault(require("./converters/valueToNode")); - -exports.valueToNode = _valueToNode.default; - -var _definitions = require("./definitions"); - -Object.keys(_definitions).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; - exports[key] = _definitions[key]; -}); - -var _appendToMemberExpression = _interopRequireDefault(require("./modifications/appendToMemberExpression")); - -exports.appendToMemberExpression = _appendToMemberExpression.default; - -var _inherits = _interopRequireDefault(require("./modifications/inherits")); - -exports.inherits = _inherits.default; - -var _prependToMemberExpression = _interopRequireDefault(require("./modifications/prependToMemberExpression")); - -exports.prependToMemberExpression = _prependToMemberExpression.default; - -var _removeProperties = _interopRequireDefault(require("./modifications/removeProperties")); - -exports.removeProperties = _removeProperties.default; - -var _removePropertiesDeep = _interopRequireDefault(require("./modifications/removePropertiesDeep")); - -exports.removePropertiesDeep = _removePropertiesDeep.default; - -var _removeTypeDuplicates = _interopRequireDefault(require("./modifications/flow/removeTypeDuplicates")); - -exports.removeTypeDuplicates = _removeTypeDuplicates.default; - -var _getBindingIdentifiers = _interopRequireDefault(require("./retrievers/getBindingIdentifiers")); - -exports.getBindingIdentifiers = _getBindingIdentifiers.default; - -var _getOuterBindingIdentifiers = _interopRequireDefault(require("./retrievers/getOuterBindingIdentifiers")); - -exports.getOuterBindingIdentifiers = _getOuterBindingIdentifiers.default; - -var _traverse = _interopRequireDefault(require("./traverse/traverse")); - -exports.traverse = _traverse.default; - -var _traverseFast = _interopRequireDefault(require("./traverse/traverseFast")); - -exports.traverseFast = _traverseFast.default; - -var _shallowEqual = _interopRequireDefault(require("./utils/shallowEqual")); - -exports.shallowEqual = _shallowEqual.default; - -var _is = _interopRequireDefault(require("./validators/is")); - -exports.is = _is.default; - -var _isBinding = _interopRequireDefault(require("./validators/isBinding")); - -exports.isBinding = _isBinding.default; - -var _isBlockScoped = _interopRequireDefault(require("./validators/isBlockScoped")); - -exports.isBlockScoped = _isBlockScoped.default; - -var _isImmutable = _interopRequireDefault(require("./validators/isImmutable")); - -exports.isImmutable = _isImmutable.default; - -var _isLet = _interopRequireDefault(require("./validators/isLet")); - -exports.isLet = _isLet.default; - -var _isNode = _interopRequireDefault(require("./validators/isNode")); - -exports.isNode = _isNode.default; - -var _isNodesEquivalent = _interopRequireDefault(require("./validators/isNodesEquivalent")); - -exports.isNodesEquivalent = _isNodesEquivalent.default; - -var _isReferenced = _interopRequireDefault(require("./validators/isReferenced")); - -exports.isReferenced = _isReferenced.default; - -var _isScope = _interopRequireDefault(require("./validators/isScope")); - -exports.isScope = _isScope.default; - -var _isSpecifierDefault = _interopRequireDefault(require("./validators/isSpecifierDefault")); - -exports.isSpecifierDefault = _isSpecifierDefault.default; - -var _isType = _interopRequireDefault(require("./validators/isType")); - -exports.isType = _isType.default; - -var _isValidES3Identifier = _interopRequireDefault(require("./validators/isValidES3Identifier")); - -exports.isValidES3Identifier = _isValidES3Identifier.default; - -var _isValidIdentifier = _interopRequireDefault(require("./validators/isValidIdentifier")); - -exports.isValidIdentifier = _isValidIdentifier.default; - -var _isVar = _interopRequireDefault(require("./validators/isVar")); - -exports.isVar = _isVar.default; - -var _matchesPattern = _interopRequireDefault(require("./validators/matchesPattern")); - -exports.matchesPattern = _matchesPattern.default; - -var _validate = _interopRequireDefault(require("./validators/validate")); - -exports.validate = _validate.default; - -var _buildMatchMemberExpression = _interopRequireDefault(require("./validators/buildMatchMemberExpression")); - -exports.buildMatchMemberExpression = _buildMatchMemberExpression.default; - -var _generated4 = require("./validators/generated"); - -Object.keys(_generated4).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; - exports[key] = _generated4[key]; -}); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var react = { - isReactComponent: _isReactComponent.default, - isCompatTag: _isCompatTag.default, - buildChildren: _buildChildren.default -}; -exports.react = react; \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/modifications/appendToMemberExpression.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/modifications/appendToMemberExpression.js deleted file mode 100644 index f9d971c6237d1c..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/modifications/appendToMemberExpression.js +++ /dev/null @@ -1,17 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = appendToMemberExpression; - -var _generated = require("../builders/generated"); - -function appendToMemberExpression(member, append, computed) { - if (computed === void 0) { - computed = false; - } - - member.object = (0, _generated.memberExpression)(member.object, member.property, member.computed); - member.property = append; - member.computed = !!computed; - return member; -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/modifications/flow/removeTypeDuplicates.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/modifications/flow/removeTypeDuplicates.js deleted file mode 100644 index c0f402088c52ce..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/modifications/flow/removeTypeDuplicates.js +++ /dev/null @@ -1,72 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = removeTypeDuplicates; - -var _generated = require("../../validators/generated"); - -function removeTypeDuplicates(nodes) { - var generics = {}; - var bases = {}; - var typeGroups = []; - var types = []; - - for (var i = 0; i < nodes.length; i++) { - var node = nodes[i]; - if (!node) continue; - - if (types.indexOf(node) >= 0) { - continue; - } - - if ((0, _generated.isAnyTypeAnnotation)(node)) { - return [node]; - } - - if ((0, _generated.isFlowBaseAnnotation)(node)) { - bases[node.type] = node; - continue; - } - - if ((0, _generated.isUnionTypeAnnotation)(node)) { - if (typeGroups.indexOf(node.types) < 0) { - nodes = nodes.concat(node.types); - typeGroups.push(node.types); - } - - continue; - } - - if ((0, _generated.isGenericTypeAnnotation)(node)) { - var name = node.id.name; - - if (generics[name]) { - var existing = generics[name]; - - if (existing.typeParameters) { - if (node.typeParameters) { - existing.typeParameters.params = removeTypeDuplicates(existing.typeParameters.params.concat(node.typeParameters.params)); - } - } else { - existing = node.typeParameters; - } - } else { - generics[name] = node; - } - - continue; - } - - types.push(node); - } - - for (var type in bases) { - types.push(bases[type]); - } - - for (var _name in generics) { - types.push(generics[_name]); - } - - return types; -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/modifications/inherits.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/modifications/inherits.js deleted file mode 100644 index 195f714cf3afd3..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/modifications/inherits.js +++ /dev/null @@ -1,37 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = inherits; - -var _constants = require("../constants"); - -var _inheritsComments = _interopRequireDefault(require("../comments/inheritsComments")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function inherits(child, parent) { - if (!child || !parent) return child; - var _arr = _constants.INHERIT_KEYS.optional; - - for (var _i = 0; _i < _arr.length; _i++) { - var key = _arr[_i]; - - if (child[key] == null) { - child[key] = parent[key]; - } - } - - for (var _key in parent) { - if (_key[0] === "_" && _key !== "__clone") child[_key] = parent[_key]; - } - - var _arr2 = _constants.INHERIT_KEYS.force; - - for (var _i2 = 0; _i2 < _arr2.length; _i2++) { - var _key2 = _arr2[_i2]; - child[_key2] = parent[_key2]; - } - - (0, _inheritsComments.default)(child, parent); - return child; -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/modifications/prependToMemberExpression.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/modifications/prependToMemberExpression.js deleted file mode 100644 index 9b0f8aef69a1c7..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/modifications/prependToMemberExpression.js +++ /dev/null @@ -1,11 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = prependToMemberExpression; - -var _generated = require("../builders/generated"); - -function prependToMemberExpression(member, prepend) { - member.object = (0, _generated.memberExpression)(prepend, member.object); - return member; -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/modifications/removeProperties.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/modifications/removeProperties.js deleted file mode 100644 index 0f3a5c31b8be4c..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/modifications/removeProperties.js +++ /dev/null @@ -1,56 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = removeProperties; - -var _constants = require("../constants"); - -var CLEAR_KEYS = ["tokens", "start", "end", "loc", "raw", "rawValue"]; - -var CLEAR_KEYS_PLUS_COMMENTS = _constants.COMMENT_KEYS.concat(["comments"]).concat(CLEAR_KEYS); - -function removeProperties(node, opts) { - if (opts === void 0) { - opts = {}; - } - - var map = opts.preserveComments ? CLEAR_KEYS : CLEAR_KEYS_PLUS_COMMENTS; - - for (var _iterator = map, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var _key2 = _ref; - if (node[_key2] != null) node[_key2] = undefined; - } - - for (var _key in node) { - if (_key[0] === "_" && node[_key] != null) node[_key] = undefined; - } - - var symbols = Object.getOwnPropertySymbols(node); - - for (var _iterator2 = symbols, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) { - var _ref2; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } - - var _sym = _ref2; - node[_sym] = null; - } -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/modifications/removePropertiesDeep.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/modifications/removePropertiesDeep.js deleted file mode 100644 index 78453469680298..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/modifications/removePropertiesDeep.js +++ /dev/null @@ -1,15 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = removePropertiesDeep; - -var _traverseFast = _interopRequireDefault(require("../traverse/traverseFast")); - -var _removeProperties = _interopRequireDefault(require("./removeProperties")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function removePropertiesDeep(tree, opts) { - (0, _traverseFast.default)(tree, _removeProperties.default, opts); - return tree; -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/retrievers/getBindingIdentifiers.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/retrievers/getBindingIdentifiers.js deleted file mode 100644 index 689b15e6a4cc38..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/retrievers/getBindingIdentifiers.js +++ /dev/null @@ -1,95 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = getBindingIdentifiers; - -var _generated = require("../validators/generated"); - -function getBindingIdentifiers(node, duplicates, outerOnly) { - var search = [].concat(node); - var ids = Object.create(null); - - while (search.length) { - var id = search.shift(); - if (!id) continue; - var keys = getBindingIdentifiers.keys[id.type]; - - if ((0, _generated.isIdentifier)(id)) { - if (duplicates) { - var _ids = ids[id.name] = ids[id.name] || []; - - _ids.push(id); - } else { - ids[id.name] = id; - } - - continue; - } - - if ((0, _generated.isExportDeclaration)(id)) { - if ((0, _generated.isDeclaration)(id.declaration)) { - search.push(id.declaration); - } - - continue; - } - - if (outerOnly) { - if ((0, _generated.isFunctionDeclaration)(id)) { - search.push(id.id); - continue; - } - - if ((0, _generated.isFunctionExpression)(id)) { - continue; - } - } - - if (keys) { - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - - if (id[key]) { - search = search.concat(id[key]); - } - } - } - } - - return ids; -} - -getBindingIdentifiers.keys = { - DeclareClass: ["id"], - DeclareFunction: ["id"], - DeclareModule: ["id"], - DeclareVariable: ["id"], - InterfaceDeclaration: ["id"], - TypeAlias: ["id"], - OpaqueType: ["id"], - CatchClause: ["param"], - LabeledStatement: ["label"], - UnaryExpression: ["argument"], - AssignmentExpression: ["left"], - ImportSpecifier: ["local"], - ImportNamespaceSpecifier: ["local"], - ImportDefaultSpecifier: ["local"], - ImportDeclaration: ["specifiers"], - ExportSpecifier: ["exported"], - ExportNamespaceSpecifier: ["exported"], - ExportDefaultSpecifier: ["exported"], - FunctionDeclaration: ["id", "params"], - FunctionExpression: ["id", "params"], - ForInStatement: ["left"], - ForOfStatement: ["left"], - ClassDeclaration: ["id"], - ClassExpression: ["id"], - RestElement: ["argument"], - UpdateExpression: ["argument"], - ObjectProperty: ["value"], - AssignmentPattern: ["left"], - ArrayPattern: ["elements"], - ObjectPattern: ["properties"], - VariableDeclaration: ["declarations"], - VariableDeclarator: ["id"] -}; \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/retrievers/getOuterBindingIdentifiers.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/retrievers/getOuterBindingIdentifiers.js deleted file mode 100644 index 367f2d87a523eb..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/retrievers/getOuterBindingIdentifiers.js +++ /dev/null @@ -1,12 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = getOuterBindingIdentifiers; - -var _getBindingIdentifiers = _interopRequireDefault(require("./getBindingIdentifiers")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function getOuterBindingIdentifiers(node, duplicates) { - return (0, _getBindingIdentifiers.default)(node, duplicates, true); -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/traverse/traverse.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/traverse/traverse.js deleted file mode 100644 index b51ed99de03a7e..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/traverse/traverse.js +++ /dev/null @@ -1,64 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = traverse; - -var _definitions = require("../definitions"); - -function traverse(node, handlers, state) { - if (typeof handlers === "function") { - handlers = { - enter: handlers - }; - } - - var _ref = handlers, - enter = _ref.enter, - exit = _ref.exit; - traverseSimpleImpl(node, enter, exit, state, []); -} - -function traverseSimpleImpl(node, enter, exit, state, ancestors) { - var keys = _definitions.VISITOR_KEYS[node.type]; - if (!keys) return; - if (enter) enter(node, ancestors, state); - - for (var _iterator = keys, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { - var _ref2; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref2 = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref2 = _i.value; - } - - var _key2 = _ref2; - var subNode = node[_key2]; - - if (Array.isArray(subNode)) { - for (var i = 0; i < subNode.length; i++) { - var child = subNode[i]; - if (!child) continue; - ancestors.push({ - node: node, - key: _key2, - index: i - }); - traverseSimpleImpl(child, enter, exit, state, ancestors); - ancestors.pop(); - } - } else if (subNode) { - ancestors.push({ - node: node, - key: _key2 - }); - traverseSimpleImpl(subNode, enter, exit, state, ancestors); - ancestors.pop(); - } - } - - if (exit) exit(node, ancestors, state); -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/traverse/traverseFast.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/traverse/traverseFast.js deleted file mode 100644 index 1ccd727f367aa7..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/traverse/traverseFast.js +++ /dev/null @@ -1,50 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = traverseFast; - -var _definitions = require("../definitions"); - -function traverseFast(node, enter, opts) { - if (!node) return; - var keys = _definitions.VISITOR_KEYS[node.type]; - if (!keys) return; - opts = opts || {}; - enter(node, opts); - - for (var _iterator = keys, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var _key = _ref; - var subNode = node[_key]; - - if (Array.isArray(subNode)) { - for (var _iterator2 = subNode, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) { - var _ref2; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } - - var _node2 = _ref2; - traverseFast(_node2, enter, opts); - } - } else { - traverseFast(subNode, enter, opts); - } - } -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/utils/inherit.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/utils/inherit.js deleted file mode 100644 index 6c57f50d239af4..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/utils/inherit.js +++ /dev/null @@ -1,14 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = inherit; - -var _uniq = _interopRequireDefault(require("lodash/uniq")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function inherit(key, child, parent) { - if (child && parent) { - child[key] = (0, _uniq.default)([].concat(child[key], parent[key]).filter(Boolean)); - } -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/utils/react/cleanJSXElementLiteralChild.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/utils/react/cleanJSXElementLiteralChild.js deleted file mode 100644 index 84de7435c9aa11..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/utils/react/cleanJSXElementLiteralChild.js +++ /dev/null @@ -1,45 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = cleanJSXElementLiteralChild; - -var _generated = require("../../builders/generated"); - -function cleanJSXElementLiteralChild(child, args) { - var lines = child.value.split(/\r\n|\n|\r/); - var lastNonEmptyLine = 0; - - for (var i = 0; i < lines.length; i++) { - if (lines[i].match(/[^ \t]/)) { - lastNonEmptyLine = i; - } - } - - var str = ""; - - for (var _i = 0; _i < lines.length; _i++) { - var line = lines[_i]; - var isFirstLine = _i === 0; - var isLastLine = _i === lines.length - 1; - var isLastNonEmptyLine = _i === lastNonEmptyLine; - var trimmedLine = line.replace(/\t/g, " "); - - if (!isFirstLine) { - trimmedLine = trimmedLine.replace(/^[ ]+/, ""); - } - - if (!isLastLine) { - trimmedLine = trimmedLine.replace(/[ ]+$/, ""); - } - - if (trimmedLine) { - if (!isLastNonEmptyLine) { - trimmedLine += " "; - } - - str += trimmedLine; - } - } - - if (str) args.push((0, _generated.stringLiteral)(str)); -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/utils/shallowEqual.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/utils/shallowEqual.js deleted file mode 100644 index 8969d543a854d7..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/utils/shallowEqual.js +++ /dev/null @@ -1,19 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = shallowEqual; - -function shallowEqual(actual, expected) { - var keys = Object.keys(expected); - var _arr = keys; - - for (var _i = 0; _i < _arr.length; _i++) { - var key = _arr[_i]; - - if (actual[key] !== expected[key]) { - return false; - } - } - - return true; -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/buildMatchMemberExpression.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/buildMatchMemberExpression.js deleted file mode 100644 index 5c5d242d196852..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/buildMatchMemberExpression.js +++ /dev/null @@ -1,15 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = buildMatchMemberExpression; - -var _matchesPattern = _interopRequireDefault(require("./matchesPattern")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function buildMatchMemberExpression(match, allowPartial) { - var parts = match.split("."); - return function (member) { - return (0, _matchesPattern.default)(member, parts, allowPartial); - }; -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/generated/index.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/generated/index.js deleted file mode 100644 index 684966d41dfe06..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/generated/index.js +++ /dev/null @@ -1,1241 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.isArrayExpression = isArrayExpression; -exports.isAssignmentExpression = isAssignmentExpression; -exports.isBinaryExpression = isBinaryExpression; -exports.isDirective = isDirective; -exports.isDirectiveLiteral = isDirectiveLiteral; -exports.isBlockStatement = isBlockStatement; -exports.isBreakStatement = isBreakStatement; -exports.isCallExpression = isCallExpression; -exports.isCatchClause = isCatchClause; -exports.isConditionalExpression = isConditionalExpression; -exports.isContinueStatement = isContinueStatement; -exports.isDebuggerStatement = isDebuggerStatement; -exports.isDoWhileStatement = isDoWhileStatement; -exports.isEmptyStatement = isEmptyStatement; -exports.isExpressionStatement = isExpressionStatement; -exports.isFile = isFile; -exports.isForInStatement = isForInStatement; -exports.isForStatement = isForStatement; -exports.isFunctionDeclaration = isFunctionDeclaration; -exports.isFunctionExpression = isFunctionExpression; -exports.isIdentifier = isIdentifier; -exports.isIfStatement = isIfStatement; -exports.isLabeledStatement = isLabeledStatement; -exports.isStringLiteral = isStringLiteral; -exports.isNumericLiteral = isNumericLiteral; -exports.isNullLiteral = isNullLiteral; -exports.isBooleanLiteral = isBooleanLiteral; -exports.isRegExpLiteral = isRegExpLiteral; -exports.isLogicalExpression = isLogicalExpression; -exports.isMemberExpression = isMemberExpression; -exports.isNewExpression = isNewExpression; -exports.isProgram = isProgram; -exports.isObjectExpression = isObjectExpression; -exports.isObjectMethod = isObjectMethod; -exports.isObjectProperty = isObjectProperty; -exports.isRestElement = isRestElement; -exports.isReturnStatement = isReturnStatement; -exports.isSequenceExpression = isSequenceExpression; -exports.isSwitchCase = isSwitchCase; -exports.isSwitchStatement = isSwitchStatement; -exports.isThisExpression = isThisExpression; -exports.isThrowStatement = isThrowStatement; -exports.isTryStatement = isTryStatement; -exports.isUnaryExpression = isUnaryExpression; -exports.isUpdateExpression = isUpdateExpression; -exports.isVariableDeclaration = isVariableDeclaration; -exports.isVariableDeclarator = isVariableDeclarator; -exports.isWhileStatement = isWhileStatement; -exports.isWithStatement = isWithStatement; -exports.isAssignmentPattern = isAssignmentPattern; -exports.isArrayPattern = isArrayPattern; -exports.isArrowFunctionExpression = isArrowFunctionExpression; -exports.isClassBody = isClassBody; -exports.isClassDeclaration = isClassDeclaration; -exports.isClassExpression = isClassExpression; -exports.isExportAllDeclaration = isExportAllDeclaration; -exports.isExportDefaultDeclaration = isExportDefaultDeclaration; -exports.isExportNamedDeclaration = isExportNamedDeclaration; -exports.isExportSpecifier = isExportSpecifier; -exports.isForOfStatement = isForOfStatement; -exports.isImportDeclaration = isImportDeclaration; -exports.isImportDefaultSpecifier = isImportDefaultSpecifier; -exports.isImportNamespaceSpecifier = isImportNamespaceSpecifier; -exports.isImportSpecifier = isImportSpecifier; -exports.isMetaProperty = isMetaProperty; -exports.isClassMethod = isClassMethod; -exports.isObjectPattern = isObjectPattern; -exports.isSpreadElement = isSpreadElement; -exports.isSuper = isSuper; -exports.isTaggedTemplateExpression = isTaggedTemplateExpression; -exports.isTemplateElement = isTemplateElement; -exports.isTemplateLiteral = isTemplateLiteral; -exports.isYieldExpression = isYieldExpression; -exports.isAnyTypeAnnotation = isAnyTypeAnnotation; -exports.isArrayTypeAnnotation = isArrayTypeAnnotation; -exports.isBooleanTypeAnnotation = isBooleanTypeAnnotation; -exports.isBooleanLiteralTypeAnnotation = isBooleanLiteralTypeAnnotation; -exports.isNullLiteralTypeAnnotation = isNullLiteralTypeAnnotation; -exports.isClassImplements = isClassImplements; -exports.isDeclareClass = isDeclareClass; -exports.isDeclareFunction = isDeclareFunction; -exports.isDeclareInterface = isDeclareInterface; -exports.isDeclareModule = isDeclareModule; -exports.isDeclareModuleExports = isDeclareModuleExports; -exports.isDeclareTypeAlias = isDeclareTypeAlias; -exports.isDeclareOpaqueType = isDeclareOpaqueType; -exports.isDeclareVariable = isDeclareVariable; -exports.isDeclareExportDeclaration = isDeclareExportDeclaration; -exports.isDeclareExportAllDeclaration = isDeclareExportAllDeclaration; -exports.isDeclaredPredicate = isDeclaredPredicate; -exports.isExistsTypeAnnotation = isExistsTypeAnnotation; -exports.isFunctionTypeAnnotation = isFunctionTypeAnnotation; -exports.isFunctionTypeParam = isFunctionTypeParam; -exports.isGenericTypeAnnotation = isGenericTypeAnnotation; -exports.isInferredPredicate = isInferredPredicate; -exports.isInterfaceExtends = isInterfaceExtends; -exports.isInterfaceDeclaration = isInterfaceDeclaration; -exports.isIntersectionTypeAnnotation = isIntersectionTypeAnnotation; -exports.isMixedTypeAnnotation = isMixedTypeAnnotation; -exports.isEmptyTypeAnnotation = isEmptyTypeAnnotation; -exports.isNullableTypeAnnotation = isNullableTypeAnnotation; -exports.isNumberLiteralTypeAnnotation = isNumberLiteralTypeAnnotation; -exports.isNumberTypeAnnotation = isNumberTypeAnnotation; -exports.isObjectTypeAnnotation = isObjectTypeAnnotation; -exports.isObjectTypeCallProperty = isObjectTypeCallProperty; -exports.isObjectTypeIndexer = isObjectTypeIndexer; -exports.isObjectTypeProperty = isObjectTypeProperty; -exports.isObjectTypeSpreadProperty = isObjectTypeSpreadProperty; -exports.isOpaqueType = isOpaqueType; -exports.isQualifiedTypeIdentifier = isQualifiedTypeIdentifier; -exports.isStringLiteralTypeAnnotation = isStringLiteralTypeAnnotation; -exports.isStringTypeAnnotation = isStringTypeAnnotation; -exports.isThisTypeAnnotation = isThisTypeAnnotation; -exports.isTupleTypeAnnotation = isTupleTypeAnnotation; -exports.isTypeofTypeAnnotation = isTypeofTypeAnnotation; -exports.isTypeAlias = isTypeAlias; -exports.isTypeAnnotation = isTypeAnnotation; -exports.isTypeCastExpression = isTypeCastExpression; -exports.isTypeParameter = isTypeParameter; -exports.isTypeParameterDeclaration = isTypeParameterDeclaration; -exports.isTypeParameterInstantiation = isTypeParameterInstantiation; -exports.isUnionTypeAnnotation = isUnionTypeAnnotation; -exports.isVoidTypeAnnotation = isVoidTypeAnnotation; -exports.isJSXAttribute = isJSXAttribute; -exports.isJSXClosingElement = isJSXClosingElement; -exports.isJSXElement = isJSXElement; -exports.isJSXEmptyExpression = isJSXEmptyExpression; -exports.isJSXExpressionContainer = isJSXExpressionContainer; -exports.isJSXSpreadChild = isJSXSpreadChild; -exports.isJSXIdentifier = isJSXIdentifier; -exports.isJSXMemberExpression = isJSXMemberExpression; -exports.isJSXNamespacedName = isJSXNamespacedName; -exports.isJSXOpeningElement = isJSXOpeningElement; -exports.isJSXSpreadAttribute = isJSXSpreadAttribute; -exports.isJSXText = isJSXText; -exports.isJSXFragment = isJSXFragment; -exports.isJSXOpeningFragment = isJSXOpeningFragment; -exports.isJSXClosingFragment = isJSXClosingFragment; -exports.isNoop = isNoop; -exports.isParenthesizedExpression = isParenthesizedExpression; -exports.isAwaitExpression = isAwaitExpression; -exports.isBindExpression = isBindExpression; -exports.isClassProperty = isClassProperty; -exports.isImport = isImport; -exports.isDecorator = isDecorator; -exports.isDoExpression = isDoExpression; -exports.isExportDefaultSpecifier = isExportDefaultSpecifier; -exports.isExportNamespaceSpecifier = isExportNamespaceSpecifier; -exports.isTSParameterProperty = isTSParameterProperty; -exports.isTSDeclareFunction = isTSDeclareFunction; -exports.isTSDeclareMethod = isTSDeclareMethod; -exports.isTSQualifiedName = isTSQualifiedName; -exports.isTSCallSignatureDeclaration = isTSCallSignatureDeclaration; -exports.isTSConstructSignatureDeclaration = isTSConstructSignatureDeclaration; -exports.isTSPropertySignature = isTSPropertySignature; -exports.isTSMethodSignature = isTSMethodSignature; -exports.isTSIndexSignature = isTSIndexSignature; -exports.isTSAnyKeyword = isTSAnyKeyword; -exports.isTSNumberKeyword = isTSNumberKeyword; -exports.isTSObjectKeyword = isTSObjectKeyword; -exports.isTSBooleanKeyword = isTSBooleanKeyword; -exports.isTSStringKeyword = isTSStringKeyword; -exports.isTSSymbolKeyword = isTSSymbolKeyword; -exports.isTSVoidKeyword = isTSVoidKeyword; -exports.isTSUndefinedKeyword = isTSUndefinedKeyword; -exports.isTSNullKeyword = isTSNullKeyword; -exports.isTSNeverKeyword = isTSNeverKeyword; -exports.isTSThisType = isTSThisType; -exports.isTSFunctionType = isTSFunctionType; -exports.isTSConstructorType = isTSConstructorType; -exports.isTSTypeReference = isTSTypeReference; -exports.isTSTypePredicate = isTSTypePredicate; -exports.isTSTypeQuery = isTSTypeQuery; -exports.isTSTypeLiteral = isTSTypeLiteral; -exports.isTSArrayType = isTSArrayType; -exports.isTSTupleType = isTSTupleType; -exports.isTSUnionType = isTSUnionType; -exports.isTSIntersectionType = isTSIntersectionType; -exports.isTSParenthesizedType = isTSParenthesizedType; -exports.isTSTypeOperator = isTSTypeOperator; -exports.isTSIndexedAccessType = isTSIndexedAccessType; -exports.isTSMappedType = isTSMappedType; -exports.isTSLiteralType = isTSLiteralType; -exports.isTSExpressionWithTypeArguments = isTSExpressionWithTypeArguments; -exports.isTSInterfaceDeclaration = isTSInterfaceDeclaration; -exports.isTSInterfaceBody = isTSInterfaceBody; -exports.isTSTypeAliasDeclaration = isTSTypeAliasDeclaration; -exports.isTSAsExpression = isTSAsExpression; -exports.isTSTypeAssertion = isTSTypeAssertion; -exports.isTSEnumDeclaration = isTSEnumDeclaration; -exports.isTSEnumMember = isTSEnumMember; -exports.isTSModuleDeclaration = isTSModuleDeclaration; -exports.isTSModuleBlock = isTSModuleBlock; -exports.isTSImportEqualsDeclaration = isTSImportEqualsDeclaration; -exports.isTSExternalModuleReference = isTSExternalModuleReference; -exports.isTSNonNullExpression = isTSNonNullExpression; -exports.isTSExportAssignment = isTSExportAssignment; -exports.isTSNamespaceExportDeclaration = isTSNamespaceExportDeclaration; -exports.isTSTypeAnnotation = isTSTypeAnnotation; -exports.isTSTypeParameterInstantiation = isTSTypeParameterInstantiation; -exports.isTSTypeParameterDeclaration = isTSTypeParameterDeclaration; -exports.isTSTypeParameter = isTSTypeParameter; -exports.isExpression = isExpression; -exports.isBinary = isBinary; -exports.isScopable = isScopable; -exports.isBlockParent = isBlockParent; -exports.isBlock = isBlock; -exports.isStatement = isStatement; -exports.isTerminatorless = isTerminatorless; -exports.isCompletionStatement = isCompletionStatement; -exports.isConditional = isConditional; -exports.isLoop = isLoop; -exports.isWhile = isWhile; -exports.isExpressionWrapper = isExpressionWrapper; -exports.isFor = isFor; -exports.isForXStatement = isForXStatement; -exports.isFunction = isFunction; -exports.isFunctionParent = isFunctionParent; -exports.isPureish = isPureish; -exports.isDeclaration = isDeclaration; -exports.isPatternLike = isPatternLike; -exports.isLVal = isLVal; -exports.isTSEntityName = isTSEntityName; -exports.isLiteral = isLiteral; -exports.isImmutable = isImmutable; -exports.isUserWhitespacable = isUserWhitespacable; -exports.isMethod = isMethod; -exports.isObjectMember = isObjectMember; -exports.isProperty = isProperty; -exports.isUnaryLike = isUnaryLike; -exports.isPattern = isPattern; -exports.isClass = isClass; -exports.isModuleDeclaration = isModuleDeclaration; -exports.isExportDeclaration = isExportDeclaration; -exports.isModuleSpecifier = isModuleSpecifier; -exports.isFlow = isFlow; -exports.isFlowBaseAnnotation = isFlowBaseAnnotation; -exports.isFlowDeclaration = isFlowDeclaration; -exports.isFlowPredicate = isFlowPredicate; -exports.isJSX = isJSX; -exports.isTSTypeElement = isTSTypeElement; -exports.isTSType = isTSType; -exports.isNumberLiteral = isNumberLiteral; -exports.isRegexLiteral = isRegexLiteral; -exports.isRestProperty = isRestProperty; -exports.isSpreadProperty = isSpreadProperty; - -var _is = _interopRequireDefault(require("../is")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function isArrayExpression(node, opts) { - return (0, _is.default)("ArrayExpression", node, opts); -} - -function isAssignmentExpression(node, opts) { - return (0, _is.default)("AssignmentExpression", node, opts); -} - -function isBinaryExpression(node, opts) { - return (0, _is.default)("BinaryExpression", node, opts); -} - -function isDirective(node, opts) { - return (0, _is.default)("Directive", node, opts); -} - -function isDirectiveLiteral(node, opts) { - return (0, _is.default)("DirectiveLiteral", node, opts); -} - -function isBlockStatement(node, opts) { - return (0, _is.default)("BlockStatement", node, opts); -} - -function isBreakStatement(node, opts) { - return (0, _is.default)("BreakStatement", node, opts); -} - -function isCallExpression(node, opts) { - return (0, _is.default)("CallExpression", node, opts); -} - -function isCatchClause(node, opts) { - return (0, _is.default)("CatchClause", node, opts); -} - -function isConditionalExpression(node, opts) { - return (0, _is.default)("ConditionalExpression", node, opts); -} - -function isContinueStatement(node, opts) { - return (0, _is.default)("ContinueStatement", node, opts); -} - -function isDebuggerStatement(node, opts) { - return (0, _is.default)("DebuggerStatement", node, opts); -} - -function isDoWhileStatement(node, opts) { - return (0, _is.default)("DoWhileStatement", node, opts); -} - -function isEmptyStatement(node, opts) { - return (0, _is.default)("EmptyStatement", node, opts); -} - -function isExpressionStatement(node, opts) { - return (0, _is.default)("ExpressionStatement", node, opts); -} - -function isFile(node, opts) { - return (0, _is.default)("File", node, opts); -} - -function isForInStatement(node, opts) { - return (0, _is.default)("ForInStatement", node, opts); -} - -function isForStatement(node, opts) { - return (0, _is.default)("ForStatement", node, opts); -} - -function isFunctionDeclaration(node, opts) { - return (0, _is.default)("FunctionDeclaration", node, opts); -} - -function isFunctionExpression(node, opts) { - return (0, _is.default)("FunctionExpression", node, opts); -} - -function isIdentifier(node, opts) { - return (0, _is.default)("Identifier", node, opts); -} - -function isIfStatement(node, opts) { - return (0, _is.default)("IfStatement", node, opts); -} - -function isLabeledStatement(node, opts) { - return (0, _is.default)("LabeledStatement", node, opts); -} - -function isStringLiteral(node, opts) { - return (0, _is.default)("StringLiteral", node, opts); -} - -function isNumericLiteral(node, opts) { - return (0, _is.default)("NumericLiteral", node, opts); -} - -function isNullLiteral(node, opts) { - return (0, _is.default)("NullLiteral", node, opts); -} - -function isBooleanLiteral(node, opts) { - return (0, _is.default)("BooleanLiteral", node, opts); -} - -function isRegExpLiteral(node, opts) { - return (0, _is.default)("RegExpLiteral", node, opts); -} - -function isLogicalExpression(node, opts) { - return (0, _is.default)("LogicalExpression", node, opts); -} - -function isMemberExpression(node, opts) { - return (0, _is.default)("MemberExpression", node, opts); -} - -function isNewExpression(node, opts) { - return (0, _is.default)("NewExpression", node, opts); -} - -function isProgram(node, opts) { - return (0, _is.default)("Program", node, opts); -} - -function isObjectExpression(node, opts) { - return (0, _is.default)("ObjectExpression", node, opts); -} - -function isObjectMethod(node, opts) { - return (0, _is.default)("ObjectMethod", node, opts); -} - -function isObjectProperty(node, opts) { - return (0, _is.default)("ObjectProperty", node, opts); -} - -function isRestElement(node, opts) { - return (0, _is.default)("RestElement", node, opts); -} - -function isReturnStatement(node, opts) { - return (0, _is.default)("ReturnStatement", node, opts); -} - -function isSequenceExpression(node, opts) { - return (0, _is.default)("SequenceExpression", node, opts); -} - -function isSwitchCase(node, opts) { - return (0, _is.default)("SwitchCase", node, opts); -} - -function isSwitchStatement(node, opts) { - return (0, _is.default)("SwitchStatement", node, opts); -} - -function isThisExpression(node, opts) { - return (0, _is.default)("ThisExpression", node, opts); -} - -function isThrowStatement(node, opts) { - return (0, _is.default)("ThrowStatement", node, opts); -} - -function isTryStatement(node, opts) { - return (0, _is.default)("TryStatement", node, opts); -} - -function isUnaryExpression(node, opts) { - return (0, _is.default)("UnaryExpression", node, opts); -} - -function isUpdateExpression(node, opts) { - return (0, _is.default)("UpdateExpression", node, opts); -} - -function isVariableDeclaration(node, opts) { - return (0, _is.default)("VariableDeclaration", node, opts); -} - -function isVariableDeclarator(node, opts) { - return (0, _is.default)("VariableDeclarator", node, opts); -} - -function isWhileStatement(node, opts) { - return (0, _is.default)("WhileStatement", node, opts); -} - -function isWithStatement(node, opts) { - return (0, _is.default)("WithStatement", node, opts); -} - -function isAssignmentPattern(node, opts) { - return (0, _is.default)("AssignmentPattern", node, opts); -} - -function isArrayPattern(node, opts) { - return (0, _is.default)("ArrayPattern", node, opts); -} - -function isArrowFunctionExpression(node, opts) { - return (0, _is.default)("ArrowFunctionExpression", node, opts); -} - -function isClassBody(node, opts) { - return (0, _is.default)("ClassBody", node, opts); -} - -function isClassDeclaration(node, opts) { - return (0, _is.default)("ClassDeclaration", node, opts); -} - -function isClassExpression(node, opts) { - return (0, _is.default)("ClassExpression", node, opts); -} - -function isExportAllDeclaration(node, opts) { - return (0, _is.default)("ExportAllDeclaration", node, opts); -} - -function isExportDefaultDeclaration(node, opts) { - return (0, _is.default)("ExportDefaultDeclaration", node, opts); -} - -function isExportNamedDeclaration(node, opts) { - return (0, _is.default)("ExportNamedDeclaration", node, opts); -} - -function isExportSpecifier(node, opts) { - return (0, _is.default)("ExportSpecifier", node, opts); -} - -function isForOfStatement(node, opts) { - return (0, _is.default)("ForOfStatement", node, opts); -} - -function isImportDeclaration(node, opts) { - return (0, _is.default)("ImportDeclaration", node, opts); -} - -function isImportDefaultSpecifier(node, opts) { - return (0, _is.default)("ImportDefaultSpecifier", node, opts); -} - -function isImportNamespaceSpecifier(node, opts) { - return (0, _is.default)("ImportNamespaceSpecifier", node, opts); -} - -function isImportSpecifier(node, opts) { - return (0, _is.default)("ImportSpecifier", node, opts); -} - -function isMetaProperty(node, opts) { - return (0, _is.default)("MetaProperty", node, opts); -} - -function isClassMethod(node, opts) { - return (0, _is.default)("ClassMethod", node, opts); -} - -function isObjectPattern(node, opts) { - return (0, _is.default)("ObjectPattern", node, opts); -} - -function isSpreadElement(node, opts) { - return (0, _is.default)("SpreadElement", node, opts); -} - -function isSuper(node, opts) { - return (0, _is.default)("Super", node, opts); -} - -function isTaggedTemplateExpression(node, opts) { - return (0, _is.default)("TaggedTemplateExpression", node, opts); -} - -function isTemplateElement(node, opts) { - return (0, _is.default)("TemplateElement", node, opts); -} - -function isTemplateLiteral(node, opts) { - return (0, _is.default)("TemplateLiteral", node, opts); -} - -function isYieldExpression(node, opts) { - return (0, _is.default)("YieldExpression", node, opts); -} - -function isAnyTypeAnnotation(node, opts) { - return (0, _is.default)("AnyTypeAnnotation", node, opts); -} - -function isArrayTypeAnnotation(node, opts) { - return (0, _is.default)("ArrayTypeAnnotation", node, opts); -} - -function isBooleanTypeAnnotation(node, opts) { - return (0, _is.default)("BooleanTypeAnnotation", node, opts); -} - -function isBooleanLiteralTypeAnnotation(node, opts) { - return (0, _is.default)("BooleanLiteralTypeAnnotation", node, opts); -} - -function isNullLiteralTypeAnnotation(node, opts) { - return (0, _is.default)("NullLiteralTypeAnnotation", node, opts); -} - -function isClassImplements(node, opts) { - return (0, _is.default)("ClassImplements", node, opts); -} - -function isDeclareClass(node, opts) { - return (0, _is.default)("DeclareClass", node, opts); -} - -function isDeclareFunction(node, opts) { - return (0, _is.default)("DeclareFunction", node, opts); -} - -function isDeclareInterface(node, opts) { - return (0, _is.default)("DeclareInterface", node, opts); -} - -function isDeclareModule(node, opts) { - return (0, _is.default)("DeclareModule", node, opts); -} - -function isDeclareModuleExports(node, opts) { - return (0, _is.default)("DeclareModuleExports", node, opts); -} - -function isDeclareTypeAlias(node, opts) { - return (0, _is.default)("DeclareTypeAlias", node, opts); -} - -function isDeclareOpaqueType(node, opts) { - return (0, _is.default)("DeclareOpaqueType", node, opts); -} - -function isDeclareVariable(node, opts) { - return (0, _is.default)("DeclareVariable", node, opts); -} - -function isDeclareExportDeclaration(node, opts) { - return (0, _is.default)("DeclareExportDeclaration", node, opts); -} - -function isDeclareExportAllDeclaration(node, opts) { - return (0, _is.default)("DeclareExportAllDeclaration", node, opts); -} - -function isDeclaredPredicate(node, opts) { - return (0, _is.default)("DeclaredPredicate", node, opts); -} - -function isExistsTypeAnnotation(node, opts) { - return (0, _is.default)("ExistsTypeAnnotation", node, opts); -} - -function isFunctionTypeAnnotation(node, opts) { - return (0, _is.default)("FunctionTypeAnnotation", node, opts); -} - -function isFunctionTypeParam(node, opts) { - return (0, _is.default)("FunctionTypeParam", node, opts); -} - -function isGenericTypeAnnotation(node, opts) { - return (0, _is.default)("GenericTypeAnnotation", node, opts); -} - -function isInferredPredicate(node, opts) { - return (0, _is.default)("InferredPredicate", node, opts); -} - -function isInterfaceExtends(node, opts) { - return (0, _is.default)("InterfaceExtends", node, opts); -} - -function isInterfaceDeclaration(node, opts) { - return (0, _is.default)("InterfaceDeclaration", node, opts); -} - -function isIntersectionTypeAnnotation(node, opts) { - return (0, _is.default)("IntersectionTypeAnnotation", node, opts); -} - -function isMixedTypeAnnotation(node, opts) { - return (0, _is.default)("MixedTypeAnnotation", node, opts); -} - -function isEmptyTypeAnnotation(node, opts) { - return (0, _is.default)("EmptyTypeAnnotation", node, opts); -} - -function isNullableTypeAnnotation(node, opts) { - return (0, _is.default)("NullableTypeAnnotation", node, opts); -} - -function isNumberLiteralTypeAnnotation(node, opts) { - return (0, _is.default)("NumberLiteralTypeAnnotation", node, opts); -} - -function isNumberTypeAnnotation(node, opts) { - return (0, _is.default)("NumberTypeAnnotation", node, opts); -} - -function isObjectTypeAnnotation(node, opts) { - return (0, _is.default)("ObjectTypeAnnotation", node, opts); -} - -function isObjectTypeCallProperty(node, opts) { - return (0, _is.default)("ObjectTypeCallProperty", node, opts); -} - -function isObjectTypeIndexer(node, opts) { - return (0, _is.default)("ObjectTypeIndexer", node, opts); -} - -function isObjectTypeProperty(node, opts) { - return (0, _is.default)("ObjectTypeProperty", node, opts); -} - -function isObjectTypeSpreadProperty(node, opts) { - return (0, _is.default)("ObjectTypeSpreadProperty", node, opts); -} - -function isOpaqueType(node, opts) { - return (0, _is.default)("OpaqueType", node, opts); -} - -function isQualifiedTypeIdentifier(node, opts) { - return (0, _is.default)("QualifiedTypeIdentifier", node, opts); -} - -function isStringLiteralTypeAnnotation(node, opts) { - return (0, _is.default)("StringLiteralTypeAnnotation", node, opts); -} - -function isStringTypeAnnotation(node, opts) { - return (0, _is.default)("StringTypeAnnotation", node, opts); -} - -function isThisTypeAnnotation(node, opts) { - return (0, _is.default)("ThisTypeAnnotation", node, opts); -} - -function isTupleTypeAnnotation(node, opts) { - return (0, _is.default)("TupleTypeAnnotation", node, opts); -} - -function isTypeofTypeAnnotation(node, opts) { - return (0, _is.default)("TypeofTypeAnnotation", node, opts); -} - -function isTypeAlias(node, opts) { - return (0, _is.default)("TypeAlias", node, opts); -} - -function isTypeAnnotation(node, opts) { - return (0, _is.default)("TypeAnnotation", node, opts); -} - -function isTypeCastExpression(node, opts) { - return (0, _is.default)("TypeCastExpression", node, opts); -} - -function isTypeParameter(node, opts) { - return (0, _is.default)("TypeParameter", node, opts); -} - -function isTypeParameterDeclaration(node, opts) { - return (0, _is.default)("TypeParameterDeclaration", node, opts); -} - -function isTypeParameterInstantiation(node, opts) { - return (0, _is.default)("TypeParameterInstantiation", node, opts); -} - -function isUnionTypeAnnotation(node, opts) { - return (0, _is.default)("UnionTypeAnnotation", node, opts); -} - -function isVoidTypeAnnotation(node, opts) { - return (0, _is.default)("VoidTypeAnnotation", node, opts); -} - -function isJSXAttribute(node, opts) { - return (0, _is.default)("JSXAttribute", node, opts); -} - -function isJSXClosingElement(node, opts) { - return (0, _is.default)("JSXClosingElement", node, opts); -} - -function isJSXElement(node, opts) { - return (0, _is.default)("JSXElement", node, opts); -} - -function isJSXEmptyExpression(node, opts) { - return (0, _is.default)("JSXEmptyExpression", node, opts); -} - -function isJSXExpressionContainer(node, opts) { - return (0, _is.default)("JSXExpressionContainer", node, opts); -} - -function isJSXSpreadChild(node, opts) { - return (0, _is.default)("JSXSpreadChild", node, opts); -} - -function isJSXIdentifier(node, opts) { - return (0, _is.default)("JSXIdentifier", node, opts); -} - -function isJSXMemberExpression(node, opts) { - return (0, _is.default)("JSXMemberExpression", node, opts); -} - -function isJSXNamespacedName(node, opts) { - return (0, _is.default)("JSXNamespacedName", node, opts); -} - -function isJSXOpeningElement(node, opts) { - return (0, _is.default)("JSXOpeningElement", node, opts); -} - -function isJSXSpreadAttribute(node, opts) { - return (0, _is.default)("JSXSpreadAttribute", node, opts); -} - -function isJSXText(node, opts) { - return (0, _is.default)("JSXText", node, opts); -} - -function isJSXFragment(node, opts) { - return (0, _is.default)("JSXFragment", node, opts); -} - -function isJSXOpeningFragment(node, opts) { - return (0, _is.default)("JSXOpeningFragment", node, opts); -} - -function isJSXClosingFragment(node, opts) { - return (0, _is.default)("JSXClosingFragment", node, opts); -} - -function isNoop(node, opts) { - return (0, _is.default)("Noop", node, opts); -} - -function isParenthesizedExpression(node, opts) { - return (0, _is.default)("ParenthesizedExpression", node, opts); -} - -function isAwaitExpression(node, opts) { - return (0, _is.default)("AwaitExpression", node, opts); -} - -function isBindExpression(node, opts) { - return (0, _is.default)("BindExpression", node, opts); -} - -function isClassProperty(node, opts) { - return (0, _is.default)("ClassProperty", node, opts); -} - -function isImport(node, opts) { - return (0, _is.default)("Import", node, opts); -} - -function isDecorator(node, opts) { - return (0, _is.default)("Decorator", node, opts); -} - -function isDoExpression(node, opts) { - return (0, _is.default)("DoExpression", node, opts); -} - -function isExportDefaultSpecifier(node, opts) { - return (0, _is.default)("ExportDefaultSpecifier", node, opts); -} - -function isExportNamespaceSpecifier(node, opts) { - return (0, _is.default)("ExportNamespaceSpecifier", node, opts); -} - -function isTSParameterProperty(node, opts) { - return (0, _is.default)("TSParameterProperty", node, opts); -} - -function isTSDeclareFunction(node, opts) { - return (0, _is.default)("TSDeclareFunction", node, opts); -} - -function isTSDeclareMethod(node, opts) { - return (0, _is.default)("TSDeclareMethod", node, opts); -} - -function isTSQualifiedName(node, opts) { - return (0, _is.default)("TSQualifiedName", node, opts); -} - -function isTSCallSignatureDeclaration(node, opts) { - return (0, _is.default)("TSCallSignatureDeclaration", node, opts); -} - -function isTSConstructSignatureDeclaration(node, opts) { - return (0, _is.default)("TSConstructSignatureDeclaration", node, opts); -} - -function isTSPropertySignature(node, opts) { - return (0, _is.default)("TSPropertySignature", node, opts); -} - -function isTSMethodSignature(node, opts) { - return (0, _is.default)("TSMethodSignature", node, opts); -} - -function isTSIndexSignature(node, opts) { - return (0, _is.default)("TSIndexSignature", node, opts); -} - -function isTSAnyKeyword(node, opts) { - return (0, _is.default)("TSAnyKeyword", node, opts); -} - -function isTSNumberKeyword(node, opts) { - return (0, _is.default)("TSNumberKeyword", node, opts); -} - -function isTSObjectKeyword(node, opts) { - return (0, _is.default)("TSObjectKeyword", node, opts); -} - -function isTSBooleanKeyword(node, opts) { - return (0, _is.default)("TSBooleanKeyword", node, opts); -} - -function isTSStringKeyword(node, opts) { - return (0, _is.default)("TSStringKeyword", node, opts); -} - -function isTSSymbolKeyword(node, opts) { - return (0, _is.default)("TSSymbolKeyword", node, opts); -} - -function isTSVoidKeyword(node, opts) { - return (0, _is.default)("TSVoidKeyword", node, opts); -} - -function isTSUndefinedKeyword(node, opts) { - return (0, _is.default)("TSUndefinedKeyword", node, opts); -} - -function isTSNullKeyword(node, opts) { - return (0, _is.default)("TSNullKeyword", node, opts); -} - -function isTSNeverKeyword(node, opts) { - return (0, _is.default)("TSNeverKeyword", node, opts); -} - -function isTSThisType(node, opts) { - return (0, _is.default)("TSThisType", node, opts); -} - -function isTSFunctionType(node, opts) { - return (0, _is.default)("TSFunctionType", node, opts); -} - -function isTSConstructorType(node, opts) { - return (0, _is.default)("TSConstructorType", node, opts); -} - -function isTSTypeReference(node, opts) { - return (0, _is.default)("TSTypeReference", node, opts); -} - -function isTSTypePredicate(node, opts) { - return (0, _is.default)("TSTypePredicate", node, opts); -} - -function isTSTypeQuery(node, opts) { - return (0, _is.default)("TSTypeQuery", node, opts); -} - -function isTSTypeLiteral(node, opts) { - return (0, _is.default)("TSTypeLiteral", node, opts); -} - -function isTSArrayType(node, opts) { - return (0, _is.default)("TSArrayType", node, opts); -} - -function isTSTupleType(node, opts) { - return (0, _is.default)("TSTupleType", node, opts); -} - -function isTSUnionType(node, opts) { - return (0, _is.default)("TSUnionType", node, opts); -} - -function isTSIntersectionType(node, opts) { - return (0, _is.default)("TSIntersectionType", node, opts); -} - -function isTSParenthesizedType(node, opts) { - return (0, _is.default)("TSParenthesizedType", node, opts); -} - -function isTSTypeOperator(node, opts) { - return (0, _is.default)("TSTypeOperator", node, opts); -} - -function isTSIndexedAccessType(node, opts) { - return (0, _is.default)("TSIndexedAccessType", node, opts); -} - -function isTSMappedType(node, opts) { - return (0, _is.default)("TSMappedType", node, opts); -} - -function isTSLiteralType(node, opts) { - return (0, _is.default)("TSLiteralType", node, opts); -} - -function isTSExpressionWithTypeArguments(node, opts) { - return (0, _is.default)("TSExpressionWithTypeArguments", node, opts); -} - -function isTSInterfaceDeclaration(node, opts) { - return (0, _is.default)("TSInterfaceDeclaration", node, opts); -} - -function isTSInterfaceBody(node, opts) { - return (0, _is.default)("TSInterfaceBody", node, opts); -} - -function isTSTypeAliasDeclaration(node, opts) { - return (0, _is.default)("TSTypeAliasDeclaration", node, opts); -} - -function isTSAsExpression(node, opts) { - return (0, _is.default)("TSAsExpression", node, opts); -} - -function isTSTypeAssertion(node, opts) { - return (0, _is.default)("TSTypeAssertion", node, opts); -} - -function isTSEnumDeclaration(node, opts) { - return (0, _is.default)("TSEnumDeclaration", node, opts); -} - -function isTSEnumMember(node, opts) { - return (0, _is.default)("TSEnumMember", node, opts); -} - -function isTSModuleDeclaration(node, opts) { - return (0, _is.default)("TSModuleDeclaration", node, opts); -} - -function isTSModuleBlock(node, opts) { - return (0, _is.default)("TSModuleBlock", node, opts); -} - -function isTSImportEqualsDeclaration(node, opts) { - return (0, _is.default)("TSImportEqualsDeclaration", node, opts); -} - -function isTSExternalModuleReference(node, opts) { - return (0, _is.default)("TSExternalModuleReference", node, opts); -} - -function isTSNonNullExpression(node, opts) { - return (0, _is.default)("TSNonNullExpression", node, opts); -} - -function isTSExportAssignment(node, opts) { - return (0, _is.default)("TSExportAssignment", node, opts); -} - -function isTSNamespaceExportDeclaration(node, opts) { - return (0, _is.default)("TSNamespaceExportDeclaration", node, opts); -} - -function isTSTypeAnnotation(node, opts) { - return (0, _is.default)("TSTypeAnnotation", node, opts); -} - -function isTSTypeParameterInstantiation(node, opts) { - return (0, _is.default)("TSTypeParameterInstantiation", node, opts); -} - -function isTSTypeParameterDeclaration(node, opts) { - return (0, _is.default)("TSTypeParameterDeclaration", node, opts); -} - -function isTSTypeParameter(node, opts) { - return (0, _is.default)("TSTypeParameter", node, opts); -} - -function isExpression(node, opts) { - return (0, _is.default)("Expression", node, opts); -} - -function isBinary(node, opts) { - return (0, _is.default)("Binary", node, opts); -} - -function isScopable(node, opts) { - return (0, _is.default)("Scopable", node, opts); -} - -function isBlockParent(node, opts) { - return (0, _is.default)("BlockParent", node, opts); -} - -function isBlock(node, opts) { - return (0, _is.default)("Block", node, opts); -} - -function isStatement(node, opts) { - return (0, _is.default)("Statement", node, opts); -} - -function isTerminatorless(node, opts) { - return (0, _is.default)("Terminatorless", node, opts); -} - -function isCompletionStatement(node, opts) { - return (0, _is.default)("CompletionStatement", node, opts); -} - -function isConditional(node, opts) { - return (0, _is.default)("Conditional", node, opts); -} - -function isLoop(node, opts) { - return (0, _is.default)("Loop", node, opts); -} - -function isWhile(node, opts) { - return (0, _is.default)("While", node, opts); -} - -function isExpressionWrapper(node, opts) { - return (0, _is.default)("ExpressionWrapper", node, opts); -} - -function isFor(node, opts) { - return (0, _is.default)("For", node, opts); -} - -function isForXStatement(node, opts) { - return (0, _is.default)("ForXStatement", node, opts); -} - -function isFunction(node, opts) { - return (0, _is.default)("Function", node, opts); -} - -function isFunctionParent(node, opts) { - return (0, _is.default)("FunctionParent", node, opts); -} - -function isPureish(node, opts) { - return (0, _is.default)("Pureish", node, opts); -} - -function isDeclaration(node, opts) { - return (0, _is.default)("Declaration", node, opts); -} - -function isPatternLike(node, opts) { - return (0, _is.default)("PatternLike", node, opts); -} - -function isLVal(node, opts) { - return (0, _is.default)("LVal", node, opts); -} - -function isTSEntityName(node, opts) { - return (0, _is.default)("TSEntityName", node, opts); -} - -function isLiteral(node, opts) { - return (0, _is.default)("Literal", node, opts); -} - -function isImmutable(node, opts) { - return (0, _is.default)("Immutable", node, opts); -} - -function isUserWhitespacable(node, opts) { - return (0, _is.default)("UserWhitespacable", node, opts); -} - -function isMethod(node, opts) { - return (0, _is.default)("Method", node, opts); -} - -function isObjectMember(node, opts) { - return (0, _is.default)("ObjectMember", node, opts); -} - -function isProperty(node, opts) { - return (0, _is.default)("Property", node, opts); -} - -function isUnaryLike(node, opts) { - return (0, _is.default)("UnaryLike", node, opts); -} - -function isPattern(node, opts) { - return (0, _is.default)("Pattern", node, opts); -} - -function isClass(node, opts) { - return (0, _is.default)("Class", node, opts); -} - -function isModuleDeclaration(node, opts) { - return (0, _is.default)("ModuleDeclaration", node, opts); -} - -function isExportDeclaration(node, opts) { - return (0, _is.default)("ExportDeclaration", node, opts); -} - -function isModuleSpecifier(node, opts) { - return (0, _is.default)("ModuleSpecifier", node, opts); -} - -function isFlow(node, opts) { - return (0, _is.default)("Flow", node, opts); -} - -function isFlowBaseAnnotation(node, opts) { - return (0, _is.default)("FlowBaseAnnotation", node, opts); -} - -function isFlowDeclaration(node, opts) { - return (0, _is.default)("FlowDeclaration", node, opts); -} - -function isFlowPredicate(node, opts) { - return (0, _is.default)("FlowPredicate", node, opts); -} - -function isJSX(node, opts) { - return (0, _is.default)("JSX", node, opts); -} - -function isTSTypeElement(node, opts) { - return (0, _is.default)("TSTypeElement", node, opts); -} - -function isTSType(node, opts) { - return (0, _is.default)("TSType", node, opts); -} - -function isNumberLiteral(node, opts) { - console.trace("The node type NumberLiteral has been renamed to NumericLiteral"); - return (0, _is.default)("NumberLiteral", node, opts); -} - -function isRegexLiteral(node, opts) { - console.trace("The node type RegexLiteral has been renamed to RegExpLiteral"); - return (0, _is.default)("RegexLiteral", node, opts); -} - -function isRestProperty(node, opts) { - console.trace("The node type RestProperty has been renamed to RestElement"); - return (0, _is.default)("RestProperty", node, opts); -} - -function isSpreadProperty(node, opts) { - console.trace("The node type SpreadProperty has been renamed to SpreadElement"); - return (0, _is.default)("SpreadProperty", node, opts); -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/is.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/is.js deleted file mode 100644 index c1e50d857b94a8..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/is.js +++ /dev/null @@ -1,22 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = is; - -var _shallowEqual = _interopRequireDefault(require("../utils/shallowEqual")); - -var _isType = _interopRequireDefault(require("./isType")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function is(type, node, opts) { - if (!node) return false; - var matches = (0, _isType.default)(node.type, type); - if (!matches) return false; - - if (typeof opts === "undefined") { - return true; - } else { - return (0, _shallowEqual.default)(node, opts); - } -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/isBinding.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/isBinding.js deleted file mode 100644 index 3644879cdde3c4..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/isBinding.js +++ /dev/null @@ -1,27 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = isBinding; - -var _getBindingIdentifiers = _interopRequireDefault(require("../retrievers/getBindingIdentifiers")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function isBinding(node, parent) { - var keys = _getBindingIdentifiers.default.keys[parent.type]; - - if (keys) { - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var val = parent[key]; - - if (Array.isArray(val)) { - if (val.indexOf(node) >= 0) return true; - } else { - if (val === node) return true; - } - } - } - - return false; -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/isBlockScoped.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/isBlockScoped.js deleted file mode 100644 index da5c53fce452a4..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/isBlockScoped.js +++ /dev/null @@ -1,14 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = isBlockScoped; - -var _generated = require("./generated"); - -var _isLet = _interopRequireDefault(require("./isLet")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function isBlockScoped(node) { - return (0, _generated.isFunctionDeclaration)(node) || (0, _generated.isClassDeclaration)(node) || (0, _isLet.default)(node); -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/isImmutable.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/isImmutable.js deleted file mode 100644 index 2ea002713e0de7..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/isImmutable.js +++ /dev/null @@ -1,24 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = isImmutable; - -var _isType = _interopRequireDefault(require("./isType")); - -var _generated = require("./generated"); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function isImmutable(node) { - if ((0, _isType.default)(node.type, "Immutable")) return true; - - if ((0, _generated.isIdentifier)(node)) { - if (node.name === "undefined") { - return true; - } else { - return false; - } - } - - return false; -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/isLet.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/isLet.js deleted file mode 100644 index a3a6169a030fa1..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/isLet.js +++ /dev/null @@ -1,12 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = isLet; - -var _generated = require("./generated"); - -var _constants = require("../constants"); - -function isLet(node) { - return (0, _generated.isVariableDeclaration)(node) && (node.kind !== "var" || node[_constants.BLOCK_SCOPED_SYMBOL]); -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/isNode.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/isNode.js deleted file mode 100644 index 641cb9c52b46c2..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/isNode.js +++ /dev/null @@ -1,10 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = isNode; - -var _definitions = require("../definitions"); - -function isNode(node) { - return !!(node && _definitions.VISITOR_KEYS[node.type]); -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/isNodesEquivalent.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/isNodesEquivalent.js deleted file mode 100644 index 549c0b470ff1d9..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/isNodesEquivalent.js +++ /dev/null @@ -1,50 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = isNodesEquivalent; - -var _definitions = require("../definitions"); - -function isNodesEquivalent(a, b) { - if (typeof a !== "object" || typeof b !== "object" || a == null || b == null) { - return a === b; - } - - if (a.type !== b.type) { - return false; - } - - var fields = Object.keys(_definitions.NODE_FIELDS[a.type] || a.type); - - for (var _i = 0; _i < fields.length; _i++) { - var field = fields[_i]; - - if (typeof a[field] !== typeof b[field]) { - return false; - } - - if (Array.isArray(a[field])) { - if (!Array.isArray(b[field])) { - return false; - } - - if (a[field].length !== b[field].length) { - return false; - } - - for (var i = 0; i < a[field].length; i++) { - if (!isNodesEquivalent(a[field][i], b[field][i])) { - return false; - } - } - - continue; - } - - if (!isNodesEquivalent(a[field], b[field])) { - return false; - } - } - - return true; -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/isReferenced.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/isReferenced.js deleted file mode 100644 index 5bb68b4ad44001..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/isReferenced.js +++ /dev/null @@ -1,99 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = isReferenced; - -function isReferenced(node, parent) { - switch (parent.type) { - case "BindExpression": - return parent.object === node || parent.callee === node; - - case "MemberExpression": - case "JSXMemberExpression": - if (parent.property === node && parent.computed) { - return true; - } else if (parent.object === node) { - return true; - } else { - return false; - } - - case "MetaProperty": - return false; - - case "ObjectProperty": - if (parent.key === node) { - return parent.computed; - } - - case "VariableDeclarator": - return parent.id !== node; - - case "ArrowFunctionExpression": - case "FunctionDeclaration": - case "FunctionExpression": - var _arr = parent.params; - - for (var _i = 0; _i < _arr.length; _i++) { - var param = _arr[_i]; - if (param === node) return false; - } - - return parent.id !== node; - - case "ExportSpecifier": - if (parent.source) { - return false; - } else { - return parent.local === node; - } - - case "ExportNamespaceSpecifier": - case "ExportDefaultSpecifier": - return false; - - case "JSXAttribute": - return parent.name !== node; - - case "ClassProperty": - if (parent.key === node) { - return parent.computed; - } else { - return parent.value === node; - } - - case "ImportDefaultSpecifier": - case "ImportNamespaceSpecifier": - case "ImportSpecifier": - return false; - - case "ClassDeclaration": - case "ClassExpression": - return parent.id !== node; - - case "ClassMethod": - case "ObjectMethod": - return parent.key === node && parent.computed; - - case "LabeledStatement": - return false; - - case "CatchClause": - return parent.param !== node; - - case "RestElement": - return false; - - case "AssignmentExpression": - return parent.right === node; - - case "AssignmentPattern": - return parent.right === node; - - case "ObjectPattern": - case "ArrayPattern": - return false; - } - - return true; -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/isScope.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/isScope.js deleted file mode 100644 index 91928ca59ef83a..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/isScope.js +++ /dev/null @@ -1,22 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = isScope; - -var _generated = require("./generated"); - -function isScope(node, parent) { - if ((0, _generated.isBlockStatement)(node) && (0, _generated.isFunction)(parent, { - body: node - })) { - return false; - } - - if ((0, _generated.isBlockStatement)(node) && (0, _generated.isCatchClause)(parent, { - body: node - })) { - return false; - } - - return (0, _generated.isScopable)(node); -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/isSpecifierDefault.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/isSpecifierDefault.js deleted file mode 100644 index 936d58e9e5b8e0..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/isSpecifierDefault.js +++ /dev/null @@ -1,12 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = isSpecifierDefault; - -var _generated = require("./generated"); - -function isSpecifierDefault(specifier) { - return (0, _generated.isImportDefaultSpecifier)(specifier) || (0, _generated.isIdentifier)(specifier.imported || specifier.exported, { - name: "default" - }); -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/isType.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/isType.js deleted file mode 100644 index 04410ca5d0b878..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/isType.js +++ /dev/null @@ -1,34 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = isType; - -var _definitions = require("../definitions"); - -function isType(nodeType, targetType) { - if (nodeType === targetType) return true; - if (_definitions.ALIAS_KEYS[targetType]) return false; - var aliases = _definitions.FLIPPED_ALIAS_KEYS[targetType]; - - if (aliases) { - if (aliases[0] === nodeType) return true; - - for (var _iterator = aliases, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var _alias = _ref; - if (nodeType === _alias) return true; - } - } - - return false; -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/isValidES3Identifier.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/isValidES3Identifier.js deleted file mode 100644 index ce98b3819c748a..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/isValidES3Identifier.js +++ /dev/null @@ -1,14 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = isValidES3Identifier; - -var _isValidIdentifier = _interopRequireDefault(require("./isValidIdentifier")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var RESERVED_WORDS_ES3_ONLY = new Set(["abstract", "boolean", "byte", "char", "double", "enum", "final", "float", "goto", "implements", "int", "interface", "long", "native", "package", "private", "protected", "public", "short", "static", "synchronized", "throws", "transient", "volatile"]); - -function isValidES3Identifier(name) { - return (0, _isValidIdentifier.default)(name) && !RESERVED_WORDS_ES3_ONLY.has(name); -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/isValidIdentifier.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/isValidIdentifier.js deleted file mode 100644 index 981ae2a6473fe4..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/isValidIdentifier.js +++ /dev/null @@ -1,18 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = isValidIdentifier; - -var _esutils = _interopRequireDefault(require("esutils")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function isValidIdentifier(name) { - if (typeof name !== "string" || _esutils.default.keyword.isReservedWordES6(name, true)) { - return false; - } else if (name === "await") { - return false; - } else { - return _esutils.default.keyword.isIdentifierNameES6(name); - } -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/isVar.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/isVar.js deleted file mode 100644 index df6b20731c833f..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/isVar.js +++ /dev/null @@ -1,14 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = isVar; - -var _generated = require("./generated"); - -var _constants = require("../constants"); - -function isVar(node) { - return (0, _generated.isVariableDeclaration)(node, { - kind: "var" - }) && !node[_constants.BLOCK_SCOPED_SYMBOL]; -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/matchesPattern.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/matchesPattern.js deleted file mode 100644 index b2cf579423a404..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/matchesPattern.js +++ /dev/null @@ -1,38 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = matchesPattern; - -var _generated = require("./generated"); - -function matchesPattern(member, match, allowPartial) { - if (!(0, _generated.isMemberExpression)(member)) return false; - var parts = Array.isArray(match) ? match : match.split("."); - var nodes = []; - var node; - - for (node = member; (0, _generated.isMemberExpression)(node); node = node.object) { - nodes.push(node.property); - } - - nodes.push(node); - if (nodes.length < parts.length) return false; - if (!allowPartial && nodes.length > parts.length) return false; - - for (var i = 0, j = nodes.length - 1; i < parts.length; i++, j--) { - var _node = nodes[j]; - var value = void 0; - - if ((0, _generated.isIdentifier)(_node)) { - value = _node.name; - } else if ((0, _generated.isStringLiteral)(_node)) { - value = _node.value; - } else { - return false; - } - - if (parts[i] !== value) return false; - } - - return true; -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/react/isCompatTag.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/react/isCompatTag.js deleted file mode 100644 index f5dc829a9b9529..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/react/isCompatTag.js +++ /dev/null @@ -1,8 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = isCompatTag; - -function isCompatTag(tagName) { - return !!tagName && /^[a-z]|-/.test(tagName); -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/react/isReactComponent.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/react/isReactComponent.js deleted file mode 100644 index af7abc2b0719a6..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/react/isReactComponent.js +++ /dev/null @@ -1,12 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = void 0; - -var _buildMatchMemberExpression = _interopRequireDefault(require("../buildMatchMemberExpression")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var isReactComponent = (0, _buildMatchMemberExpression.default)("React.Component"); -var _default = isReactComponent; -exports.default = _default; \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/validate.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/validate.js deleted file mode 100644 index ab96408b3a7760..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/lib/validators/validate.js +++ /dev/null @@ -1,16 +0,0 @@ -"use strict"; - -exports.__esModule = true; -exports.default = validate; - -var _definitions = require("../definitions"); - -function validate(node, key, val) { - if (!node) return; - var fields = _definitions.NODE_FIELDS[node.type]; - if (!fields) return; - var field = fields[key]; - if (!field || !field.validate) return; - if (field.optional && val == null) return; - field.validate(node, key, val); -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/package.json b/tools/node_modules/babel-eslint/node_modules/@babel/types/package.json deleted file mode 100644 index af3128ee9f3589..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/package.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "_from": "@babel/types@7.0.0-beta.36", - "_id": "@babel/types@7.0.0-beta.36", - "_inBundle": false, - "_integrity": "sha512-PyAORDO9um9tfnrddXgmWN9e6Sq9qxraQIt5ynqBOSXKA5qvK1kUr+Q3nSzKFdzorsiK+oqcUnAFvEoKxv9D+Q==", - "_location": "/babel-eslint/@babel/types", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "@babel/types@7.0.0-beta.36", - "name": "@babel/types", - "escapedName": "@babel%2ftypes", - "scope": "@babel", - "rawSpec": "7.0.0-beta.36", - "saveSpec": null, - "fetchSpec": "7.0.0-beta.36" - }, - "_requiredBy": [ - "/babel-eslint", - "/babel-eslint/@babel/helper-function-name", - "/babel-eslint/@babel/helper-get-function-arity", - "/babel-eslint/@babel/template", - "/babel-eslint/@babel/traverse" - ], - "_resolved": "https://registry.npmjs.org/@babel/types/-/types-7.0.0-beta.36.tgz", - "_shasum": "64f2004353de42adb72f9ebb4665fc35b5499d23", - "_spec": "@babel/types@7.0.0-beta.36", - "_where": "/home/mzasso/git/nodejs/node/tools/babel-eslint-tmp/node_modules/babel-eslint", - "author": { - "name": "Sebastian McKenzie", - "email": "sebmck@gmail.com" - }, - "bundleDependencies": false, - "dependencies": { - "esutils": "^2.0.2", - "lodash": "^4.2.0", - "to-fast-properties": "^2.0.0" - }, - "deprecated": false, - "description": "Babel Types is a Lodash-esque utility library for AST nodes", - "devDependencies": { - "@babel/generator": "7.0.0-beta.36", - "babylon": "7.0.0-beta.36" - }, - "homepage": "https://babeljs.io/", - "license": "MIT", - "main": "lib/index.js", - "name": "@babel/types", - "repository": { - "type": "git", - "url": "https://github.com/babel/babel/tree/master/packages/babel-types" - }, - "version": "7.0.0-beta.36" -} diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/scripts/generateTypeHelpers.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/scripts/generateTypeHelpers.js deleted file mode 100644 index e122145c3ca1f7..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/scripts/generateTypeHelpers.js +++ /dev/null @@ -1,31 +0,0 @@ -"use strict"; -const fs = require("fs"); -const path = require("path"); -const generateBuilders = require("./generators/generateBuilders"); -const generateValidators = require("./generators/generateValidators"); -const generateAsserts = require("./generators/generateAsserts"); -const generateConstants = require("./generators/generateConstants"); -const format = require("./utils/formatCode"); - -const baseDir = path.join(__dirname, "../src"); - -function writeFile(content, location) { - const file = path.join(baseDir, location); - - try { - fs.mkdirSync(path.dirname(file)); - } catch (error) { - if (error.code !== "EEXIST") { - throw error; - } - } - - fs.writeFileSync(file, format(content, file)); -} - -console.log("Generating @babel/types dynamic functions"); - -writeFile(generateBuilders(), "builders/generated/index.js"); -writeFile(generateValidators(), "validators/generated/index.js"); -writeFile(generateAsserts(), "asserts/generated/index.js"); -writeFile(generateConstants(), "constants/generated/index.js"); diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/scripts/generators/generateAsserts.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/scripts/generators/generateAsserts.js deleted file mode 100644 index 150e8557c733e4..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/scripts/generators/generateAsserts.js +++ /dev/null @@ -1,43 +0,0 @@ -"use strict"; -const definitions = require("../../lib/definitions"); - -function addAssertHelper(type) { - return `export function assert${type}(node: Object, opts?: Object = {}): void { - assert("${type}", node, opts) } - `; -} - -module.exports = function generateAsserts() { - let output = `// @flow -/* - * This file is auto-generated! Do not modify it directly. - * To re-generate run 'make build' - */ -import is from "../../validators/is"; - -function assert(type: string, node: Object, opts?: Object): void { - if (!is(type, node, opts)) { - throw new Error( - \`Expected type "\${type}" with option \${JSON.stringify(opts)}, but instead got "\${node.type}".\`, - ); - } -}\n\n`; - - Object.keys(definitions.VISITOR_KEYS).forEach(type => { - output += addAssertHelper(type); - }); - - Object.keys(definitions.FLIPPED_ALIAS_KEYS).forEach(type => { - output += addAssertHelper(type); - }); - - Object.keys(definitions.DEPRECATED_KEYS).forEach(type => { - const newType = definitions.DEPRECATED_KEYS[type]; - output += `export function assert${type}(node: Object, opts: Object): void { - console.trace("The node type ${type} has been renamed to ${newType}"); - assert("${type}", node, opts); -}\n`; - }); - - return output; -}; diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/scripts/generators/generateBuilders.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/scripts/generators/generateBuilders.js deleted file mode 100644 index 08a5b6fc61555f..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/scripts/generators/generateBuilders.js +++ /dev/null @@ -1,43 +0,0 @@ -"use strict"; -const definitions = require("../../lib/definitions"); -const formatBuilderName = require("../utils/formatBuilderName"); -const lowerFirst = require("../utils/lowerFirst"); - -module.exports = function generateBuilders() { - let output = `// @flow -/* - * This file is auto-generated! Do not modify it directly. - * To re-generate run 'make build' - */ -import builder from "../builder";\n\n`; - - Object.keys(definitions.BUILDER_KEYS).forEach(type => { - output += `export function ${type}(...args: Array): Object { return builder("${type}", ...args); } -export { ${type} as ${formatBuilderName(type)} };\n`; - - // This is needed for backwards compatibility. - // It should be removed in the next major version. - // JSXIdentifier -> jSXIdentifier - if (/^[A-Z]{2}/.test(type)) { - output += `export { ${type} as ${lowerFirst(type)} }\n`; - } - }); - - Object.keys(definitions.DEPRECATED_KEYS).forEach(type => { - const newType = definitions.DEPRECATED_KEYS[type]; - output += `export function ${type}(...args: Array): Object { - console.trace("The node type ${type} has been renamed to ${newType}"); - return ${type}("${type}", ...args); -} -export { ${type} as ${formatBuilderName(type)} };\n`; - - // This is needed for backwards compatibility. - // It should be removed in the next major version. - // JSXIdentifier -> jSXIdentifier - if (/^[A-Z]{2}/.test(type)) { - output += `export { ${type} as ${lowerFirst(type)} }\n`; - } - }); - - return output; -}; diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/scripts/generators/generateConstants.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/scripts/generators/generateConstants.js deleted file mode 100644 index 1e4d2cabaec4da..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/scripts/generators/generateConstants.js +++ /dev/null @@ -1,17 +0,0 @@ -"use strict"; -const definitions = require("../../lib/definitions"); - -module.exports = function generateConstants() { - let output = `// @flow -/* - * This file is auto-generated! Do not modify it directly. - * To re-generate run 'make build' - */ -import { FLIPPED_ALIAS_KEYS } from "../../definitions";\n\n`; - - Object.keys(definitions.FLIPPED_ALIAS_KEYS).forEach(type => { - output += `export const ${type.toUpperCase()}_TYPES = FLIPPED_ALIAS_KEYS["${type}"];\n`; - }); - - return output; -}; diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/scripts/generators/generateValidators.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/scripts/generators/generateValidators.js deleted file mode 100644 index b523d6adc85354..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/scripts/generators/generateValidators.js +++ /dev/null @@ -1,35 +0,0 @@ -"use strict"; -const definitions = require("../../lib/definitions"); - -function addIsHelper(type) { - return `export function is${type}(node: Object, opts?: Object): boolean { - return is("${type}", node, opts) } - `; -} - -module.exports = function generateValidators() { - let output = `// @flow -/* - * This file is auto-generated! Do not modify it directly. - * To re-generate run 'make build' - */ -import is from "../is";\n\n`; - - Object.keys(definitions.VISITOR_KEYS).forEach(type => { - output += addIsHelper(type); - }); - - Object.keys(definitions.FLIPPED_ALIAS_KEYS).forEach(type => { - output += addIsHelper(type); - }); - - Object.keys(definitions.DEPRECATED_KEYS).forEach(type => { - const newType = definitions.DEPRECATED_KEYS[type]; - output += `export function is${type}(node: Object, opts: Object): boolean { - console.trace("The node type ${type} has been renamed to ${newType}"); - return is("${type}", node, opts); -}\n`; - }); - - return output; -}; diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/scripts/utils/formatBuilderName.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/scripts/utils/formatBuilderName.js deleted file mode 100644 index 1b543a9bfaf570..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/scripts/utils/formatBuilderName.js +++ /dev/null @@ -1,9 +0,0 @@ -"use strict"; - -const toLowerCase = Function.call.bind("".toLowerCase); - -module.exports = function formatBuilderName(type) { - // FunctionExpression -> functionExpression - // JSXIdentifier -> jsxIdentifier - return type.replace(/^([A-Z](?=[a-z])|[A-Z]+(?=[A-Z]))/, toLowerCase); -}; diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/scripts/utils/formatCode.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/scripts/utils/formatCode.js deleted file mode 100644 index 9d279e6e49ec41..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/scripts/utils/formatCode.js +++ /dev/null @@ -1,9 +0,0 @@ -"use strict"; -const prettier = require("prettier"); - -module.exports = function formatCode(code, filename) { - filename = filename || __filename; - const prettierConfig = prettier.resolveConfig.sync(filename); - - return prettier.format(code, prettierConfig); -}; diff --git a/tools/node_modules/babel-eslint/node_modules/@babel/types/scripts/utils/lowerFirst.js b/tools/node_modules/babel-eslint/node_modules/@babel/types/scripts/utils/lowerFirst.js deleted file mode 100644 index 9e7b0cee51c116..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/@babel/types/scripts/utils/lowerFirst.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -module.exports = function lowerFirst(string) { - return string[0].toLowerCase() + string.slice(1); -}; diff --git a/tools/node_modules/babel-eslint/node_modules/ansi-styles/index.js b/tools/node_modules/babel-eslint/node_modules/ansi-styles/index.js deleted file mode 100644 index 3d3baa66d75d1c..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/ansi-styles/index.js +++ /dev/null @@ -1,152 +0,0 @@ -'use strict'; -const colorConvert = require('color-convert'); - -const wrapAnsi16 = (fn, offset) => function () { - const code = fn.apply(colorConvert, arguments); - return `\u001B[${code + offset}m`; -}; - -const wrapAnsi256 = (fn, offset) => function () { - const code = fn.apply(colorConvert, arguments); - return `\u001B[${38 + offset};5;${code}m`; -}; - -const wrapAnsi16m = (fn, offset) => function () { - const rgb = fn.apply(colorConvert, arguments); - return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; -}; - -function assembleStyles() { - const codes = new Map(); - const styles = { - modifier: { - reset: [0, 0], - // 21 isn't widely supported and 22 does the same thing - bold: [1, 22], - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29] - }, - color: { - black: [30, 39], - red: [31, 39], - green: [32, 39], - yellow: [33, 39], - blue: [34, 39], - magenta: [35, 39], - cyan: [36, 39], - white: [37, 39], - gray: [90, 39], - - // Bright color - redBright: [91, 39], - greenBright: [92, 39], - yellowBright: [93, 39], - blueBright: [94, 39], - magentaBright: [95, 39], - cyanBright: [96, 39], - whiteBright: [97, 39] - }, - bgColor: { - bgBlack: [40, 49], - bgRed: [41, 49], - bgGreen: [42, 49], - bgYellow: [43, 49], - bgBlue: [44, 49], - bgMagenta: [45, 49], - bgCyan: [46, 49], - bgWhite: [47, 49], - - // Bright color - bgBlackBright: [100, 49], - bgRedBright: [101, 49], - bgGreenBright: [102, 49], - bgYellowBright: [103, 49], - bgBlueBright: [104, 49], - bgMagentaBright: [105, 49], - bgCyanBright: [106, 49], - bgWhiteBright: [107, 49] - } - }; - - // Fix humans - styles.color.grey = styles.color.gray; - - for (const groupName of Object.keys(styles)) { - const group = styles[groupName]; - - for (const styleName of Object.keys(group)) { - const style = group[styleName]; - - styles[styleName] = { - open: `\u001B[${style[0]}m`, - close: `\u001B[${style[1]}m` - }; - - group[styleName] = styles[styleName]; - - codes.set(style[0], style[1]); - } - - Object.defineProperty(styles, groupName, { - value: group, - enumerable: false - }); - - Object.defineProperty(styles, 'codes', { - value: codes, - enumerable: false - }); - } - - const rgb2rgb = (r, g, b) => [r, g, b]; - - styles.color.close = '\u001B[39m'; - styles.bgColor.close = '\u001B[49m'; - - styles.color.ansi = {}; - styles.color.ansi256 = {}; - styles.color.ansi16m = { - rgb: wrapAnsi16m(rgb2rgb, 0) - }; - - styles.bgColor.ansi = {}; - styles.bgColor.ansi256 = {}; - styles.bgColor.ansi16m = { - rgb: wrapAnsi16m(rgb2rgb, 10) - }; - - for (const key of Object.keys(colorConvert)) { - if (typeof colorConvert[key] !== 'object') { - continue; - } - - const suite = colorConvert[key]; - - if ('ansi16' in suite) { - styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0); - styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10); - } - - if ('ansi256' in suite) { - styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0); - styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10); - } - - if ('rgb' in suite) { - styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0); - styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10); - } - } - - return styles; -} - -// Make the export immutable -Object.defineProperty(module, 'exports', { - enumerable: true, - get: assembleStyles -}); diff --git a/tools/node_modules/babel-eslint/node_modules/ansi-styles/license b/tools/node_modules/babel-eslint/node_modules/ansi-styles/license deleted file mode 100644 index e7af2f77107d73..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/ansi-styles/license +++ /dev/null @@ -1,9 +0,0 @@ -MIT License - -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/node_modules/babel-eslint/node_modules/ansi-styles/package.json b/tools/node_modules/babel-eslint/node_modules/ansi-styles/package.json deleted file mode 100644 index 6e9e19423b4668..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/ansi-styles/package.json +++ /dev/null @@ -1,86 +0,0 @@ -{ - "_from": "ansi-styles@^3.1.0", - "_id": "ansi-styles@3.2.0", - "_inBundle": false, - "_integrity": "sha512-NnSOmMEYtVR2JVMIGTzynRkkaxtiq1xnFBcdQD/DnNCYPoEPsVJhM98BDyaoNOQIi7p4okdi3E27eN7GQbsUug==", - "_location": "/babel-eslint/ansi-styles", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "ansi-styles@^3.1.0", - "name": "ansi-styles", - "escapedName": "ansi-styles", - "rawSpec": "^3.1.0", - "saveSpec": null, - "fetchSpec": "^3.1.0" - }, - "_requiredBy": [ - "/babel-eslint/chalk" - ], - "_resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.0.tgz", - "_shasum": "c159b8d5be0f9e5a6f346dab94f16ce022161b88", - "_spec": "ansi-styles@^3.1.0", - "_where": "/home/mzasso/git/nodejs/node/tools/babel-eslint-tmp/node_modules/babel-eslint/node_modules/chalk", - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" - }, - "ava": { - "require": "babel-polyfill" - }, - "bugs": { - "url": "https://github.com/chalk/ansi-styles/issues" - }, - "bundleDependencies": false, - "dependencies": { - "color-convert": "^1.9.0" - }, - "deprecated": false, - "description": "ANSI escape codes for styling strings in the terminal", - "devDependencies": { - "ava": "*", - "babel-polyfill": "^6.23.0", - "xo": "*" - }, - "engines": { - "node": ">=4" - }, - "files": [ - "index.js" - ], - "homepage": "https://github.com/chalk/ansi-styles#readme", - "keywords": [ - "ansi", - "styles", - "color", - "colour", - "colors", - "terminal", - "console", - "cli", - "string", - "tty", - "escape", - "formatting", - "rgb", - "256", - "shell", - "xterm", - "log", - "logging", - "command-line", - "text" - ], - "license": "MIT", - "name": "ansi-styles", - "repository": { - "type": "git", - "url": "git+https://github.com/chalk/ansi-styles.git" - }, - "scripts": { - "test": "xo && ava" - }, - "version": "3.2.0" -} diff --git a/tools/node_modules/babel-eslint/node_modules/ansi-styles/readme.md b/tools/node_modules/babel-eslint/node_modules/ansi-styles/readme.md deleted file mode 100644 index dce368742b42af..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/ansi-styles/readme.md +++ /dev/null @@ -1,147 +0,0 @@ -# ansi-styles [![Build Status](https://travis-ci.org/chalk/ansi-styles.svg?branch=master)](https://travis-ci.org/chalk/ansi-styles) - -> [ANSI escape codes](http://en.wikipedia.org/wiki/ANSI_escape_code#Colors_and_Styles) for styling strings in the terminal - -You probably want the higher-level [chalk](https://github.com/chalk/chalk) module for styling your strings. - -![](screenshot.png) - - -## Install - -``` -$ npm install ansi-styles -``` - - -## Usage - -```js -const style = require('ansi-styles'); - -console.log(`${style.green.open}Hello world!${style.green.close}`); - - -// Color conversion between 16/256/truecolor -// NOTE: If conversion goes to 16 colors or 256 colors, the original color -// may be degraded to fit that color palette. This means terminals -// that do not support 16 million colors will best-match the -// original color. -console.log(style.bgColor.ansi.hsl(120, 80, 72) + 'Hello world!' + style.bgColor.close); -console.log(style.color.ansi256.rgb(199, 20, 250) + 'Hello world!' + style.color.close); -console.log(style.color.ansi16m.hex('#ABCDEF') + 'Hello world!' + style.color.close); -``` - -## API - -Each style has an `open` and `close` property. - - -## Styles - -### Modifiers - -- `reset` -- `bold` -- `dim` -- `italic` *(Not widely supported)* -- `underline` -- `inverse` -- `hidden` -- `strikethrough` *(Not widely supported)* - -### Colors - -- `black` -- `red` -- `green` -- `yellow` -- `blue` -- `magenta` -- `cyan` -- `white` -- `gray` ("bright black") -- `redBright` -- `greenBright` -- `yellowBright` -- `blueBright` -- `magentaBright` -- `cyanBright` -- `whiteBright` - -### Background colors - -- `bgBlack` -- `bgRed` -- `bgGreen` -- `bgYellow` -- `bgBlue` -- `bgMagenta` -- `bgCyan` -- `bgWhite` -- `bgBlackBright` -- `bgRedBright` -- `bgGreenBright` -- `bgYellowBright` -- `bgBlueBright` -- `bgMagentaBright` -- `bgCyanBright` -- `bgWhiteBright` - - -## Advanced usage - -By default, you get a map of styles, but the styles are also available as groups. They are non-enumerable so they don't show up unless you access them explicitly. This makes it easier to expose only a subset in a higher-level module. - -- `style.modifier` -- `style.color` -- `style.bgColor` - -###### Example - -```js -console.log(style.color.green.open); -``` - -Raw escape codes (i.e. without the CSI escape prefix `\u001B[` and render mode postfix `m`) are available under `style.codes`, which returns a `Map` with the open codes as keys and close codes as values. - -###### Example - -```js -console.log(style.codes.get(36)); -//=> 39 -``` - - -## [256 / 16 million (TrueColor) support](https://gist.github.com/XVilka/8346728) - -`ansi-styles` uses the [`color-convert`](https://github.com/Qix-/color-convert) package to allow for converting between various colors and ANSI escapes, with support for 256 and 16 million colors. - -To use these, call the associated conversion function with the intended output, for example: - -```js -style.color.ansi.rgb(100, 200, 15); // RGB to 16 color ansi foreground code -style.bgColor.ansi.rgb(100, 200, 15); // RGB to 16 color ansi background code - -style.color.ansi256.hsl(120, 100, 60); // HSL to 256 color ansi foreground code -style.bgColor.ansi256.hsl(120, 100, 60); // HSL to 256 color ansi foreground code - -style.color.ansi16m.hex('#C0FFEE'); // Hex (RGB) to 16 million color foreground code -style.bgColor.ansi16m.hex('#C0FFEE'); // Hex (RGB) to 16 million color background code -``` - - -## Related - -- [ansi-escapes](https://github.com/sindresorhus/ansi-escapes) - ANSI escape codes for manipulating the terminal - - -## Maintainers - -- [Sindre Sorhus](https://github.com/sindresorhus) -- [Josh Junon](https://github.com/qix-) - - -## License - -MIT diff --git a/tools/node_modules/babel-eslint/node_modules/babylon/LICENSE b/tools/node_modules/babel-eslint/node_modules/babylon/LICENSE deleted file mode 100644 index d4c7fc583804df..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/babylon/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (C) 2012-2014 by various contributors (see AUTHORS) - -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/node_modules/babel-eslint/node_modules/babylon/README.md b/tools/node_modules/babel-eslint/node_modules/babylon/README.md deleted file mode 100644 index 78dd00be332591..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/babylon/README.md +++ /dev/null @@ -1,163 +0,0 @@ -

- babylon -

- -

- Babylon is a JavaScript parser used in Babel. -

- - - The latest ECMAScript version enabled by default (ES2017). - - Comment attachment. - - Support for JSX, Flow, Typescript. - - Support for experimental language proposals (accepting PRs for anything at least [stage-0](https://github.com/tc39/proposals/blob/master/stage-0-proposals.md)). - -## Credits - -Heavily based on [acorn](https://github.com/marijnh/acorn) and [acorn-jsx](https://github.com/RReverser/acorn-jsx), -thanks to the awesome work of [@RReverser](https://github.com/RReverser) and [@marijnh](https://github.com/marijnh). - -## API - -### `babylon.parse(code, [options])` - -### `babylon.parseExpression(code, [options])` - -`parse()` parses the provided `code` as an entire ECMAScript program, while -`parseExpression()` tries to parse a single Expression with performance in -mind. When in doubt, use `.parse()`. - -### Options - -- **allowImportExportEverywhere**: By default, `import` and `export` - declarations can only appear at a program's top level. Setting this - option to `true` allows them anywhere where a statement is allowed. - -- **allowReturnOutsideFunction**: By default, a return statement at - the top level raises an error. Set this to `true` to accept such - code. - -- **allowSuperOutsideMethod**: TODO - -- **sourceType**: Indicate the mode the code should be parsed in. Can be - one of `"script"`, `"module"`, or `"unambiguous"`. Defaults to `"script"`. `"unambiguous"` will make Babylon attempt to _guess_, based on the presence of ES6 `import` or `export` statements. Files with ES6 `import`s and `export`s are considered `"module"` and are otherwise `"script"`. - -- **sourceFilename**: Correlate output AST nodes with their source filename. Useful when generating code and source maps from the ASTs of multiple input files. - -- **startLine**: By default, the first line of code parsed is treated as line 1. You can provide a line number to alternatively start with. Useful for integration with other source tools. - -- **plugins**: Array containing the plugins that you want to enable. - -- **strictMode**: TODO - -- **ranges**: Adds a `ranges` property to each node: `[node.start, node.end]` - -- **tokens**: Adds all parsed tokens to a `tokens` property on the `File` node - -### Output - -Babylon generates AST according to [Babel AST format][]. -It is based on [ESTree spec][] with the following deviations: - -> There is now an `estree` plugin which reverts these deviations - -- [Literal][] token is replaced with [StringLiteral][], [NumericLiteral][], [BooleanLiteral][], [NullLiteral][], [RegExpLiteral][] -- [Property][] token is replaced with [ObjectProperty][] and [ObjectMethod][] -- [MethodDefinition][] is replaced with [ClassMethod][] -- [Program][] and [BlockStatement][] contain additional `directives` field with [Directive][] and [DirectiveLiteral][] -- [ClassMethod][], [ObjectProperty][], and [ObjectMethod][] value property's properties in [FunctionExpression][] is coerced/brought into the main method node. - -AST for JSX code is based on [Facebook JSX AST][] with the addition of one node type: - -- `JSXText` - -[Babel AST format]: https://github.com/babel/babylon/blob/master/ast/spec.md -[ESTree spec]: https://github.com/estree/estree - -[Literal]: https://github.com/estree/estree/blob/master/es5.md#literal -[Property]: https://github.com/estree/estree/blob/master/es5.md#property -[MethodDefinition]: https://github.com/estree/estree/blob/master/es2015.md#methoddefinition - -[StringLiteral]: https://github.com/babel/babylon/blob/master/ast/spec.md#stringliteral -[NumericLiteral]: https://github.com/babel/babylon/blob/master/ast/spec.md#numericliteral -[BooleanLiteral]: https://github.com/babel/babylon/blob/master/ast/spec.md#booleanliteral -[NullLiteral]: https://github.com/babel/babylon/blob/master/ast/spec.md#nullliteral -[RegExpLiteral]: https://github.com/babel/babylon/blob/master/ast/spec.md#regexpliteral -[ObjectProperty]: https://github.com/babel/babylon/blob/master/ast/spec.md#objectproperty -[ObjectMethod]: https://github.com/babel/babylon/blob/master/ast/spec.md#objectmethod -[ClassMethod]: https://github.com/babel/babylon/blob/master/ast/spec.md#classmethod -[Program]: https://github.com/babel/babylon/blob/master/ast/spec.md#programs -[BlockStatement]: https://github.com/babel/babylon/blob/master/ast/spec.md#blockstatement -[Directive]: https://github.com/babel/babylon/blob/master/ast/spec.md#directive -[DirectiveLiteral]: https://github.com/babel/babylon/blob/master/ast/spec.md#directiveliteral -[FunctionExpression]: https://github.com/babel/babylon/blob/master/ast/spec.md#functionexpression - -[Facebook JSX AST]: https://github.com/facebook/jsx/blob/master/AST.md - -### Semver - -Babylon follows semver in most situations. The only thing to note is that some spec-compliancy bug fixes may be released under patch versions. - -For example: We push a fix to early error on something like [#107](https://github.com/babel/babylon/pull/107) - multiple default exports per file. That would be considered a bug fix even though it would cause a build to fail. - -### Example - -```javascript -require("babylon").parse("code", { - // parse in strict mode and allow module declarations - sourceType: "module", - - plugins: [ - // enable jsx and flow syntax - "jsx", - "flow" - ] -}); -``` - -### Plugins - -| Name | Code Example | -|------|--------------| -| `estree` ([repo](https://github.com/estree/estree)) | n/a | -| `jsx` ([repo](https://facebook.github.io/jsx/)) | `{s}` | -| `flow` ([repo](https://github.com/facebook/flow)) | `var a: string = "";` | -| `typescript` ([repo](https://github.com/Microsoft/TypeScript)) | `var a: string = "";` | -| `doExpressions` | `var a = do { if (true) { 'hi'; } };` | -| `objectRestSpread` ([proposal](https://github.com/tc39/proposal-object-rest-spread)) | `var a = { b, ...c };` | -| `decorators` (Stage 1) and `decorators2` (Stage 2 [proposal](https://github.com/tc39/proposal-decorators)) | `@a class A {}` | -| `classProperties` ([proposal](https://github.com/tc39/proposal-class-public-fields)) | `class A { b = 1; }` | -| `classPrivateProperties` ([proposal](https://github.com/tc39/proposal-private-fields)) | `class A { #b = 1; }` | -| `classPrivateMethods` ([proposal](https://github.com/tc39/proposal-private-methods)) | `class A { #c() {} }` | -| `exportExtensions` ([proposal 1](https://github.com/leebyron/ecmascript-export-default-from)), ([proposal 2](https://github.com/leebyron/ecmascript-export-ns-from)) | Proposal 1: `export v from "mod"` Proposal 2: `export * as ns from "mod"` | -| `asyncGenerators` ([proposal](https://github.com/tc39/proposal-async-iteration)) | `async function*() {}`, `for await (let a of b) {}` | -| `functionBind` ([proposal](https://github.com/zenparsing/es-function-bind)) | `a::b`, `::console.log` | -| `functionSent` | `function.sent` | -| `dynamicImport` ([proposal](https://github.com/tc39/proposal-dynamic-import)) | `import('./guy').then(a)` | -| `numericSeparator` ([proposal](https://github.com/samuelgoto/proposal-numeric-separator)) | `1_000_000` | -| `optionalChaining` ([proposal](https://github.com/tc39/proposal-optional-chaining)) | `a?.b` | -| `importMeta` ([proposal](https://github.com/tc39/proposal-import-meta)) | `import.meta.url` | -| `bigInt` ([proposal](https://github.com/tc39/proposal-bigint)) | `100n` | -| `optionalCatchBinding` ([proposal](https://github.com/babel/proposals/issues/7)) | `try {throw 0;} catch{do();}` | -| `throwExpressions` ([proposal](https://github.com/babel/proposals/issues/23)) | `() => throw new Error("")` | -| `pipelineOperator` ([proposal](https://github.com/babel/proposals/issues/29)) | `a \|> b` | -| `nullishCoalescingOperator` ([proposal](https://github.com/babel/proposals/issues/14)) | `a ?? b` | - -### FAQ - -#### Will Babylon support a plugin system? - -Previous issues: [babel/babel#1351](https://github.com/babel/babel/issues/1351), [#500](https://github.com/babel/babylon/issues/500). - -We currently aren't willing to commit to supporting the API for plugins or the resulting ecosystem (there is already enough work maintaining Babel's own plugin system). It's not clear how to make that API effective, and it would limit out ability to refactor and optimize the codebase. - -Our current recommendation for those that want to create their own custom syntax is for users to fork Babylon. - -To consume your custom parser, you can add to your `.babelrc` via its npm package name or require it if using JavaScript, - -```json -{ - "parserOpts": { - "parser": "custom-fork-of-babylon-on-npm-here" - } -} -``` diff --git a/tools/node_modules/babel-eslint/node_modules/babylon/bin/babylon.js b/tools/node_modules/babel-eslint/node_modules/babylon/bin/babylon.js deleted file mode 100755 index 440eef35ff8f8f..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/babylon/bin/babylon.js +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env node -/* eslint no-var: 0 */ - -var babylon = require(".."); -var fs = require("fs"); - -var filename = process.argv[2]; -if (!filename) { - console.error("no filename specified"); - process.exit(0); -} - -var file = fs.readFileSync(filename, "utf8"); -var ast = babylon.parse(file); - -console.log(JSON.stringify(ast, null, " ")); diff --git a/tools/node_modules/babel-eslint/node_modules/babylon/lib/index.js b/tools/node_modules/babel-eslint/node_modules/babylon/lib/index.js deleted file mode 100644 index 901202fd4d02b9..00000000000000 --- a/tools/node_modules/babel-eslint/node_modules/babylon/lib/index.js +++ /dev/null @@ -1,10635 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, '__esModule', { value: true }); - -function _inheritsLoose(subClass, superClass) { - subClass.prototype = Object.create(superClass.prototype); - subClass.prototype.constructor = subClass; - subClass.__proto__ = superClass; -} - -// A second optional argument can be given to further configure -// the parser process. These options are recognized: -var defaultOptions = { - // Source type ("script" or "module") for different semantics - sourceType: "script", - // Source filename. - sourceFilename: undefined, - // Line from which to start counting source. Useful for - // integration with other tools. - startLine: 1, - // 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, - // TODO - allowSuperOutsideMethod: false, - // An array of plugins to enable - plugins: [], - // TODO - strictMode: 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, - // Adds all parsed tokens to a `tokens` property on the `File` node - tokens: false -}; // Interpret and default an options object - -function getOptions(opts) { - var options = {}; - - for (var key in defaultOptions) { - options[key] = opts && opts[key] != null ? opts[key] : defaultOptions[key]; - } - - return options; -} - -// ## 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). -// -// `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 beforeExpr = true; -var startsExpr = true; -var isLoop = true; -var isAssign = true; -var prefix = true; -var postfix = true; -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.rightAssociative = !!conf.rightAssociative; - this.isLoop = !!conf.isLoop; - this.isAssign = !!conf.isAssign; - this.prefix = !!conf.prefix; - this.postfix = !!conf.postfix; - this.binop = conf.binop === 0 ? 0 : conf.binop || null; - this.updateContext = null; -}; - -var KeywordTokenType = -/*#__PURE__*/ -function (_TokenType) { - _inheritsLoose(KeywordTokenType, _TokenType); - - function KeywordTokenType(name, options) { - if (options === void 0) { - options = {}; - } - - options.keyword = name; - return _TokenType.call(this, name, options) || this; - } - - return KeywordTokenType; -}(TokenType); - -var BinopTokenType = -/*#__PURE__*/ -function (_TokenType2) { - _inheritsLoose(BinopTokenType, _TokenType2); - - function BinopTokenType(name, prec) { - return _TokenType2.call(this, name, { - beforeExpr, - binop: prec - }) || this; - } - - return BinopTokenType; -}(TokenType); -var types = { - num: new TokenType("num", { - startsExpr - }), - bigint: new TokenType("bigint", { - 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, - startsExpr - }), - bracketR: new TokenType("]"), - braceL: new TokenType("{", { - beforeExpr, - startsExpr - }), - braceBarL: new TokenType("{|", { - beforeExpr, - startsExpr - }), - braceR: new TokenType("}"), - braceBarR: new TokenType("|}"), - parenL: new TokenType("(", { - beforeExpr, - startsExpr - }), - parenR: new TokenType(")"), - comma: new TokenType(",", { - beforeExpr - }), - semi: new TokenType(";", { - beforeExpr - }), - colon: new TokenType(":", { - beforeExpr - }), - doubleColon: new TokenType("::", { - beforeExpr - }), - dot: new TokenType("."), - question: new TokenType("?", { - beforeExpr - }), - questionDot: new TokenType("?."), - arrow: new TokenType("=>", { - beforeExpr - }), - template: new TokenType("template"), - ellipsis: new TokenType("...", { - beforeExpr - }), - backQuote: new TokenType("`", { - startsExpr - }), - dollarBraceL: new TokenType("${", { - beforeExpr, - startsExpr - }), - at: new TokenType("@"), - hash: new TokenType("#"), - // 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, - isAssign - }), - assign: new TokenType("_=", { - beforeExpr, - isAssign - }), - incDec: new TokenType("++/--", { - prefix, - postfix, - startsExpr - }), - bang: new TokenType("!", { - beforeExpr, - prefix, - startsExpr - }), - tilde: new TokenType("~", { - beforeExpr, - prefix, - startsExpr - }), - pipeline: new BinopTokenType("|>", 0), - nullishCoalescing: new BinopTokenType("??", 1), - logicalOR: new BinopTokenType("||", 1), - logicalAND: new BinopTokenType("&&", 2), - bitwiseOR: new BinopTokenType("|", 3), - bitwiseXOR: new BinopTokenType("^", 4), - bitwiseAND: new BinopTokenType("&", 5), - equality: new BinopTokenType("==/!=", 6), - relational: new BinopTokenType("", 7), - bitShift: new BinopTokenType("<>", 8), - plusMin: new TokenType("+/-", { - beforeExpr, - binop: 9, - prefix, - startsExpr - }), - modulo: new BinopTokenType("%", 10), - star: new BinopTokenType("*", 10), - slash: new BinopTokenType("/", 10), - exponent: new TokenType("**", { - beforeExpr, - binop: 11, - rightAssociative: true - }) -}; -var keywords = { - break: new KeywordTokenType("break"), - case: new KeywordTokenType("case", { - beforeExpr - }), - catch: new KeywordTokenType("catch"), - continue: new KeywordTokenType("continue"), - debugger: new KeywordTokenType("debugger"), - default: new KeywordTokenType("default", { - beforeExpr - }), - do: new KeywordTokenType("do", { - isLoop, - beforeExpr - }), - else: new KeywordTokenType("else", { - beforeExpr - }), - finally: new KeywordTokenType("finally"), - for: new KeywordTokenType("for", { - isLoop - }), - function: new KeywordTokenType("function", { - startsExpr - }), - if: new KeywordTokenType("if"), - return: new KeywordTokenType("return", { - beforeExpr - }), - switch: new KeywordTokenType("switch"), - throw: new KeywordTokenType("throw", { - beforeExpr, - prefix, - startsExpr - }), - try: new KeywordTokenType("try"), - var: new KeywordTokenType("var"), - let: new KeywordTokenType("let"), - const: new KeywordTokenType("const"), - while: new KeywordTokenType("while", { - isLoop - }), - with: new KeywordTokenType("with"), - new: new KeywordTokenType("new", { - beforeExpr, - startsExpr - }), - this: new KeywordTokenType("this", { - startsExpr - }), - super: new KeywordTokenType("super", { - startsExpr - }), - class: new KeywordTokenType("class"), - extends: new KeywordTokenType("extends", { - beforeExpr - }), - export: new KeywordTokenType("export"), - import: new KeywordTokenType("import", { - startsExpr - }), - yield: new KeywordTokenType("yield", { - beforeExpr, - startsExpr - }), - null: new KeywordTokenType("null", { - startsExpr - }), - true: new KeywordTokenType("true", { - startsExpr - }), - false: new KeywordTokenType("false", { - startsExpr - }), - in: new KeywordTokenType("in", { - beforeExpr, - binop: 7 - }), - instanceof: new KeywordTokenType("instanceof", { - beforeExpr, - binop: 7 - }), - typeof: new KeywordTokenType("typeof", { - beforeExpr, - prefix, - startsExpr - }), - void: new KeywordTokenType("void", { - beforeExpr, - prefix, - startsExpr - }), - delete: new KeywordTokenType("delete", { - beforeExpr, - prefix, - startsExpr - }) -}; // Map keyword names to token types. - -Object.keys(keywords).forEach(function (name) { - types["_" + name] = keywords[name]; -}); - -/* eslint max-len: 0 */ -function makePredicate(words) { - var wordsArr = words.split(" "); - return function (str) { - return wordsArr.indexOf(str) >= 0; - }; -} // Reserved word lists for various dialects of the language - - -var reservedWords = { - "6": makePredicate("enum await"), - strict: makePredicate("implements interface let package private protected public static yield"), - strictBind: makePredicate("eval arguments") -}; // And the keywords - -var isKeyword = makePredicate("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 let const class extends export import yield 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`. - -/* prettier-ignore */ - -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\u0860-\u086a\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\u09fc\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-\u312e\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fea\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"; -/* prettier-ignore */ - -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\u0afa-\u0aff\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\u0d00-\u0d03\u0d3b\u0d3c\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\u1cf7-\u1cf9\u1dc0-\u1df9\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`. - -/* prettier-ignore */ - -var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 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, 257, 0, 11, 39, 8, 0, 22, 0, 12, 39, 3, 3, 55, 56, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 698, 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, 1, 31, 6124, 20, 754, 9486, 286, 82, 395, 2309, 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, 15, 7472, 3104, 541]; -/* prettier-ignore */ - -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, 280, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 19719, 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; - } - - return false; -} // Test whether a given character code starts an identifier. - - -function isIdentifierStart(code) { - 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)); - } - - return isInAstralSet(code, astralIdentifierStartCodes); -} // Test whether a given character is part of an identifier. - -function isIdentifierChar(code) { - 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)); - } - - return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes); -} - -// 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]/; - -// 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) // Takes a Tokenizer as a this-parameter, and returns void. -{ - this.token = token; - this.isExpr = !!isExpr; - this.preserveSpace = !!preserveSpace; - this.override = override; -}; -var types$1 = { - braceStatement: new TokContext("{", false), - braceExpression: new TokContext("{", true), - templateQuasi: new TokContext("${", true), - parenStatement: new TokContext("(", false), - parenExpression: new TokContext("(", true), - template: new TokContext("`", true, true, function (p) { - return p.readTmplToken(); - }), - functionExpression: new TokContext("function", true) -}; // Token-specific context update code - -types.parenR.updateContext = types.braceR.updateContext = function () { - if (this.state.context.length === 1) { - this.state.exprAllowed = true; - return; - } - - var out = this.state.context.pop(); - - if (out === types$1.braceStatement && this.curContext() === types$1.functionExpression) { - this.state.context.pop(); - this.state.exprAllowed = false; - } else if (out === types$1.templateQuasi) { - this.state.exprAllowed = true; - } else { - this.state.exprAllowed = !out.isExpr; - } -}; - -types.name.updateContext = function (prevType) { - if (this.state.value === "of" && this.curContext() === types$1.parenStatement) { - this.state.exprAllowed = !prevType.beforeExpr; - return; - } - - this.state.exprAllowed = false; - - if (prevType === types._let || prevType === types._const || prevType === types._var) { - if (lineBreak.test(this.input.slice(this.state.end))) { - this.state.exprAllowed = true; - } - } -}; - -types.braceL.updateContext = function (prevType) { - this.state.context.push(this.braceIsBlock(prevType) ? types$1.braceStatement : types$1.braceExpression); - this.state.exprAllowed = true; -}; - -types.dollarBraceL.updateContext = function () { - this.state.context.push(types$1.templateQuasi); - this.state.exprAllowed = true; -}; - -types.parenL.updateContext = function (prevType) { - var statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while; - this.state.context.push(statementParens ? types$1.parenStatement : types$1.parenExpression); - this.state.exprAllowed = true; -}; - -types.incDec.updateContext = function () {// tokExprAllowed stays unchanged -}; - -types._function.updateContext = function () { - if (this.curContext() !== types$1.braceStatement) { - this.state.context.push(types$1.functionExpression); - } - - this.state.exprAllowed = false; -}; - -types.backQuote.updateContext = function () { - if (this.curContext() === types$1.template) { - this.state.context.pop(); - } else { - this.state.context.push(types$1.template); - } - - this.state.exprAllowed = false; -}; - -// 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; -}; -var SourceLocation = function SourceLocation(start, end) { - this.start = start; // $FlowIgnore (may start as null, but initialized later) - - this.end = end; -}; // 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); - } - } // istanbul ignore next - - - throw new Error("Unreachable"); -} - -var BaseParser = -/*#__PURE__*/ -function () { - function BaseParser() {} - - var _proto = BaseParser.prototype; - - // Properties set by constructor in index.js - // Initialized by Tokenizer - _proto.isReservedWord = function isReservedWord(word) { - if (word === "await") { - return this.inModule; - } else { - return reservedWords[6](word); - } - }; - - _proto.hasPlugin = function hasPlugin(name) { - return !!this.plugins[name]; - }; - - return BaseParser; -}(); - -/* eslint max-len: 0 */ - -/** - * Based on the comment attachment algorithm used in espree and estraverse. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -function last(stack) { - return stack[stack.length - 1]; -} - -var CommentsParser = -/*#__PURE__*/ -function (_BaseParser) { - _inheritsLoose(CommentsParser, _BaseParser); - - function CommentsParser() { - return _BaseParser.apply(this, arguments) || this; - } - - var _proto = CommentsParser.prototype; - - _proto.addComment = function addComment(comment) { - if (this.filename) comment.loc.filename = this.filename; - this.state.trailingComments.push(comment); - this.state.leadingComments.push(comment); - }; - - _proto.processComment = function processComment(node) { - if (node.type === "Program" && node.body.length > 0) return; - var stack = this.state.commentStack; - var firstChild, lastChild, trailingComments, i, j; - - if (this.state.trailingComments.length > 0) { - // If the first comment in trailingComments comes after the - // current node, then we're good - all comments in the array will - // come after the node and so it's safe to add them as official - // trailingComments. - if (this.state.trailingComments[0].start >= node.end) { - trailingComments = this.state.trailingComments; - this.state.trailingComments = []; - } else { - // Otherwise, if the first comment doesn't come after the - // current node, that means we have a mix of leading and trailing - // comments in the array and that leadingComments contains the - // same items as trailingComments. Reset trailingComments to - // zero items and we'll handle this by evaluating leadingComments - // later. - this.state.trailingComments.length = 0; - } - } else { - if (stack.length > 0) { - var lastInStack = last(stack); - - if (lastInStack.trailingComments && lastInStack.trailingComments[0].start >= node.end) { - trailingComments = lastInStack.trailingComments; - lastInStack.trailingComments = null; - } - } - } // Eating the stack. - - - if (stack.length > 0 && last(stack).start >= node.start) { - firstChild = stack.pop(); - } - - while (stack.length > 0 && last(stack).start >= node.start) { - lastChild = stack.pop(); - } - - if (!lastChild && firstChild) lastChild = firstChild; // Attach comments that follow a trailing comma on the last - // property in an object literal or a trailing comma in function arguments - // as trailing comments - - if (firstChild && this.state.leadingComments.length > 0) { - var lastComment = last(this.state.leadingComments); - - if (firstChild.type === "ObjectProperty") { - if (lastComment.start >= node.start) { - if (this.state.commentPreviousNode) { - for (j = 0; j < this.state.leadingComments.length; j++) { - if (this.state.leadingComments[j].end < this.state.commentPreviousNode.end) { - this.state.leadingComments.splice(j, 1); - j--; - } - } - - if (this.state.leadingComments.length > 0) { - firstChild.trailingComments = this.state.leadingComments; - this.state.leadingComments = []; - } - } - } - } else if (node.type === "CallExpression" && node.arguments && node.arguments.length) { - var lastArg = last(node.arguments); - - if (lastArg && lastComment.start >= lastArg.start && lastComment.end <= node.end) { - if (this.state.commentPreviousNode) { - if (this.state.leadingComments.length > 0) { - lastArg.trailingComments = this.state.leadingComments; - this.state.leadingComments = []; - } - } - } - } - } - - if (lastChild) { - if (lastChild.leadingComments) { - if (lastChild !== node && lastChild.leadingComments.length > 0 && last(lastChild.leadingComments).end <= node.start) { - node.leadingComments = lastChild.leadingComments; - lastChild.leadingComments = null; - } else { - // A leading comment for an anonymous class had been stolen by its first ClassMethod, - // so this takes back the leading comment. - // See also: https://github.com/eslint/espree/issues/158 - for (i = lastChild.leadingComments.length - 2; i >= 0; --i) { - if (lastChild.leadingComments[i].end <= node.start) { - node.leadingComments = lastChild.leadingComments.splice(0, i + 1); - break; - } - } - } - } - } else if (this.state.leadingComments.length > 0) { - if (last(this.state.leadingComments).end <= node.start) { - if (this.state.commentPreviousNode) { - for (j = 0; j < this.state.leadingComments.length; j++) { - if (this.state.leadingComments[j].end < this.state.commentPreviousNode.end) { - this.state.leadingComments.splice(j, 1); - j--; - } - } - } - - if (this.state.leadingComments.length > 0) { - node.leadingComments = this.state.leadingComments; - this.state.leadingComments = []; - } - } else { - // https://github.com/eslint/espree/issues/2 - // - // In special cases, such as return (without a value) and - // debugger, all comments will end up as leadingComments and - // will otherwise be eliminated. This step runs when the - // commentStack is empty and there are comments left - // in leadingComments. - // - // This loop figures out the stopping point between the actual - // leading and trailing comments by finding the location of the - // first comment that comes after the given node. - for (i = 0; i < this.state.leadingComments.length; i++) { - if (this.state.leadingComments[i].end > node.start) { - break; - } - } // Split the array based on the location of the first comment - // that comes after the node. Keep in mind that this could - // result in an empty array, and if so, the array must be - // deleted. - - - var leadingComments = this.state.leadingComments.slice(0, i); - node.leadingComments = leadingComments.length === 0 ? null : leadingComments; // Similarly, trailing comments are attached later. The variable - // must be reset to null if there are no trailing comments. - - trailingComments = this.state.leadingComments.slice(i); - - if (trailingComments.length === 0) { - trailingComments = null; - } - } - } - - this.state.commentPreviousNode = node; - - if (trailingComments) { - if (trailingComments.length && trailingComments[0].start >= node.start && last(trailingComments).end <= node.end) { - node.innerComments = trailingComments; - } else { - node.trailingComments = trailingComments; - } - } - - stack.push(node); - }; - - return CommentsParser; -}(BaseParser); - -// 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. - -var LocationParser = -/*#__PURE__*/ -function (_CommentsParser) { - _inheritsLoose(LocationParser, _CommentsParser); - - function LocationParser() { - return _CommentsParser.apply(this, arguments) || this; - } - - var _proto = LocationParser.prototype; - - _proto.raise = function raise(pos, message, missingPluginNames) { - var loc = getLineInfo(this.input, pos); - message += ` (${loc.line}:${loc.column})`; // $FlowIgnore - - var err = new SyntaxError(message); - err.pos = pos; - err.loc = loc; - - if (missingPluginNames) { - err.missingPlugin = missingPluginNames; - } - - throw err; - }; - - return LocationParser; -}(CommentsParser); - -var State = -/*#__PURE__*/ -function () { - function State() {} - - var _proto = State.prototype; - - _proto.init = function init(options, input) { - this.strict = options.strictMode === false ? false : options.sourceType === "module"; - this.input = input; - this.potentialArrowAt = -1; - this.noArrowAt = []; - this.noArrowParamsConversionAt = []; // eslint-disable-next-line max-len - - this.inMethod = this.inFunction = this.inParameters = this.maybeInArrowParameters = this.inGenerator = this.inAsync = this.inPropertyName = this.inType = this.inClassProperty = this.noAnonFunctionType = false; - this.classLevel = 0; - this.labels = []; - this.decoratorStack = [[]]; - this.yieldInPossibleArrowParameters = null; - this.tokens = []; - this.comments = []; - this.trailingComments = []; - this.leadingComments = []; - this.commentStack = []; // $FlowIgnore - - this.commentPreviousNode = null; - this.pos = this.lineStart = 0; - this.curLine = options.startLine; - this.type = types.eof; - this.value = null; - this.start = this.end = this.pos; - this.startLoc = this.endLoc = this.curPosition(); // $FlowIgnore - - this.lastTokEndLoc = this.lastTokStartLoc = null; - this.lastTokStart = this.lastTokEnd = this.pos; - this.context = [types$1.braceStatement]; - this.exprAllowed = true; - this.containsEsc = this.containsOctal = false; - this.octalPosition = null; - this.invalidTemplateEscapePosition = null; - this.exportedIdentifiers = []; - }; // TODO - - - _proto.curPosition = function curPosition() { - return new Position(this.curLine, this.pos - this.lineStart); - }; - - _proto.clone = function clone(skipArrays) { - var _this = this; - - var state = new State(); - Object.keys(this).forEach(function (key) { - // $FlowIgnore - var val = _this[key]; - - if ((!skipArrays || key === "context") && Array.isArray(val)) { - val = val.slice(); - } // $FlowIgnore - - - state[key] = val; - }); - return state; - }; - - return State; -}(); - -var _isDigit = function isDigit(code) { - return code >= 48 && code <= 57; -}; - -/* eslint max-len: 0 */ -// an immediate sibling of NumericLiteralSeparator _ - -var forbiddenNumericSeparatorSiblings = { - decBinOct: [46, 66, 69, 79, 95, // multiple separators are not allowed - 98, 101, 111], - hex: [46, 88, 95, // multiple separators are not allowed - 120] -}; -var allowedNumericSeparatorSiblings = {}; -allowedNumericSeparatorSiblings.bin = [// 0 - 1 -48, 49]; -allowedNumericSeparatorSiblings.oct = allowedNumericSeparatorSiblings.bin.concat([50, 51, 52, 53, 54, 55]); -allowedNumericSeparatorSiblings.dec = allowedNumericSeparatorSiblings.oct.concat([56, 57]); -allowedNumericSeparatorSiblings.hex = allowedNumericSeparatorSiblings.dec.concat([65, 66, 67, 68, 69, 70, 97, 98, 99, 100, 101, 102]); // 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(state) { - this.type = state.type; - this.value = state.value; - this.start = state.start; - this.end = state.end; - this.loc = new SourceLocation(state.startLoc, state.endLoc); -}; // ## Tokenizer - -function codePointToString(code) { - // UTF-16 Decoding - if (code <= 0xffff) { - return String.fromCharCode(code); - } else { - return String.fromCharCode((code - 0x10000 >> 10) + 0xd800, (code - 0x10000 & 1023) + 0xdc00); - } -} - -var Tokenizer = -/*#__PURE__*/ -function (_LocationParser) { - _inheritsLoose(Tokenizer, _LocationParser); - - // Forward-declarations - // parser/util.js - function Tokenizer(options, input) { - var _this; - - _this = _LocationParser.call(this) || this; - _this.state = new State(); - - _this.state.init(options, input); - - _this.isLookahead = false; - return _this; - } // Move to the next token - - - var _proto = Tokenizer.prototype; - - _proto.next = function next() { - if (this.options.tokens && !this.isLookahead) { - this.state.tokens.push(new Token(this.state)); - } - - this.state.lastTokEnd = this.state.end; - this.state.lastTokStart = this.state.start; - this.state.lastTokEndLoc = this.state.endLoc; - this.state.lastTokStartLoc = this.state.startLoc; - this.nextToken(); - }; // TODO - - - _proto.eat = function eat(type) { - if (this.match(type)) { - this.next(); - return true; - } else { - return false; - } - }; // TODO - - - _proto.match = function match(type) { - return this.state.type === type; - }; // TODO - - - _proto.isKeyword = function isKeyword$$1(word) { - return isKeyword(word); - }; // TODO - - - _proto.lookahead = function lookahead() { - var old = this.state; - this.state = old.clone(true); - this.isLookahead = true; - this.next(); - this.isLookahead = false; - var curr = this.state; - this.state = old; - return curr; - }; // Toggle strict mode. Re-reads the next number or string to please - // pedantic tests (`"use strict"; 010;` should fail). - - - _proto.setStrict = function setStrict(strict) { - this.state.strict = strict; - if (!this.match(types.num) && !this.match(types.string)) return; - this.state.pos = this.state.start; - - while (this.state.pos < this.state.lineStart) { - this.state.lineStart = this.input.lastIndexOf("\n", this.state.lineStart - 2) + 1; - --this.state.curLine; - } - - this.nextToken(); - }; - - _proto.curContext = function curContext() { - return this.state.context[this.state.context.length - 1]; - }; // Read a single token, updating the parser object's token-related - // properties. - - - _proto.nextToken = function nextToken() { - var curContext = this.curContext(); - if (!curContext || !curContext.preserveSpace) this.skipSpace(); - this.state.containsOctal = false; - this.state.octalPosition = null; - this.state.start = this.state.pos; - this.state.startLoc = this.state.curPosition(); - - if (this.state.pos >= this.input.length) { - this.finishToken(types.eof); - return; - } - - if (curContext.override) { - curContext.override(this); - } else { - this.readToken(this.fullCharCodeAtPos()); - } - }; - - _proto.readToken = function readToken(code) { - // Identifier or keyword. '\uXXXX' sequences are allowed in - // identifiers, so '\' also dispatches to that. - if (isIdentifierStart(code) || code === 92) { - this.readWord(); - } else { - this.getTokenFromCode(code); - } - }; - - _proto.fullCharCodeAtPos = function fullCharCodeAtPos() { - var code = this.input.charCodeAt(this.state.pos); - if (code <= 0xd7ff || code >= 0xe000) return code; - var next = this.input.charCodeAt(this.state.pos + 1); - return (code << 10) + next - 0x35fdc00; - }; - - _proto.pushComment = function pushComment(block, text, start, end, startLoc, endLoc) { - var comment = { - type: block ? "CommentBlock" : "CommentLine", - value: text, - start: start, - end: end, - loc: new SourceLocation(startLoc, endLoc) - }; - - if (!this.isLookahead) { - if (this.options.tokens) this.state.tokens.push(comment); - this.state.comments.push(comment); - this.addComment(comment); - } - }; - - _proto.skipBlockComment = function skipBlockComment() { - var startLoc = this.state.curPosition(); - var start = this.state.pos; - var end = this.input.indexOf("*/", this.state.pos += 2); - if (end === -1) this.raise(this.state.pos - 2, "Unterminated comment"); - this.state.pos = end + 2; - lineBreakG.lastIndex = start; - var match; - - while ((match = lineBreakG.exec(this.input)) && match.index < this.state.pos) { - ++this.state.curLine; - this.state.lineStart = match.index + match[0].length; - } - - this.pushComment(true, this.input.slice(start + 2, end), start, this.state.pos, startLoc, this.state.curPosition()); - }; - - _proto.skipLineComment = function skipLineComment(startSkip) { - var start = this.state.pos; - var startLoc = this.state.curPosition(); - var ch = this.input.charCodeAt(this.state.pos += startSkip); - - if (this.state.pos < this.input.length) { - while (ch !== 10 && ch !== 13 && ch !== 8232 && ch !== 8233 && ++this.state.pos < this.input.length) { - ch = this.input.charCodeAt(this.state.pos); - } - } - - this.pushComment(false, this.input.slice(start + startSkip, this.state.pos), start, this.state.pos, startLoc, this.state.curPosition()); - }; // Called at the start of the parse and after every token. Skips - // whitespace and comments, and. - - - _proto.skipSpace = function skipSpace() { - loop: while (this.state.pos < this.input.length) { - var ch = this.input.charCodeAt(this.state.pos); - - switch (ch) { - case 32: - case 160: - ++this.state.pos; - break; - - case 13: - if (this.input.charCodeAt(this.state.pos + 1) === 10) { - ++this.state.pos; - } - - case 10: - case 8232: - case 8233: - ++this.state.pos; - ++this.state.curLine; - this.state.lineStart = this.state.pos; - break; - - case 47: - switch (this.input.charCodeAt(this.state.pos + 1)) { - case 42: - this.skipBlockComment(); - break; - - case 47: - this.skipLineComment(2); - break; - - default: - break loop; - } - - break; - - default: - if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) { - ++this.state.pos; - } else { - 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. - - - _proto.finishToken = function finishToken(type, val) { - this.state.end = this.state.pos; - this.state.endLoc = this.state.curPosition(); - var prevType = this.state.type; - this.state.type = type; - this.state.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. - // - - - _proto.readToken_dot = function readToken_dot() { - var next = this.input.charCodeAt(this.state.pos + 1); - - if (next >= 48 && next <= 57) { - this.readNumber(true); - return; - } - - var next2 = this.input.charCodeAt(this.state.pos + 2); - - if (next === 46 && next2 === 46) { - this.state.pos += 3; - this.finishToken(types.ellipsis); - } else { - ++this.state.pos; - this.finishToken(types.dot); - } - }; - - _proto.readToken_slash = function readToken_slash() { - // '/' - if (this.state.exprAllowed) { - ++this.state.pos; - this.readRegexp(); - return; - } - - var next = this.input.charCodeAt(this.state.pos + 1); - - if (next === 61) { - this.finishOp(types.assign, 2); - } else { - this.finishOp(types.slash, 1); - } - }; - - _proto.readToken_mult_modulo = function readToken_mult_modulo(code) { - // '%*' - var type = code === 42 ? types.star : types.modulo; - var width = 1; - var next = this.input.charCodeAt(this.state.pos + 1); - var exprAllowed = this.state.exprAllowed; // Exponentiation operator ** - - if (code === 42 && next === 42) { - width++; - next = this.input.charCodeAt(this.state.pos + 2); - type = types.exponent; - } - - if (next === 61 && !exprAllowed) { - width++; - type = types.assign; - } - - this.finishOp(type, width); - }; - - _proto.readToken_pipe_amp = function readToken_pipe_amp(code) { - // '|&' - var next = this.input.charCodeAt(this.state.pos + 1); - - if (next === code) { - this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2); - return; - } - - if (code === 124) { - // '|>' - if (next === 62) { - this.finishOp(types.pipeline, 2); - return; - } else if (next === 125 && this.hasPlugin("flow")) { - // '|}' - this.finishOp(types.braceBarR, 2); - return; - } - } - - if (next === 61) { - this.finishOp(types.assign, 2); - return; - } - - this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1); - }; - - _proto.readToken_caret = function readToken_caret() { - // '^' - var next = this.input.charCodeAt(this.state.pos + 1); - - if (next === 61) { - this.finishOp(types.assign, 2); - } else { - this.finishOp(types.bitwiseXOR, 1); - } - }; - - _proto.readToken_plus_min = function readToken_plus_min(code) { - // '+-' - var next = this.input.charCodeAt(this.state.pos + 1); - - if (next === code) { - if (next === 45 && !this.inModule && this.input.charCodeAt(this.state.pos + 2) === 62 && lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.pos))) { - // A `-->` line comment - this.skipLineComment(3); - this.skipSpace(); - this.nextToken(); - return; - } - - this.finishOp(types.incDec, 2); - return; - } - - if (next === 61) { - this.finishOp(types.assign, 2); - } else { - this.finishOp(types.plusMin, 1); - } - }; - - _proto.readToken_lt_gt = function readToken_lt_gt(code) { - // '<>' - var next = this.input.charCodeAt(this.state.pos + 1); - var size = 1; - - if (next === code) { - size = code === 62 && this.input.charCodeAt(this.state.pos + 2) === 62 ? 3 : 2; - - if (this.input.charCodeAt(this.state.pos + size) === 61) { - this.finishOp(types.assign, size + 1); - return; - } - - this.finishOp(types.bitShift, size); - return; - } - - if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.state.pos + 2) === 45 && this.input.charCodeAt(this.state.pos + 3) === 45) { - // ` - -
- -
-Nicholas C. Zakas -
-
- -
-Kevin Partington -
-
- -
-Ilya Volodin -
-
- -
-Brandon Mills -
-
- -
-Toru Nagashima -
-
- -
-Gyandeep Singh -
-
- -
-Kai Cataldo -
-
- -
-Teddy Katz -
-
- -### Committers - -The people who review and fix bugs and help triage issues. - - - -
- -
-薛定谔的猫 -
-
- -
-Pig Fang -
-
- -## Sponsors - -The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://opencollective.com/eslint) to get your logo on our README and website. - - - -

Gold Sponsors

-

Facebook Open Source Airbnb

Silver Sponsors

-

AMP Project

Bronze Sponsors

-

Faithlife

- - -## Technology Sponsors - -* Site search ([eslint.org](https://eslint.org)) is sponsored by [Algolia](https://www.algolia.com) - - -[npm-image]: https://img.shields.io/npm/v/eslint.svg?style=flat-square -[npm-url]: https://www.npmjs.com/package/eslint -[travis-image]: https://img.shields.io/travis/eslint/eslint/master.svg?style=flat-square -[travis-url]: https://travis-ci.org/eslint/eslint -[appveyor-image]: https://ci.appveyor.com/api/projects/status/iwxmiobcvbw3b0av/branch/master?svg=true -[appveyor-url]: https://ci.appveyor.com/project/nzakas/eslint/branch/master -[coveralls-image]: https://img.shields.io/coveralls/eslint/eslint/master.svg?style=flat-square -[coveralls-url]: https://coveralls.io/r/eslint/eslint?branch=master -[downloads-image]: https://img.shields.io/npm/dm/eslint.svg?style=flat-square -[downloads-url]: https://www.npmjs.com/package/eslint diff --git a/tools/node_modules/eslint/bin/eslint.js b/tools/node_modules/eslint/bin/eslint.js deleted file mode 100755 index e51121ec6afe7f..00000000000000 --- a/tools/node_modules/eslint/bin/eslint.js +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/env node - -/** - * @fileoverview Main CLI that is run via the eslint command. - * @author Nicholas C. Zakas - */ - -/* eslint no-console:off */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const useStdIn = (process.argv.indexOf("--stdin") > -1), - init = (process.argv.indexOf("--init") > -1), - debug = (process.argv.indexOf("--debug") > -1); - -// must do this initialization *before* other requires in order to work -if (debug) { - require("debug").enable("eslint:*,-eslint:code-path"); -} - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -// now we can safely include the other modules that use debug -const cli = require("../lib/cli"), - path = require("path"), - fs = require("fs"); - -//------------------------------------------------------------------------------ -// Execution -//------------------------------------------------------------------------------ - -process.once("uncaughtException", err => { - - // lazy load - const lodash = require("lodash"); - - if (typeof err.messageTemplate === "string" && err.messageTemplate.length > 0) { - const template = lodash.template(fs.readFileSync(path.resolve(__dirname, `../messages/${err.messageTemplate}.txt`), "utf-8")); - const pkg = require("../package.json"); - - console.error("\nOops! Something went wrong! :("); - console.error(`\nESLint: ${pkg.version}.\n${template(err.messageData || {})}`); - } else { - - console.error(err.stack); - } - - process.exitCode = 2; -}); - -if (useStdIn) { - - /* - * Note: `process.stdin.fd` is not used here due to https://github.com/nodejs/node/issues/7439. - * Accessing the `process.stdin` property seems to modify the behavior of file descriptor 0, resulting - * in an error when stdin is piped in asynchronously. - */ - const STDIN_FILE_DESCRIPTOR = 0; - - process.exitCode = cli.execute(process.argv, fs.readFileSync(STDIN_FILE_DESCRIPTOR, "utf8")); -} else if (init) { - const configInit = require("../lib/config/config-initializer"); - - configInit.initializeConfig().then(() => { - process.exitCode = 0; - }).catch(err => { - process.exitCode = 1; - console.error(err.message); - console.error(err.stack); - }); -} else { - process.exitCode = cli.execute(process.argv); -} diff --git a/tools/node_modules/eslint/conf/category-list.json b/tools/node_modules/eslint/conf/category-list.json deleted file mode 100644 index 5427667b09e332..00000000000000 --- a/tools/node_modules/eslint/conf/category-list.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "categories": [ - { "name": "Possible Errors", "description": "These rules relate to possible syntax or logic errors in JavaScript code:" }, - { "name": "Best Practices", "description": "These rules relate to better ways of doing things to help you avoid problems:" }, - { "name": "Strict Mode", "description": "These rules relate to strict mode directives:" }, - { "name": "Variables", "description": "These rules relate to variable declarations:" }, - { "name": "Node.js and CommonJS", "description": "These rules relate to code running in Node.js, or in browsers with CommonJS:" }, - { "name": "Stylistic Issues", "description": "These rules relate to style guidelines, and are therefore quite subjective:" }, - { "name": "ECMAScript 6", "description": "These rules relate to ES6, also known as ES2015:" } - ], - "deprecated": { - "name": "Deprecated", - "description": "These rules have been deprecated in accordance with the [deprecation policy](/docs/user-guide/rule-deprecation), and replaced by newer rules:", - "rules": [] - }, - "removed": { - "name": "Removed", - "description": "These rules from older versions of ESLint (before the [deprecation policy](/docs/user-guide/rule-deprecation) existed) have been replaced by newer rules:", - "rules": [ - { "removed": "generator-star", "replacedBy": ["generator-star-spacing"] }, - { "removed": "global-strict", "replacedBy": ["strict"] }, - { "removed": "no-arrow-condition", "replacedBy": ["no-confusing-arrow", "no-constant-condition"] }, - { "removed": "no-comma-dangle", "replacedBy": ["comma-dangle"] }, - { "removed": "no-empty-class", "replacedBy": ["no-empty-character-class"] }, - { "removed": "no-empty-label", "replacedBy": ["no-labels"] }, - { "removed": "no-extra-strict", "replacedBy": ["strict"] }, - { "removed": "no-reserved-keys", "replacedBy": ["quote-props"] }, - { "removed": "no-space-before-semi", "replacedBy": ["semi-spacing"] }, - { "removed": "no-wrap-func", "replacedBy": ["no-extra-parens"] }, - { "removed": "space-after-function-name", "replacedBy": ["space-before-function-paren"] }, - { "removed": "space-after-keywords", "replacedBy": ["keyword-spacing"] }, - { "removed": "space-before-function-parentheses", "replacedBy": ["space-before-function-paren"] }, - { "removed": "space-before-keywords", "replacedBy": ["keyword-spacing"] }, - { "removed": "space-in-brackets", "replacedBy": ["object-curly-spacing", "array-bracket-spacing"] }, - { "removed": "space-return-throw-case", "replacedBy": ["keyword-spacing"] }, - { "removed": "space-unary-word-ops", "replacedBy": ["space-unary-ops"] }, - { "removed": "spaced-line-comment", "replacedBy": ["spaced-comment"] } - ] - } -} diff --git a/tools/node_modules/eslint/conf/config-schema.js b/tools/node_modules/eslint/conf/config-schema.js deleted file mode 100644 index 626e1d54c520cc..00000000000000 --- a/tools/node_modules/eslint/conf/config-schema.js +++ /dev/null @@ -1,70 +0,0 @@ -/** - * @fileoverview Defines a schema for configs. - * @author Sylvan Mably - */ - -"use strict"; - -const baseConfigProperties = { - env: { type: "object" }, - globals: { type: "object" }, - parser: { type: ["string", "null"] }, - parserOptions: { type: "object" }, - plugins: { type: "array" }, - rules: { type: "object" }, - settings: { type: "object" }, - - ecmaFeatures: { type: "object" } // deprecated; logs a warning when used -}; - -const overrideProperties = Object.assign( - {}, - baseConfigProperties, - { - files: { - oneOf: [ - { type: "string" }, - { - type: "array", - items: { type: "string" }, - minItems: 1 - } - ] - }, - excludedFiles: { - oneOf: [ - { type: "string" }, - { - type: "array", - items: { type: "string" } - } - ] - } - } -); - -const topLevelConfigProperties = Object.assign( - {}, - baseConfigProperties, - { - extends: { type: ["string", "array"] }, - root: { type: "boolean" }, - overrides: { - type: "array", - items: { - type: "object", - properties: overrideProperties, - required: ["files"], - additionalProperties: false - } - } - } -); - -const configSchema = { - type: "object", - properties: topLevelConfigProperties, - additionalProperties: false -}; - -module.exports = configSchema; diff --git a/tools/node_modules/eslint/conf/default-cli-options.js b/tools/node_modules/eslint/conf/default-cli-options.js deleted file mode 100644 index 9670a14b00c304..00000000000000 --- a/tools/node_modules/eslint/conf/default-cli-options.js +++ /dev/null @@ -1,31 +0,0 @@ -/** - * @fileoverview Default CLIEngineOptions. - * @author Ian VanSchooten - */ - -"use strict"; - -module.exports = { - configFile: null, - baseConfig: false, - rulePaths: [], - useEslintrc: true, - envs: [], - globals: [], - extensions: [".js"], - ignore: true, - ignorePath: null, - cache: false, - - /* - * in order to honor the cacheFile option if specified - * this option should not have a default value otherwise - * it will always be used - */ - cacheLocation: "", - cacheFile: ".eslintcache", - fix: false, - allowInlineConfig: true, - reportUnusedDisableDirectives: false, - globInputPaths: true -}; diff --git a/tools/node_modules/eslint/conf/environments.js b/tools/node_modules/eslint/conf/environments.js deleted file mode 100644 index 1c2b12eed31bb5..00000000000000 --- a/tools/node_modules/eslint/conf/environments.js +++ /dev/null @@ -1,109 +0,0 @@ -/** - * @fileoverview Defines environment settings and globals. - * @author Elan Shanker - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const globals = require("globals"); - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = { - builtin: { - globals: globals.es5 - }, - browser: { - globals: globals.browser - }, - node: { - globals: globals.node, - parserOptions: { - ecmaFeatures: { - globalReturn: true - } - } - }, - commonjs: { - globals: globals.commonjs, - parserOptions: { - ecmaFeatures: { - globalReturn: true - } - } - }, - "shared-node-browser": { - globals: globals["shared-node-browser"] - }, - worker: { - globals: globals.worker - }, - amd: { - globals: globals.amd - }, - mocha: { - globals: globals.mocha - }, - jasmine: { - globals: globals.jasmine - }, - jest: { - globals: globals.jest - }, - phantomjs: { - globals: globals.phantomjs - }, - jquery: { - globals: globals.jquery - }, - qunit: { - globals: globals.qunit - }, - prototypejs: { - globals: globals.prototypejs - }, - shelljs: { - globals: globals.shelljs - }, - meteor: { - globals: globals.meteor - }, - mongo: { - globals: globals.mongo - }, - protractor: { - globals: globals.protractor - }, - applescript: { - globals: globals.applescript - }, - nashorn: { - globals: globals.nashorn - }, - serviceworker: { - globals: globals.serviceworker - }, - atomtest: { - globals: globals.atomtest - }, - embertest: { - globals: globals.embertest - }, - webextensions: { - globals: globals.webextensions - }, - es6: { - globals: globals.es2015, - parserOptions: { - ecmaVersion: 6 - } - }, - greasemonkey: { - globals: globals.greasemonkey - } -}; diff --git a/tools/node_modules/eslint/conf/eslint-all.js b/tools/node_modules/eslint/conf/eslint-all.js deleted file mode 100644 index 3850fcea3abb1c..00000000000000 --- a/tools/node_modules/eslint/conf/eslint-all.js +++ /dev/null @@ -1,29 +0,0 @@ -/** - * @fileoverview Config to enable all rules. - * @author Robert Fletcher - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const builtInRules = require("../lib/built-in-rules-index"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const enabledRules = Object.keys(builtInRules).reduce((result, ruleId) => { - if (!builtInRules[ruleId].meta.deprecated) { - result[ruleId] = "error"; - } - return result; -}, {}); - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = { rules: enabledRules }; diff --git a/tools/node_modules/eslint/conf/eslint-recommended.js b/tools/node_modules/eslint/conf/eslint-recommended.js deleted file mode 100644 index 447a99638a4423..00000000000000 --- a/tools/node_modules/eslint/conf/eslint-recommended.js +++ /dev/null @@ -1,15 +0,0 @@ -/** - * @fileoverview Configuration applied when a user configuration extends from - * eslint:recommended. - * @author Nicholas C. Zakas - */ - -"use strict"; - -const builtInRules = require("../lib/built-in-rules-index"); - -module.exports = { - rules: Object.assign({}, ...Object.keys(builtInRules).map(ruleId => ({ - [ruleId]: builtInRules[ruleId].meta.docs.recommended ? "error" : "off" - }))) -}; diff --git a/tools/node_modules/eslint/conf/replacements.json b/tools/node_modules/eslint/conf/replacements.json deleted file mode 100644 index c047811e602d41..00000000000000 --- a/tools/node_modules/eslint/conf/replacements.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "rules": { - "generator-star": ["generator-star-spacing"], - "global-strict": ["strict"], - "no-arrow-condition": ["no-confusing-arrow", "no-constant-condition"], - "no-comma-dangle": ["comma-dangle"], - "no-empty-class": ["no-empty-character-class"], - "no-empty-label": ["no-labels"], - "no-extra-strict": ["strict"], - "no-reserved-keys": ["quote-props"], - "no-space-before-semi": ["semi-spacing"], - "no-wrap-func": ["no-extra-parens"], - "space-after-function-name": ["space-before-function-paren"], - "space-after-keywords": ["keyword-spacing"], - "space-before-function-parentheses": ["space-before-function-paren"], - "space-before-keywords": ["keyword-spacing"], - "space-in-brackets": ["object-curly-spacing", "array-bracket-spacing", "computed-property-spacing"], - "space-return-throw-case": ["keyword-spacing"], - "space-unary-word-ops": ["space-unary-ops"], - "spaced-line-comment": ["spaced-comment"] - } -} diff --git a/tools/node_modules/eslint/lib/api.js b/tools/node_modules/eslint/lib/api.js deleted file mode 100644 index 91dae3c7cbb42b..00000000000000 --- a/tools/node_modules/eslint/lib/api.js +++ /dev/null @@ -1,28 +0,0 @@ -/** - * @fileoverview Expose out ESLint and CLI to require. - * @author Ian Christian Myers - */ - -"use strict"; - -const Linter = require("./linter"); - -module.exports = { - Linter, - CLIEngine: require("./cli-engine"), - RuleTester: require("./testers/rule-tester"), - SourceCode: require("./util/source-code") -}; - -let deprecatedLinterInstance = null; - -Object.defineProperty(module.exports, "linter", { - enumerable: false, - get() { - if (!deprecatedLinterInstance) { - deprecatedLinterInstance = new Linter(); - } - - return deprecatedLinterInstance; - } -}); diff --git a/tools/node_modules/eslint/lib/built-in-rules-index.js b/tools/node_modules/eslint/lib/built-in-rules-index.js deleted file mode 100644 index aaf2f06eccdd41..00000000000000 --- a/tools/node_modules/eslint/lib/built-in-rules-index.js +++ /dev/null @@ -1,277 +0,0 @@ -/** - * @fileoverview Collects the built-in rules into a map structure so that they can be imported all at once and without - * using the file-system directly. - * @author Peter (Somogyvari) Metz - */ - -"use strict"; - -/* eslint sort-keys: ["error", "asc"] */ - -module.exports = { - "accessor-pairs": require("./rules/accessor-pairs"), - "array-bracket-newline": require("./rules/array-bracket-newline"), - "array-bracket-spacing": require("./rules/array-bracket-spacing"), - "array-callback-return": require("./rules/array-callback-return"), - "array-element-newline": require("./rules/array-element-newline"), - "arrow-body-style": require("./rules/arrow-body-style"), - "arrow-parens": require("./rules/arrow-parens"), - "arrow-spacing": require("./rules/arrow-spacing"), - "block-scoped-var": require("./rules/block-scoped-var"), - "block-spacing": require("./rules/block-spacing"), - "brace-style": require("./rules/brace-style"), - "callback-return": require("./rules/callback-return"), - camelcase: require("./rules/camelcase"), - "capitalized-comments": require("./rules/capitalized-comments"), - "class-methods-use-this": require("./rules/class-methods-use-this"), - "comma-dangle": require("./rules/comma-dangle"), - "comma-spacing": require("./rules/comma-spacing"), - "comma-style": require("./rules/comma-style"), - complexity: require("./rules/complexity"), - "computed-property-spacing": require("./rules/computed-property-spacing"), - "consistent-return": require("./rules/consistent-return"), - "consistent-this": require("./rules/consistent-this"), - "constructor-super": require("./rules/constructor-super"), - curly: require("./rules/curly"), - "default-case": require("./rules/default-case"), - "dot-location": require("./rules/dot-location"), - "dot-notation": require("./rules/dot-notation"), - "eol-last": require("./rules/eol-last"), - eqeqeq: require("./rules/eqeqeq"), - "for-direction": require("./rules/for-direction"), - "func-call-spacing": require("./rules/func-call-spacing"), - "func-name-matching": require("./rules/func-name-matching"), - "func-names": require("./rules/func-names"), - "func-style": require("./rules/func-style"), - "function-paren-newline": require("./rules/function-paren-newline"), - "generator-star-spacing": require("./rules/generator-star-spacing"), - "getter-return": require("./rules/getter-return"), - "global-require": require("./rules/global-require"), - "guard-for-in": require("./rules/guard-for-in"), - "handle-callback-err": require("./rules/handle-callback-err"), - "id-blacklist": require("./rules/id-blacklist"), - "id-length": require("./rules/id-length"), - "id-match": require("./rules/id-match"), - "implicit-arrow-linebreak": require("./rules/implicit-arrow-linebreak"), - indent: require("./rules/indent"), - "indent-legacy": require("./rules/indent-legacy"), - "init-declarations": require("./rules/init-declarations"), - "jsx-quotes": require("./rules/jsx-quotes"), - "key-spacing": require("./rules/key-spacing"), - "keyword-spacing": require("./rules/keyword-spacing"), - "line-comment-position": require("./rules/line-comment-position"), - "linebreak-style": require("./rules/linebreak-style"), - "lines-around-comment": require("./rules/lines-around-comment"), - "lines-around-directive": require("./rules/lines-around-directive"), - "lines-between-class-members": require("./rules/lines-between-class-members"), - "max-classes-per-file": require("./rules/max-classes-per-file"), - "max-depth": require("./rules/max-depth"), - "max-len": require("./rules/max-len"), - "max-lines": require("./rules/max-lines"), - "max-lines-per-function": require("./rules/max-lines-per-function"), - "max-nested-callbacks": require("./rules/max-nested-callbacks"), - "max-params": require("./rules/max-params"), - "max-statements": require("./rules/max-statements"), - "max-statements-per-line": require("./rules/max-statements-per-line"), - "multiline-comment-style": require("./rules/multiline-comment-style"), - "multiline-ternary": require("./rules/multiline-ternary"), - "new-cap": require("./rules/new-cap"), - "new-parens": require("./rules/new-parens"), - "newline-after-var": require("./rules/newline-after-var"), - "newline-before-return": require("./rules/newline-before-return"), - "newline-per-chained-call": require("./rules/newline-per-chained-call"), - "no-alert": require("./rules/no-alert"), - "no-array-constructor": require("./rules/no-array-constructor"), - "no-async-promise-executor": require("./rules/no-async-promise-executor"), - "no-await-in-loop": require("./rules/no-await-in-loop"), - "no-bitwise": require("./rules/no-bitwise"), - "no-buffer-constructor": require("./rules/no-buffer-constructor"), - "no-caller": require("./rules/no-caller"), - "no-case-declarations": require("./rules/no-case-declarations"), - "no-catch-shadow": require("./rules/no-catch-shadow"), - "no-class-assign": require("./rules/no-class-assign"), - "no-compare-neg-zero": require("./rules/no-compare-neg-zero"), - "no-cond-assign": require("./rules/no-cond-assign"), - "no-confusing-arrow": require("./rules/no-confusing-arrow"), - "no-console": require("./rules/no-console"), - "no-const-assign": require("./rules/no-const-assign"), - "no-constant-condition": require("./rules/no-constant-condition"), - "no-continue": require("./rules/no-continue"), - "no-control-regex": require("./rules/no-control-regex"), - "no-debugger": require("./rules/no-debugger"), - "no-delete-var": require("./rules/no-delete-var"), - "no-div-regex": require("./rules/no-div-regex"), - "no-dupe-args": require("./rules/no-dupe-args"), - "no-dupe-class-members": require("./rules/no-dupe-class-members"), - "no-dupe-keys": require("./rules/no-dupe-keys"), - "no-duplicate-case": require("./rules/no-duplicate-case"), - "no-duplicate-imports": require("./rules/no-duplicate-imports"), - "no-else-return": require("./rules/no-else-return"), - "no-empty": require("./rules/no-empty"), - "no-empty-character-class": require("./rules/no-empty-character-class"), - "no-empty-function": require("./rules/no-empty-function"), - "no-empty-pattern": require("./rules/no-empty-pattern"), - "no-eq-null": require("./rules/no-eq-null"), - "no-eval": require("./rules/no-eval"), - "no-ex-assign": require("./rules/no-ex-assign"), - "no-extend-native": require("./rules/no-extend-native"), - "no-extra-bind": require("./rules/no-extra-bind"), - "no-extra-boolean-cast": require("./rules/no-extra-boolean-cast"), - "no-extra-label": require("./rules/no-extra-label"), - "no-extra-parens": require("./rules/no-extra-parens"), - "no-extra-semi": require("./rules/no-extra-semi"), - "no-fallthrough": require("./rules/no-fallthrough"), - "no-floating-decimal": require("./rules/no-floating-decimal"), - "no-func-assign": require("./rules/no-func-assign"), - "no-global-assign": require("./rules/no-global-assign"), - "no-implicit-coercion": require("./rules/no-implicit-coercion"), - "no-implicit-globals": require("./rules/no-implicit-globals"), - "no-implied-eval": require("./rules/no-implied-eval"), - "no-inline-comments": require("./rules/no-inline-comments"), - "no-inner-declarations": require("./rules/no-inner-declarations"), - "no-invalid-regexp": require("./rules/no-invalid-regexp"), - "no-invalid-this": require("./rules/no-invalid-this"), - "no-irregular-whitespace": require("./rules/no-irregular-whitespace"), - "no-iterator": require("./rules/no-iterator"), - "no-label-var": require("./rules/no-label-var"), - "no-labels": require("./rules/no-labels"), - "no-lone-blocks": require("./rules/no-lone-blocks"), - "no-lonely-if": require("./rules/no-lonely-if"), - "no-loop-func": require("./rules/no-loop-func"), - "no-magic-numbers": require("./rules/no-magic-numbers"), - "no-misleading-character-class": require("./rules/no-misleading-character-class"), - "no-mixed-operators": require("./rules/no-mixed-operators"), - "no-mixed-requires": require("./rules/no-mixed-requires"), - "no-mixed-spaces-and-tabs": require("./rules/no-mixed-spaces-and-tabs"), - "no-multi-assign": require("./rules/no-multi-assign"), - "no-multi-spaces": require("./rules/no-multi-spaces"), - "no-multi-str": require("./rules/no-multi-str"), - "no-multiple-empty-lines": require("./rules/no-multiple-empty-lines"), - "no-native-reassign": require("./rules/no-native-reassign"), - "no-negated-condition": require("./rules/no-negated-condition"), - "no-negated-in-lhs": require("./rules/no-negated-in-lhs"), - "no-nested-ternary": require("./rules/no-nested-ternary"), - "no-new": require("./rules/no-new"), - "no-new-func": require("./rules/no-new-func"), - "no-new-object": require("./rules/no-new-object"), - "no-new-require": require("./rules/no-new-require"), - "no-new-symbol": require("./rules/no-new-symbol"), - "no-new-wrappers": require("./rules/no-new-wrappers"), - "no-obj-calls": require("./rules/no-obj-calls"), - "no-octal": require("./rules/no-octal"), - "no-octal-escape": require("./rules/no-octal-escape"), - "no-param-reassign": require("./rules/no-param-reassign"), - "no-path-concat": require("./rules/no-path-concat"), - "no-plusplus": require("./rules/no-plusplus"), - "no-process-env": require("./rules/no-process-env"), - "no-process-exit": require("./rules/no-process-exit"), - "no-proto": require("./rules/no-proto"), - "no-prototype-builtins": require("./rules/no-prototype-builtins"), - "no-redeclare": require("./rules/no-redeclare"), - "no-regex-spaces": require("./rules/no-regex-spaces"), - "no-restricted-globals": require("./rules/no-restricted-globals"), - "no-restricted-imports": require("./rules/no-restricted-imports"), - "no-restricted-modules": require("./rules/no-restricted-modules"), - "no-restricted-properties": require("./rules/no-restricted-properties"), - "no-restricted-syntax": require("./rules/no-restricted-syntax"), - "no-return-assign": require("./rules/no-return-assign"), - "no-return-await": require("./rules/no-return-await"), - "no-script-url": require("./rules/no-script-url"), - "no-self-assign": require("./rules/no-self-assign"), - "no-self-compare": require("./rules/no-self-compare"), - "no-sequences": require("./rules/no-sequences"), - "no-shadow": require("./rules/no-shadow"), - "no-shadow-restricted-names": require("./rules/no-shadow-restricted-names"), - "no-spaced-func": require("./rules/no-spaced-func"), - "no-sparse-arrays": require("./rules/no-sparse-arrays"), - "no-sync": require("./rules/no-sync"), - "no-tabs": require("./rules/no-tabs"), - "no-template-curly-in-string": require("./rules/no-template-curly-in-string"), - "no-ternary": require("./rules/no-ternary"), - "no-this-before-super": require("./rules/no-this-before-super"), - "no-throw-literal": require("./rules/no-throw-literal"), - "no-trailing-spaces": require("./rules/no-trailing-spaces"), - "no-undef": require("./rules/no-undef"), - "no-undef-init": require("./rules/no-undef-init"), - "no-undefined": require("./rules/no-undefined"), - "no-underscore-dangle": require("./rules/no-underscore-dangle"), - "no-unexpected-multiline": require("./rules/no-unexpected-multiline"), - "no-unmodified-loop-condition": require("./rules/no-unmodified-loop-condition"), - "no-unneeded-ternary": require("./rules/no-unneeded-ternary"), - "no-unreachable": require("./rules/no-unreachable"), - "no-unsafe-finally": require("./rules/no-unsafe-finally"), - "no-unsafe-negation": require("./rules/no-unsafe-negation"), - "no-unused-expressions": require("./rules/no-unused-expressions"), - "no-unused-labels": require("./rules/no-unused-labels"), - "no-unused-vars": require("./rules/no-unused-vars"), - "no-use-before-define": require("./rules/no-use-before-define"), - "no-useless-call": require("./rules/no-useless-call"), - "no-useless-catch": require("./rules/no-useless-catch"), - "no-useless-computed-key": require("./rules/no-useless-computed-key"), - "no-useless-concat": require("./rules/no-useless-concat"), - "no-useless-constructor": require("./rules/no-useless-constructor"), - "no-useless-escape": require("./rules/no-useless-escape"), - "no-useless-rename": require("./rules/no-useless-rename"), - "no-useless-return": require("./rules/no-useless-return"), - "no-var": require("./rules/no-var"), - "no-void": require("./rules/no-void"), - "no-warning-comments": require("./rules/no-warning-comments"), - "no-whitespace-before-property": require("./rules/no-whitespace-before-property"), - "no-with": require("./rules/no-with"), - "nonblock-statement-body-position": require("./rules/nonblock-statement-body-position"), - "object-curly-newline": require("./rules/object-curly-newline"), - "object-curly-spacing": require("./rules/object-curly-spacing"), - "object-property-newline": require("./rules/object-property-newline"), - "object-shorthand": require("./rules/object-shorthand"), - "one-var": require("./rules/one-var"), - "one-var-declaration-per-line": require("./rules/one-var-declaration-per-line"), - "operator-assignment": require("./rules/operator-assignment"), - "operator-linebreak": require("./rules/operator-linebreak"), - "padded-blocks": require("./rules/padded-blocks"), - "padding-line-between-statements": require("./rules/padding-line-between-statements"), - "prefer-arrow-callback": require("./rules/prefer-arrow-callback"), - "prefer-const": require("./rules/prefer-const"), - "prefer-destructuring": require("./rules/prefer-destructuring"), - "prefer-numeric-literals": require("./rules/prefer-numeric-literals"), - "prefer-object-spread": require("./rules/prefer-object-spread"), - "prefer-promise-reject-errors": require("./rules/prefer-promise-reject-errors"), - "prefer-reflect": require("./rules/prefer-reflect"), - "prefer-rest-params": require("./rules/prefer-rest-params"), - "prefer-spread": require("./rules/prefer-spread"), - "prefer-template": require("./rules/prefer-template"), - "quote-props": require("./rules/quote-props"), - quotes: require("./rules/quotes"), - radix: require("./rules/radix"), - "require-atomic-updates": require("./rules/require-atomic-updates"), - "require-await": require("./rules/require-await"), - "require-jsdoc": require("./rules/require-jsdoc"), - "require-unicode-regexp": require("./rules/require-unicode-regexp"), - "require-yield": require("./rules/require-yield"), - "rest-spread-spacing": require("./rules/rest-spread-spacing"), - semi: require("./rules/semi"), - "semi-spacing": require("./rules/semi-spacing"), - "semi-style": require("./rules/semi-style"), - "sort-imports": require("./rules/sort-imports"), - "sort-keys": require("./rules/sort-keys"), - "sort-vars": require("./rules/sort-vars"), - "space-before-blocks": require("./rules/space-before-blocks"), - "space-before-function-paren": require("./rules/space-before-function-paren"), - "space-in-parens": require("./rules/space-in-parens"), - "space-infix-ops": require("./rules/space-infix-ops"), - "space-unary-ops": require("./rules/space-unary-ops"), - "spaced-comment": require("./rules/spaced-comment"), - strict: require("./rules/strict"), - "switch-colon-spacing": require("./rules/switch-colon-spacing"), - "symbol-description": require("./rules/symbol-description"), - "template-curly-spacing": require("./rules/template-curly-spacing"), - "template-tag-spacing": require("./rules/template-tag-spacing"), - "unicode-bom": require("./rules/unicode-bom"), - "use-isnan": require("./rules/use-isnan"), - "valid-jsdoc": require("./rules/valid-jsdoc"), - "valid-typeof": require("./rules/valid-typeof"), - "vars-on-top": require("./rules/vars-on-top"), - "wrap-iife": require("./rules/wrap-iife"), - "wrap-regex": require("./rules/wrap-regex"), - "yield-star-spacing": require("./rules/yield-star-spacing"), - yoda: require("./rules/yoda") -}; diff --git a/tools/node_modules/eslint/lib/cli-engine.js b/tools/node_modules/eslint/lib/cli-engine.js deleted file mode 100644 index dbf1abd00430c6..00000000000000 --- a/tools/node_modules/eslint/lib/cli-engine.js +++ /dev/null @@ -1,796 +0,0 @@ -/** - * @fileoverview Main CLI object. - * @author Nicholas C. Zakas - */ - -"use strict"; - -/* - * The CLI object should *not* call process.exit() directly. It should only return - * exit codes. This allows other programs to use the CLI object and still control - * when the program exits. - */ - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const fs = require("fs"), - path = require("path"), - defaultOptions = require("../conf/default-cli-options"), - Linter = require("./linter"), - lodash = require("lodash"), - IgnoredPaths = require("./util/ignored-paths"), - Config = require("./config"), - ConfigOps = require("./config/config-ops"), - LintResultCache = require("./util/lint-result-cache"), - globUtils = require("./util/glob-utils"), - validator = require("./config/config-validator"), - hash = require("./util/hash"), - ModuleResolver = require("./util/module-resolver"), - naming = require("./util/naming"), - pkg = require("../package.json"), - loadRules = require("./load-rules"); - -const debug = require("debug")("eslint:cli-engine"); -const resolver = new ModuleResolver(); -const validFixTypes = new Set(["problem", "suggestion", "layout"]); - -//------------------------------------------------------------------------------ -// Typedefs -//------------------------------------------------------------------------------ - -/** - * The options to configure a CLI engine with. - * @typedef {Object} CLIEngineOptions - * @property {boolean} allowInlineConfig Enable or disable inline configuration comments. - * @property {Object} baseConfig Base config object, extended by all configs used with this CLIEngine instance - * @property {boolean} cache Enable result caching. - * @property {string} cacheLocation The cache file to use instead of .eslintcache. - * @property {string} configFile The configuration file to use. - * @property {string} cwd The value to use for the current working directory. - * @property {string[]} envs An array of environments to load. - * @property {string[]} extensions An array of file extensions to check. - * @property {boolean|Function} fix Execute in autofix mode. If a function, should return a boolean. - * @property {string[]} fixTypes Array of rule types to apply fixes for. - * @property {string[]} globals An array of global variables to declare. - * @property {boolean} ignore False disables use of .eslintignore. - * @property {string} ignorePath The ignore file to use instead of .eslintignore. - * @property {string} ignorePattern A glob pattern of files to ignore. - * @property {boolean} useEslintrc False disables looking for .eslintrc - * @property {string} parser The name of the parser to use. - * @property {Object} parserOptions An object of parserOption settings to use. - * @property {string[]} plugins An array of plugins to load. - * @property {Object} rules An object of rules to use. - * @property {string[]} rulePaths An array of directories to load custom rules from. - * @property {boolean} reportUnusedDisableDirectives `true` adds reports for unused eslint-disable directives - */ - -/** - * A linting warning or error. - * @typedef {Object} LintMessage - * @property {string} message The message to display to the user. - */ - -/** - * A linting result. - * @typedef {Object} LintResult - * @property {string} filePath The path to the file that was linted. - * @property {LintMessage[]} messages All of the messages for the result. - * @property {number} errorCount Number of errors for the result. - * @property {number} warningCount Number of warnings for the result. - * @property {number} fixableErrorCount Number of fixable errors for the result. - * @property {number} fixableWarningCount Number of fixable warnings for the result. - * @property {string=} [source] The source code of the file that was linted. - * @property {string=} [output] The source code of the file that was linted, with as many fixes applied as possible. - */ - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Determines if each fix type in an array is supported by ESLint and throws - * an error if not. - * @param {string[]} fixTypes An array of fix types to check. - * @returns {void} - * @throws {Error} If an invalid fix type is found. - */ -function validateFixTypes(fixTypes) { - for (const fixType of fixTypes) { - if (!validFixTypes.has(fixType)) { - throw new Error(`Invalid fix type "${fixType}" found.`); - } - } -} - -/** - * It will calculate the error and warning count for collection of messages per file - * @param {Object[]} messages - Collection of messages - * @returns {Object} Contains the stats - * @private - */ -function calculateStatsPerFile(messages) { - return messages.reduce((stat, message) => { - if (message.fatal || message.severity === 2) { - stat.errorCount++; - if (message.fix) { - stat.fixableErrorCount++; - } - } else { - stat.warningCount++; - if (message.fix) { - stat.fixableWarningCount++; - } - } - return stat; - }, { - errorCount: 0, - warningCount: 0, - fixableErrorCount: 0, - fixableWarningCount: 0 - }); -} - -/** - * It will calculate the error and warning count for collection of results from all files - * @param {Object[]} results - Collection of messages from all the files - * @returns {Object} Contains the stats - * @private - */ -function calculateStatsPerRun(results) { - return results.reduce((stat, result) => { - stat.errorCount += result.errorCount; - stat.warningCount += result.warningCount; - stat.fixableErrorCount += result.fixableErrorCount; - stat.fixableWarningCount += result.fixableWarningCount; - return stat; - }, { - errorCount: 0, - warningCount: 0, - fixableErrorCount: 0, - fixableWarningCount: 0 - }); -} - -/** - * Processes an source code using ESLint. - * @param {string} text The source code to check. - * @param {Object} configHelper The configuration options for ESLint. - * @param {string} filename An optional string representing the texts filename. - * @param {boolean|Function} fix Indicates if fixes should be processed. - * @param {boolean} allowInlineConfig Allow/ignore comments that change config. - * @param {boolean} reportUnusedDisableDirectives Allow/ignore comments that change config. - * @param {Linter} linter Linter context - * @returns {{rules: LintResult, config: Object}} The results for linting on this text and the fully-resolved config for it. - * @private - */ -function processText(text, configHelper, filename, fix, allowInlineConfig, reportUnusedDisableDirectives, linter) { - let filePath, - fileExtension, - processor; - - if (filename) { - filePath = path.resolve(filename); - fileExtension = path.extname(filename); - } - - const effectiveFilename = filename || ""; - - debug(`Linting ${effectiveFilename}`); - const config = configHelper.getConfig(filePath); - - if (config.plugins) { - configHelper.plugins.loadAll(config.plugins); - } - - const loadedPlugins = configHelper.plugins.getAll(); - - for (const plugin in loadedPlugins) { - if (loadedPlugins[plugin].processors && Object.keys(loadedPlugins[plugin].processors).indexOf(fileExtension) >= 0) { - processor = loadedPlugins[plugin].processors[fileExtension]; - break; - } - } - - const autofixingEnabled = typeof fix !== "undefined" && (!processor || processor.supportsAutofix); - const fixedResult = linter.verifyAndFix(text, config, { - filename: effectiveFilename, - allowInlineConfig, - reportUnusedDisableDirectives, - fix: !!autofixingEnabled && fix, - preprocess: processor && (rawText => processor.preprocess(rawText, effectiveFilename)), - postprocess: processor && (problemLists => processor.postprocess(problemLists, effectiveFilename)) - }); - const stats = calculateStatsPerFile(fixedResult.messages); - - const result = { - filePath: effectiveFilename, - messages: fixedResult.messages, - errorCount: stats.errorCount, - warningCount: stats.warningCount, - fixableErrorCount: stats.fixableErrorCount, - fixableWarningCount: stats.fixableWarningCount - }; - - if (fixedResult.fixed) { - result.output = fixedResult.output; - } - - if (result.errorCount + result.warningCount > 0 && typeof result.output === "undefined") { - result.source = text; - } - - return { result, config }; -} - -/** - * Processes an individual file using ESLint. Files used here are known to - * exist, so no need to check that here. - * @param {string} filename The filename of the file being checked. - * @param {Object} configHelper The configuration options for ESLint. - * @param {Object} options The CLIEngine options object. - * @param {Linter} linter Linter context - * @returns {{rules: LintResult, config: Object}} The results for linting on this text and the fully-resolved config for it. - * @private - */ -function processFile(filename, configHelper, options, linter) { - - const text = fs.readFileSync(path.resolve(filename), "utf8"); - - return processText( - text, - configHelper, - filename, - options.fix, - options.allowInlineConfig, - options.reportUnusedDisableDirectives, - linter - ); -} - -/** - * Returns result with warning by ignore settings - * @param {string} filePath - File path of checked code - * @param {string} baseDir - Absolute path of base directory - * @returns {LintResult} Result with single warning - * @private - */ -function createIgnoreResult(filePath, baseDir) { - let message; - const isHidden = /^\./.test(path.basename(filePath)); - const isInNodeModules = baseDir && path.relative(baseDir, filePath).startsWith("node_modules"); - const isInBowerComponents = baseDir && path.relative(baseDir, filePath).startsWith("bower_components"); - - if (isHidden) { - 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."; - } else if (isInBowerComponents) { - 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."; - } - - return { - filePath: path.resolve(filePath), - messages: [ - { - fatal: false, - severity: 1, - message - } - ], - errorCount: 0, - warningCount: 1, - fixableErrorCount: 0, - fixableWarningCount: 0 - }; -} - -/** - * Produces rule warnings (i.e. deprecation) from configured rules - * @param {(Array|Set)} usedRules - Rules configured - * @param {Map} loadedRules - Map of loaded rules - * @returns {Array} Contains rule warnings - * @private - */ -function createRuleDeprecationWarnings(usedRules, loadedRules) { - const usedDeprecatedRules = []; - - usedRules.forEach(name => { - const loadedRule = loadedRules.get(name); - - if (loadedRule && loadedRule.meta && loadedRule.meta.deprecated) { - const deprecatedRule = { ruleId: name }; - const replacedBy = lodash.get(loadedRule, "meta.replacedBy", []); - - if (replacedBy.every(newRule => lodash.isString(newRule))) { - deprecatedRule.replacedBy = replacedBy; - } - - usedDeprecatedRules.push(deprecatedRule); - } - }); - - return usedDeprecatedRules; -} - -/** - * Checks if the given message is an error message. - * @param {Object} message The message to check. - * @returns {boolean} Whether or not the message is an error message. - * @private - */ -function isErrorMessage(message) { - return message.severity === 2; -} - - -/** - * return the cacheFile to be used by eslint, based on whether the provided parameter is - * a directory or looks like a directory (ends in `path.sep`), in which case the file - * name will be the `cacheFile/.cache_hashOfCWD` - * - * if cacheFile points to a file or looks like a file then in will just use that file - * - * @param {string} cacheFile The name of file to be used to store the cache - * @param {string} cwd Current working directory - * @returns {string} the resolved path to the cache file - */ -function getCacheFile(cacheFile, cwd) { - - /* - * make sure the path separators are normalized for the environment/os - * keeping the trailing path separator if present - */ - const normalizedCacheFile = path.normalize(cacheFile); - - const resolvedCacheFile = path.resolve(cwd, normalizedCacheFile); - const looksLikeADirectory = normalizedCacheFile.slice(-1) === path.sep; - - /** - * return the name for the cache file in case the provided parameter is a directory - * @returns {string} the resolved path to the cacheFile - */ - function getCacheFileForDirectory() { - return path.join(resolvedCacheFile, `.cache_${hash(cwd)}`); - } - - let fileStats; - - try { - fileStats = fs.lstatSync(resolvedCacheFile); - } catch (ex) { - fileStats = null; - } - - - /* - * in case the file exists we need to verify if the provided path - * is a directory or a file. If it is a directory we want to create a file - * inside that directory - */ - if (fileStats) { - - /* - * is a directory or is a file, but the original file the user provided - * looks like a directory but `path.resolve` removed the `last path.sep` - * so we need to still treat this like a directory - */ - if (fileStats.isDirectory() || looksLikeADirectory) { - return getCacheFileForDirectory(); - } - - // is file so just use that file - return resolvedCacheFile; - } - - /* - * here we known the file or directory doesn't exist, - * so we will try to infer if its a directory if it looks like a directory - * for the current operating system. - */ - - // if the last character passed is a path separator we assume is a directory - if (looksLikeADirectory) { - return getCacheFileForDirectory(); - } - - return resolvedCacheFile; -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -class CLIEngine { - - /** - * Creates a new instance of the core CLI engine. - * @param {CLIEngineOptions} providedOptions The options for this instance. - * @constructor - */ - constructor(providedOptions) { - - const options = Object.assign( - Object.create(null), - defaultOptions, - { cwd: process.cwd() }, - providedOptions - ); - - /* - * if an --ignore-path option is provided, ensure that the ignore - * file exists and is not a directory - */ - if (options.ignore && options.ignorePath) { - try { - if (!fs.statSync(options.ignorePath).isFile()) { - throw new Error(`${options.ignorePath} is not a file`); - } - } catch (e) { - e.message = `Error: Could not load file ${options.ignorePath}\nError: ${e.message}`; - throw e; - } - } - - /** - * Stored options for this instance - * @type {Object} - */ - this.options = options; - this.linter = new Linter(); - - // load in additional rules - if (this.options.rulePaths) { - const cwd = this.options.cwd; - - this.options.rulePaths.forEach(rulesdir => { - debug(`Loading rules from ${rulesdir}`); - this.linter.defineRules(loadRules(rulesdir, cwd)); - }); - } - - if (this.options.rules && Object.keys(this.options.rules).length) { - const loadedRules = this.linter.getRules(); - - // Ajv validator with default schema will mutate original object, so we must clone it recursively. - this.options.rules = lodash.cloneDeep(this.options.rules); - - Object.keys(this.options.rules).forEach(name => { - validator.validateRuleOptions(loadedRules.get(name), name, this.options.rules[name], "CLI"); - }); - } - - this.config = new Config(this.options, this.linter); - - if (this.options.cache) { - const cacheFile = getCacheFile(this.options.cacheLocation || this.options.cacheFile, this.options.cwd); - - /** - * Cache used to avoid operating on files that haven't changed since the - * last successful execution. - * @type {Object} - */ - this._lintResultCache = new LintResultCache(cacheFile, this.config); - } - - // setup special filter for fixes - if (this.options.fix && this.options.fixTypes && this.options.fixTypes.length > 0) { - - debug(`Using fix types ${this.options.fixTypes}`); - - // throw an error if any invalid fix types are found - validateFixTypes(this.options.fixTypes); - - // convert to Set for faster lookup - const fixTypes = new Set(this.options.fixTypes); - - // save original value of options.fix in case it's a function - const originalFix = (typeof this.options.fix === "function") - ? this.options.fix : () => this.options.fix; - - // create a cache of rules (but don't populate until needed) - this._rulesCache = null; - - this.options.fix = lintResult => { - const rule = this._rulesCache.get(lintResult.ruleId); - const matches = rule.meta && fixTypes.has(rule.meta.type); - - return matches && originalFix(lintResult); - }; - } - - } - - getRules() { - return this.linter.getRules(); - } - - /** - * Returns results that only contains errors. - * @param {LintResult[]} results The results to filter. - * @returns {LintResult[]} The filtered results. - */ - static getErrorResults(results) { - const filtered = []; - - results.forEach(result => { - const filteredMessages = result.messages.filter(isErrorMessage); - - if (filteredMessages.length > 0) { - filtered.push( - Object.assign(result, { - messages: filteredMessages, - errorCount: filteredMessages.length, - warningCount: 0, - fixableErrorCount: result.fixableErrorCount, - fixableWarningCount: 0 - }) - ); - } - }); - - return filtered; - } - - /** - * Outputs fixes from the given results to files. - * @param {Object} report The report object created by CLIEngine. - * @returns {void} - */ - static outputFixes(report) { - report.results.filter(result => Object.prototype.hasOwnProperty.call(result, "output")).forEach(result => { - fs.writeFileSync(result.filePath, result.output); - }); - } - - - /** - * Add a plugin by passing its configuration - * @param {string} name Name of the plugin. - * @param {Object} pluginobject Plugin configuration object. - * @returns {void} - */ - addPlugin(name, pluginobject) { - this.config.plugins.define(name, pluginobject); - } - - /** - * Resolves the patterns passed into executeOnFiles() into glob-based patterns - * for easier handling. - * @param {string[]} patterns The file patterns passed on the command line. - * @returns {string[]} The equivalent glob patterns. - */ - resolveFileGlobPatterns(patterns) { - return globUtils.resolveFileGlobPatterns(patterns.filter(Boolean), this.options); - } - - /** - * Executes the current configuration on an array of file and directory names. - * @param {string[]} patterns An array of file and directory names. - * @returns {Object} The results for all files that were linted. - */ - executeOnFiles(patterns) { - const options = this.options, - lintResultCache = this._lintResultCache, - configHelper = this.config; - const cacheFile = getCacheFile(this.options.cacheLocation || this.options.cacheFile, this.options.cwd); - - if (!options.cache && fs.existsSync(cacheFile)) { - fs.unlinkSync(cacheFile); - } - - const startTime = Date.now(); - const fileList = globUtils.listFilesToProcess(patterns, options); - const allUsedRules = new Set(); - const results = fileList.map(fileInfo => { - if (fileInfo.ignored) { - return createIgnoreResult(fileInfo.filename, options.cwd); - } - - if (options.cache) { - const cachedLintResults = lintResultCache.getCachedLintResults(fileInfo.filename); - - if (cachedLintResults) { - const resultHadMessages = cachedLintResults.messages && cachedLintResults.messages.length; - - if (resultHadMessages && options.fix) { - debug(`Reprocessing cached file to allow autofix: ${fileInfo.filename}`); - } else { - debug(`Skipping file since it hasn't changed: ${fileInfo.filename}`); - - return cachedLintResults; - } - } - } - - // if there's a cache, populate it - if ("_rulesCache" in this) { - this._rulesCache = this.getRules(); - } - - debug(`Processing ${fileInfo.filename}`); - - const { result, config } = processFile(fileInfo.filename, configHelper, options, this.linter); - - Object.keys(config.rules) - .filter(ruleId => ConfigOps.getRuleSeverity(config.rules[ruleId])) - .forEach(ruleId => allUsedRules.add(ruleId)); - - return result; - }); - - if (options.cache) { - results.forEach(result => { - - /* - * Store the lint result in the LintResultCache. - * NOTE: The LintResultCache will remove the file source and any - * other properties that are difficult to serialize, and will - * hydrate those properties back in on future lint runs. - */ - lintResultCache.setCachedLintResults(result.filePath, result); - }); - - // persist the cache to disk - lintResultCache.reconcile(); - } - - const stats = calculateStatsPerRun(results); - - const usedDeprecatedRules = createRuleDeprecationWarnings(allUsedRules, this.getRules()); - - debug(`Linting complete in: ${Date.now() - startTime}ms`); - - return { - results, - errorCount: stats.errorCount, - warningCount: stats.warningCount, - fixableErrorCount: stats.fixableErrorCount, - fixableWarningCount: stats.fixableWarningCount, - usedDeprecatedRules - }; - } - - /** - * Executes the current configuration on text. - * @param {string} text A string of JavaScript code to lint. - * @param {string} filename An optional string representing the texts filename. - * @param {boolean} warnIgnored Always warn when a file is ignored - * @returns {Object} The results for the linting. - */ - executeOnText(text, filename, warnIgnored) { - - const results = [], - options = this.options, - configHelper = this.config, - ignoredPaths = new IgnoredPaths(options); - - // resolve filename based on options.cwd (for reporting, ignoredPaths also resolves) - - const resolvedFilename = filename && !path.isAbsolute(filename) - ? path.resolve(options.cwd, filename) - : filename; - let usedDeprecatedRules; - - if (resolvedFilename && ignoredPaths.contains(resolvedFilename)) { - if (warnIgnored) { - results.push(createIgnoreResult(resolvedFilename, options.cwd)); - } - usedDeprecatedRules = []; - } else { - - // if there's a cache, populate it - if ("_rulesCache" in this) { - this._rulesCache = this.getRules(); - } - - const { result, config } = processText( - text, - configHelper, - resolvedFilename, - options.fix, - options.allowInlineConfig, - options.reportUnusedDisableDirectives, - this.linter - ); - - results.push(result); - usedDeprecatedRules = createRuleDeprecationWarnings( - Object.keys(config.rules).filter(rule => ConfigOps.getRuleSeverity(config.rules[rule])), - this.getRules() - ); - } - - const stats = calculateStatsPerRun(results); - - return { - results, - errorCount: stats.errorCount, - warningCount: stats.warningCount, - fixableErrorCount: stats.fixableErrorCount, - fixableWarningCount: stats.fixableWarningCount, - usedDeprecatedRules - }; - } - - /** - * Returns a configuration object for the given file based on the CLI options. - * This is the same logic used by the ESLint CLI executable to determine - * configuration for each file it processes. - * @param {string} filePath The path of the file to retrieve a config object for. - * @returns {Object} A configuration object for the file. - */ - getConfigForFile(filePath) { - const configHelper = this.config; - - return configHelper.getConfig(filePath); - } - - /** - * Checks if a given path is ignored by ESLint. - * @param {string} filePath The path of the file to check. - * @returns {boolean} Whether or not the given path is ignored. - */ - isPathIgnored(filePath) { - const resolvedPath = path.resolve(this.options.cwd, filePath); - const ignoredPaths = new IgnoredPaths(this.options); - - return ignoredPaths.contains(resolvedPath); - } - - /** - * Returns the formatter representing the given format or null if no formatter - * with the given name can be found. - * @param {string} [format] The name of the format to load or the path to a - * custom formatter. - * @returns {Function} The formatter function or null if not found. - */ - getFormatter(format) { - - // default is stylish - const resolvedFormatName = format || "stylish"; - - // only strings are valid formatters - if (typeof resolvedFormatName === "string") { - - // replace \ with / for Windows compatibility - const normalizedFormatName = resolvedFormatName.replace(/\\/g, "/"); - - const cwd = this.options ? this.options.cwd : process.cwd(); - const namespace = naming.getNamespaceFromTerm(normalizedFormatName); - - let formatterPath; - - // if there's a slash, then it's a file - if (!namespace && normalizedFormatName.indexOf("/") > -1) { - formatterPath = path.resolve(cwd, normalizedFormatName); - } else { - try { - const npmFormat = naming.normalizePackageName(normalizedFormatName, "eslint-formatter"); - - formatterPath = resolver.resolve(npmFormat, `${cwd}/node_modules`); - } catch (e) { - formatterPath = `./formatters/${normalizedFormatName}`; - } - } - - try { - return require(formatterPath); - } catch (ex) { - ex.message = `There was a problem loading formatter: ${formatterPath}\nError: ${ex.message}`; - throw ex; - } - - } else { - return null; - } - } -} - -CLIEngine.version = pkg.version; -CLIEngine.getFormatter = CLIEngine.prototype.getFormatter; - -module.exports = CLIEngine; diff --git a/tools/node_modules/eslint/lib/cli.js b/tools/node_modules/eslint/lib/cli.js deleted file mode 100644 index f67eb7274ffa64..00000000000000 --- a/tools/node_modules/eslint/lib/cli.js +++ /dev/null @@ -1,227 +0,0 @@ -/** - * @fileoverview Main CLI object. - * @author Nicholas C. Zakas - */ - -"use strict"; - -/* - * The CLI object should *not* call process.exit() directly. It should only return - * exit codes. This allows other programs to use the CLI object and still control - * when the program exits. - */ - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const fs = require("fs"), - path = require("path"), - options = require("./options"), - CLIEngine = require("./cli-engine"), - mkdirp = require("mkdirp"), - log = require("./util/logging"); - -const debug = require("debug")("eslint:cli"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Predicate function for whether or not to apply fixes in quiet mode. - * If a message is a warning, do not apply a fix. - * @param {LintResult} lintResult The lint result. - * @returns {boolean} True if the lint message is an error (and thus should be - * autofixed), false otherwise. - */ -function quietFixPredicate(lintResult) { - return lintResult.severity === 2; -} - -/** - * Translates the CLI options into the options expected by the CLIEngine. - * @param {Object} cliOptions The CLI options to translate. - * @returns {CLIEngineOptions} The options object for the CLIEngine. - * @private - */ -function translateOptions(cliOptions) { - return { - envs: cliOptions.env, - extensions: cliOptions.ext, - rules: cliOptions.rule, - plugins: cliOptions.plugin, - globals: cliOptions.global, - ignore: cliOptions.ignore, - ignorePath: cliOptions.ignorePath, - ignorePattern: cliOptions.ignorePattern, - configFile: cliOptions.config, - rulePaths: cliOptions.rulesdir, - useEslintrc: cliOptions.eslintrc, - parser: cliOptions.parser, - parserOptions: cliOptions.parserOptions, - cache: cliOptions.cache, - cacheFile: cliOptions.cacheFile, - cacheLocation: cliOptions.cacheLocation, - fix: (cliOptions.fix || cliOptions.fixDryRun) && (cliOptions.quiet ? quietFixPredicate : true), - fixTypes: cliOptions.fixType, - allowInlineConfig: cliOptions.inlineConfig, - reportUnusedDisableDirectives: cliOptions.reportUnusedDisableDirectives - }; -} - -/** - * Outputs the results of the linting. - * @param {CLIEngine} engine The CLIEngine to use. - * @param {LintResult[]} results The results to print. - * @param {string} format The name of the formatter to use or the path to the formatter. - * @param {string} outputFile The path for the output file. - * @returns {boolean} True if the printing succeeds, false if not. - * @private - */ -function printResults(engine, results, format, outputFile) { - let formatter; - - try { - formatter = engine.getFormatter(format); - } catch (e) { - log.error(e.message); - return false; - } - - const output = formatter(results); - - if (output) { - if (outputFile) { - const filePath = path.resolve(process.cwd(), outputFile); - - if (fs.existsSync(filePath) && fs.statSync(filePath).isDirectory()) { - log.error("Cannot write to output file path, it is a directory: %s", outputFile); - return false; - } - - try { - mkdirp.sync(path.dirname(filePath)); - fs.writeFileSync(filePath, output); - } catch (ex) { - log.error("There was a problem writing the output file:\n%s", ex); - return false; - } - } else { - log.info(output); - } - } - - return true; - -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -/** - * Encapsulates all CLI behavior for eslint. Makes it easier to test as well as - * for other Node.js programs to effectively run the CLI. - */ -const cli = { - - /** - * Executes the CLI based on an array of arguments that is passed in. - * @param {string|Array|Object} args The arguments to process. - * @param {string} [text] The text to lint (used for TTY). - * @returns {int} The exit code for the operation. - */ - execute(args, text) { - if (Array.isArray(args)) { - debug("CLI args: %o", args.slice(2)); - } - - let currentOptions; - - try { - currentOptions = options.parse(args); - } catch (error) { - log.error(error.message); - return 2; - } - - const files = currentOptions._; - - const useStdin = typeof text === "string"; - - if (currentOptions.version) { // version from package.json - - log.info(`v${require("../package.json").version}`); - - } else if (currentOptions.printConfig) { - if (files.length) { - log.error("The --print-config option must be used with exactly one file name."); - return 2; - } - if (useStdin) { - log.error("The --print-config option is not available for piped-in code."); - return 2; - } - - const engine = new CLIEngine(translateOptions(currentOptions)); - - const fileConfig = engine.getConfigForFile(currentOptions.printConfig); - - log.info(JSON.stringify(fileConfig, null, " ")); - return 0; - } else if (currentOptions.help || (!files.length && !useStdin)) { - - log.info(options.generateHelp()); - - } else { - - debug(`Running on ${useStdin ? "text" : "files"}`); - - if (currentOptions.fix && currentOptions.fixDryRun) { - log.error("The --fix option and the --fix-dry-run option cannot be used together."); - return 2; - } - - if (useStdin && currentOptions.fix) { - log.error("The --fix option is not available for piped-in code; use --fix-dry-run instead."); - return 2; - } - - if (currentOptions.fixType && !currentOptions.fix && !currentOptions.fixDryRun) { - log.error("The --fix-type option requires either --fix or --fix-dry-run."); - return 2; - } - - const engine = new CLIEngine(translateOptions(currentOptions)); - const report = useStdin ? engine.executeOnText(text, currentOptions.stdinFilename, true) : engine.executeOnFiles(files); - - if (currentOptions.fix) { - debug("Fix mode enabled - applying fixes"); - CLIEngine.outputFixes(report); - } - - if (currentOptions.quiet) { - debug("Quiet mode enabled - filtering out warnings"); - report.results = CLIEngine.getErrorResults(report.results); - } - - if (printResults(engine, report.results, currentOptions.format, currentOptions.outputFile)) { - const tooManyWarnings = currentOptions.maxWarnings >= 0 && report.warningCount > currentOptions.maxWarnings; - - if (!report.errorCount && tooManyWarnings) { - log.error("ESLint found too many warnings (maximum: %s).", currentOptions.maxWarnings); - } - - return (report.errorCount || tooManyWarnings) ? 1 : 0; - } - return 2; - - - } - - return 0; - } -}; - -module.exports = cli; diff --git a/tools/node_modules/eslint/lib/code-path-analysis/code-path-analyzer.js b/tools/node_modules/eslint/lib/code-path-analysis/code-path-analyzer.js deleted file mode 100644 index b81e212e7f47dd..00000000000000 --- a/tools/node_modules/eslint/lib/code-path-analysis/code-path-analyzer.js +++ /dev/null @@ -1,683 +0,0 @@ -/** - * @fileoverview A class of the code path analyzer. - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const assert = require("assert"), - CodePath = require("./code-path"), - CodePathSegment = require("./code-path-segment"), - IdGenerator = require("./id-generator"), - debug = require("./debug-helpers"), - astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks whether or not a given node is a `case` node (not `default` node). - * - * @param {ASTNode} node - A `SwitchCase` node to check. - * @returns {boolean} `true` if the node is a `case` node (not `default` node). - */ -function isCaseNode(node) { - return Boolean(node.test); -} - -/** - * Checks whether the given logical operator is taken into account for the code - * path analysis. - * - * @param {string} operator - The operator found in the LogicalExpression node - * @returns {boolean} `true` if the operator is "&&" or "||" - */ -function isHandledLogicalOperator(operator) { - return operator === "&&" || operator === "||"; -} - -/** - * Checks whether or not a given logical expression node goes different path - * between the `true` case and the `false` case. - * - * @param {ASTNode} node - A node to check. - * @returns {boolean} `true` if the node is a test of a choice statement. - */ -function isForkingByTrueOrFalse(node) { - const parent = node.parent; - - switch (parent.type) { - case "ConditionalExpression": - case "IfStatement": - case "WhileStatement": - case "DoWhileStatement": - case "ForStatement": - return parent.test === node; - - case "LogicalExpression": - return isHandledLogicalOperator(parent.operator); - - default: - return false; - } -} - -/** - * Gets the boolean value of a given literal node. - * - * This is used to detect infinity loops (e.g. `while (true) {}`). - * Statements preceded by an infinity loop are unreachable if the loop didn't - * have any `break` statement. - * - * @param {ASTNode} node - A node to get. - * @returns {boolean|undefined} a boolean value if the node is a Literal node, - * otherwise `undefined`. - */ -function getBooleanValueIfSimpleConstant(node) { - if (node.type === "Literal") { - return Boolean(node.value); - } - return void 0; -} - -/** - * Checks that a given identifier node is a reference or not. - * - * This is used to detect the first throwable node in a `try` block. - * - * @param {ASTNode} node - An Identifier node to check. - * @returns {boolean} `true` if the node is a reference. - */ -function isIdentifierReference(node) { - const parent = node.parent; - - switch (parent.type) { - case "LabeledStatement": - case "BreakStatement": - case "ContinueStatement": - case "ArrayPattern": - case "RestElement": - case "ImportSpecifier": - case "ImportDefaultSpecifier": - case "ImportNamespaceSpecifier": - case "CatchClause": - return false; - - case "FunctionDeclaration": - case "FunctionExpression": - case "ArrowFunctionExpression": - case "ClassDeclaration": - case "ClassExpression": - case "VariableDeclarator": - return parent.id !== node; - - case "Property": - case "MethodDefinition": - return ( - parent.key !== node || - parent.computed || - parent.shorthand - ); - - case "AssignmentPattern": - return parent.key !== node; - - default: - return true; - } -} - -/** - * Updates the current segment with the head segment. - * This is similar to local branches and tracking branches of git. - * - * To separate the current and the head is in order to not make useless segments. - * - * In this process, both "onCodePathSegmentStart" and "onCodePathSegmentEnd" - * events are fired. - * - * @param {CodePathAnalyzer} analyzer - The instance. - * @param {ASTNode} node - The current AST node. - * @returns {void} - */ -function forwardCurrentToHead(analyzer, node) { - const codePath = analyzer.codePath; - const state = CodePath.getState(codePath); - const currentSegments = state.currentSegments; - const headSegments = state.headSegments; - const end = Math.max(currentSegments.length, headSegments.length); - let i, currentSegment, headSegment; - - // Fires leaving events. - for (i = 0; i < end; ++i) { - currentSegment = currentSegments[i]; - headSegment = headSegments[i]; - - if (currentSegment !== headSegment && currentSegment) { - debug.dump(`onCodePathSegmentEnd ${currentSegment.id}`); - - if (currentSegment.reachable) { - analyzer.emitter.emit( - "onCodePathSegmentEnd", - currentSegment, - node - ); - } - } - } - - // Update state. - state.currentSegments = headSegments; - - // Fires entering events. - for (i = 0; i < end; ++i) { - currentSegment = currentSegments[i]; - headSegment = headSegments[i]; - - if (currentSegment !== headSegment && headSegment) { - debug.dump(`onCodePathSegmentStart ${headSegment.id}`); - - CodePathSegment.markUsed(headSegment); - if (headSegment.reachable) { - analyzer.emitter.emit( - "onCodePathSegmentStart", - headSegment, - node - ); - } - } - } - -} - -/** - * Updates the current segment with empty. - * This is called at the last of functions or the program. - * - * @param {CodePathAnalyzer} analyzer - The instance. - * @param {ASTNode} node - The current AST node. - * @returns {void} - */ -function leaveFromCurrentSegment(analyzer, node) { - const state = CodePath.getState(analyzer.codePath); - const currentSegments = state.currentSegments; - - for (let i = 0; i < currentSegments.length; ++i) { - const currentSegment = currentSegments[i]; - - debug.dump(`onCodePathSegmentEnd ${currentSegment.id}`); - if (currentSegment.reachable) { - analyzer.emitter.emit( - "onCodePathSegmentEnd", - currentSegment, - node - ); - } - } - - state.currentSegments = []; -} - -/** - * Updates the code path due to the position of a given node in the parent node - * thereof. - * - * For example, if the node is `parent.consequent`, this creates a fork from the - * current path. - * - * @param {CodePathAnalyzer} analyzer - The instance. - * @param {ASTNode} node - The current AST node. - * @returns {void} - */ -function preprocess(analyzer, node) { - const codePath = analyzer.codePath; - const state = CodePath.getState(codePath); - const parent = node.parent; - - switch (parent.type) { - case "LogicalExpression": - if ( - parent.right === node && - isHandledLogicalOperator(parent.operator) - ) { - state.makeLogicalRight(); - } - break; - - case "ConditionalExpression": - case "IfStatement": - - /* - * Fork if this node is at `consequent`/`alternate`. - * `popForkContext()` exists at `IfStatement:exit` and - * `ConditionalExpression:exit`. - */ - if (parent.consequent === node) { - state.makeIfConsequent(); - } else if (parent.alternate === node) { - state.makeIfAlternate(); - } - break; - - case "SwitchCase": - if (parent.consequent[0] === node) { - state.makeSwitchCaseBody(false, !parent.test); - } - break; - - case "TryStatement": - if (parent.handler === node) { - state.makeCatchBlock(); - } else if (parent.finalizer === node) { - state.makeFinallyBlock(); - } - break; - - case "WhileStatement": - if (parent.test === node) { - state.makeWhileTest(getBooleanValueIfSimpleConstant(node)); - } else { - assert(parent.body === node); - state.makeWhileBody(); - } - break; - - case "DoWhileStatement": - if (parent.body === node) { - state.makeDoWhileBody(); - } else { - assert(parent.test === node); - state.makeDoWhileTest(getBooleanValueIfSimpleConstant(node)); - } - break; - - case "ForStatement": - if (parent.test === node) { - state.makeForTest(getBooleanValueIfSimpleConstant(node)); - } else if (parent.update === node) { - state.makeForUpdate(); - } else if (parent.body === node) { - state.makeForBody(); - } - break; - - case "ForInStatement": - case "ForOfStatement": - if (parent.left === node) { - state.makeForInOfLeft(); - } else if (parent.right === node) { - state.makeForInOfRight(); - } else { - assert(parent.body === node); - state.makeForInOfBody(); - } - break; - - case "AssignmentPattern": - - /* - * Fork if this node is at `right`. - * `left` is executed always, so it uses the current path. - * `popForkContext()` exists at `AssignmentPattern:exit`. - */ - if (parent.right === node) { - state.pushForkContext(); - state.forkBypassPath(); - state.forkPath(); - } - break; - - default: - break; - } -} - -/** - * Updates the code path due to the type of a given node in entering. - * - * @param {CodePathAnalyzer} analyzer - The instance. - * @param {ASTNode} node - The current AST node. - * @returns {void} - */ -function processCodePathToEnter(analyzer, node) { - let codePath = analyzer.codePath; - let state = codePath && CodePath.getState(codePath); - const parent = node.parent; - - switch (node.type) { - case "Program": - case "FunctionDeclaration": - case "FunctionExpression": - case "ArrowFunctionExpression": - if (codePath) { - - // Emits onCodePathSegmentStart events if updated. - forwardCurrentToHead(analyzer, node); - debug.dumpState(node, state, false); - } - - // Create the code path of this scope. - codePath = analyzer.codePath = new CodePath( - analyzer.idGenerator.next(), - codePath, - analyzer.onLooped - ); - state = CodePath.getState(codePath); - - // Emits onCodePathStart events. - debug.dump(`onCodePathStart ${codePath.id}`); - analyzer.emitter.emit("onCodePathStart", codePath, node); - break; - - case "LogicalExpression": - if (isHandledLogicalOperator(node.operator)) { - state.pushChoiceContext( - node.operator, - isForkingByTrueOrFalse(node) - ); - } - break; - - case "ConditionalExpression": - case "IfStatement": - state.pushChoiceContext("test", false); - break; - - case "SwitchStatement": - state.pushSwitchContext( - node.cases.some(isCaseNode), - astUtils.getLabel(node) - ); - break; - - case "TryStatement": - state.pushTryContext(Boolean(node.finalizer)); - break; - - case "SwitchCase": - - /* - * Fork if this node is after the 2st node in `cases`. - * It's similar to `else` blocks. - * The next `test` node is processed in this path. - */ - if (parent.discriminant !== node && parent.cases[0] !== node) { - state.forkPath(); - } - break; - - case "WhileStatement": - case "DoWhileStatement": - case "ForStatement": - case "ForInStatement": - case "ForOfStatement": - state.pushLoopContext(node.type, astUtils.getLabel(node)); - break; - - case "LabeledStatement": - if (!astUtils.isBreakableStatement(node.body)) { - state.pushBreakContext(false, node.label.name); - } - break; - - default: - break; - } - - // Emits onCodePathSegmentStart events if updated. - forwardCurrentToHead(analyzer, node); - debug.dumpState(node, state, false); -} - -/** - * Updates the code path due to the type of a given node in leaving. - * - * @param {CodePathAnalyzer} analyzer - The instance. - * @param {ASTNode} node - The current AST node. - * @returns {void} - */ -function processCodePathToExit(analyzer, node) { - const codePath = analyzer.codePath; - const state = CodePath.getState(codePath); - let dontForward = false; - - switch (node.type) { - case "IfStatement": - case "ConditionalExpression": - state.popChoiceContext(); - break; - - case "LogicalExpression": - if (isHandledLogicalOperator(node.operator)) { - state.popChoiceContext(); - } - break; - - case "SwitchStatement": - state.popSwitchContext(); - break; - - case "SwitchCase": - - /* - * This is the same as the process at the 1st `consequent` node in - * `preprocess` function. - * Must do if this `consequent` is empty. - */ - if (node.consequent.length === 0) { - state.makeSwitchCaseBody(true, !node.test); - } - if (state.forkContext.reachable) { - dontForward = true; - } - break; - - case "TryStatement": - state.popTryContext(); - break; - - case "BreakStatement": - forwardCurrentToHead(analyzer, node); - state.makeBreak(node.label && node.label.name); - dontForward = true; - break; - - case "ContinueStatement": - forwardCurrentToHead(analyzer, node); - state.makeContinue(node.label && node.label.name); - dontForward = true; - break; - - case "ReturnStatement": - forwardCurrentToHead(analyzer, node); - state.makeReturn(); - dontForward = true; - break; - - case "ThrowStatement": - forwardCurrentToHead(analyzer, node); - state.makeThrow(); - dontForward = true; - break; - - case "Identifier": - if (isIdentifierReference(node)) { - state.makeFirstThrowablePathInTryBlock(); - dontForward = true; - } - break; - - case "CallExpression": - case "MemberExpression": - case "NewExpression": - state.makeFirstThrowablePathInTryBlock(); - break; - - case "WhileStatement": - case "DoWhileStatement": - case "ForStatement": - case "ForInStatement": - case "ForOfStatement": - state.popLoopContext(); - break; - - case "AssignmentPattern": - state.popForkContext(); - break; - - case "LabeledStatement": - if (!astUtils.isBreakableStatement(node.body)) { - state.popBreakContext(); - } - break; - - default: - break; - } - - // Emits onCodePathSegmentStart events if updated. - if (!dontForward) { - forwardCurrentToHead(analyzer, node); - } - debug.dumpState(node, state, true); -} - -/** - * Updates the code path to finalize the current code path. - * - * @param {CodePathAnalyzer} analyzer - The instance. - * @param {ASTNode} node - The current AST node. - * @returns {void} - */ -function postprocess(analyzer, node) { - switch (node.type) { - case "Program": - case "FunctionDeclaration": - case "FunctionExpression": - case "ArrowFunctionExpression": { - let codePath = analyzer.codePath; - - // Mark the current path as the final node. - CodePath.getState(codePath).makeFinal(); - - // Emits onCodePathSegmentEnd event of the current segments. - leaveFromCurrentSegment(analyzer, node); - - // Emits onCodePathEnd event of this code path. - debug.dump(`onCodePathEnd ${codePath.id}`); - analyzer.emitter.emit("onCodePathEnd", codePath, node); - debug.dumpDot(codePath); - - codePath = analyzer.codePath = analyzer.codePath.upper; - if (codePath) { - debug.dumpState(node, CodePath.getState(codePath), true); - } - break; - } - - default: - break; - } -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -/** - * The class to analyze code paths. - * This class implements the EventGenerator interface. - */ -class 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. - * This updates state of analysis and calls `enterNode` of the wrapped. - * - * @param {ASTNode} node - A node which is entering. - * @returns {void} - */ - enterNode(node) { - this.currentNode = node; - - // Updates the code path due to node's position in its parent node. - if (node.parent) { - preprocess(this, node); - } - - /* - * Updates the code path. - * And emits onCodePathStart/onCodePathSegmentStart events. - */ - processCodePathToEnter(this, node); - - // Emits node events. - this.original.enterNode(node); - - this.currentNode = null; - } - - /** - * Does the process to leave a given AST node. - * This updates state of analysis and calls `leaveNode` of the wrapped. - * - * @param {ASTNode} node - A node which is leaving. - * @returns {void} - */ - leaveNode(node) { - this.currentNode = node; - - /* - * Updates the code path. - * And emits onCodePathStart/onCodePathSegmentStart events. - */ - processCodePathToExit(this, node); - - // Emits node events. - this.original.leaveNode(node); - - // Emits the last onCodePathStart/onCodePathSegmentStart events. - postprocess(this, node); - - this.currentNode = null; - } - - /** - * This is called on a code path looped. - * Then this raises a looped event. - * - * @param {CodePathSegment} fromSegment - A segment of prev. - * @param {CodePathSegment} toSegment - A segment of next. - * @returns {void} - */ - onLooped(fromSegment, toSegment) { - if (fromSegment.reachable && toSegment.reachable) { - debug.dump(`onCodePathSegmentLoop ${fromSegment.id} -> ${toSegment.id}`); - this.emitter.emit( - "onCodePathSegmentLoop", - fromSegment, - toSegment, - this.currentNode - ); - } - } -} - -module.exports = CodePathAnalyzer; diff --git a/tools/node_modules/eslint/lib/code-path-analysis/code-path-segment.js b/tools/node_modules/eslint/lib/code-path-analysis/code-path-segment.js deleted file mode 100644 index 8145f9280162bb..00000000000000 --- a/tools/node_modules/eslint/lib/code-path-analysis/code-path-segment.js +++ /dev/null @@ -1,245 +0,0 @@ -/** - * @fileoverview A class of the code path segment. - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const debug = require("./debug-helpers"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks whether or not a given segment is reachable. - * - * @param {CodePathSegment} segment - A segment to check. - * @returns {boolean} `true` if the segment is reachable. - */ -function isReachable(segment) { - return segment.reachable; -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -/** - * A code path segment. - */ -class CodePathSegment { - - /** - * @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. - */ - 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: [] - } - }); - - /* istanbul ignore if */ - if (debug.enabled) { - this.internal.nodes = []; - this.internal.exitNodes = []; - } - } - - /** - * 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. - */ - isLoopedPrevSegment(segment) { - return this.internal.loopedPrevSegments.indexOf(segment) !== -1; - } - - /** - * Creates the root segment. - * - * @param {string} id - An identifier. - * @returns {CodePathSegment} The created segment. - */ - static newRoot(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. - */ - static newNext(id, allPrevSegments) { - return new CodePathSegment( - id, - CodePathSegment.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. - */ - static newUnreachable(id, allPrevSegments) { - const segment = new CodePathSegment(id, CodePathSegment.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. - */ - static newDisconnected(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} - */ - static markUsed(segment) { - if (segment.internal.used) { - return; - } - segment.internal.used = true; - - let 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); - } - } - } - - /** - * 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); - } - - /** - * Replaces unused segments with the previous segments of each unused segment. - * - * @param {CodePathSegment[]} segments - An array of segments to replace. - * @returns {CodePathSegment[]} The replaced array. - */ - static flattenUnusedSegments(segments) { - const done = Object.create(null); - const retv = []; - - for (let i = 0; i < segments.length; ++i) { - const segment = segments[i]; - - // Ignores duplicated. - if (done[segment.id]) { - continue; - } - - // Use previous segments if unused. - if (!segment.internal.used) { - for (let j = 0; j < segment.allPrevSegments.length; ++j) { - const prevSegment = segment.allPrevSegments[j]; - - if (!done[prevSegment.id]) { - done[prevSegment.id] = true; - retv.push(prevSegment); - } - } - } else { - done[segment.id] = true; - retv.push(segment); - } - } - - return retv; - } -} - -module.exports = CodePathSegment; diff --git a/tools/node_modules/eslint/lib/code-path-analysis/code-path-state.js b/tools/node_modules/eslint/lib/code-path-analysis/code-path-state.js deleted file mode 100644 index 57da10fa915a36..00000000000000 --- a/tools/node_modules/eslint/lib/code-path-analysis/code-path-state.js +++ /dev/null @@ -1,1440 +0,0 @@ -/** - * @fileoverview A class to manage state of generating a code path. - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const CodePathSegment = require("./code-path-segment"), - ForkContext = require("./fork-context"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Adds given segments into the `dest` array. - * If the `others` array does not includes the given segments, adds to the `all` - * array as well. - * - * This adds only reachable and used segments. - * - * @param {CodePathSegment[]} dest - A destination array (`returnedSegments` or `thrownSegments`). - * @param {CodePathSegment[]} others - Another destination array (`returnedSegments` or `thrownSegments`). - * @param {CodePathSegment[]} all - The unified destination array (`finalSegments`). - * @param {CodePathSegment[]} segments - Segments to add. - * @returns {void} - */ -function addToReturnedOrThrown(dest, others, all, segments) { - for (let i = 0; i < segments.length; ++i) { - const segment = segments[i]; - - dest.push(segment); - if (others.indexOf(segment) === -1) { - all.push(segment); - } - } -} - -/** - * Gets a loop-context for a `continue` statement. - * - * @param {CodePathState} state - A state to get. - * @param {string} label - The label of a `continue` statement. - * @returns {LoopContext} A loop-context for a `continue` statement. - */ -function getContinueContext(state, label) { - if (!label) { - return state.loopContext; - } - - let context = state.loopContext; - - while (context) { - if (context.label === label) { - return context; - } - context = context.upper; - } - - /* istanbul ignore next: foolproof (syntax error) */ - return null; -} - -/** - * Gets a context for a `break` statement. - * - * @param {CodePathState} state - A state to get. - * @param {string} label - The label of a `break` statement. - * @returns {LoopContext|SwitchContext} A context for a `break` statement. - */ -function getBreakContext(state, label) { - let context = state.breakContext; - - while (context) { - if (label ? context.label === label : context.breakable) { - return context; - } - context = context.upper; - } - - /* istanbul ignore next: foolproof (syntax error) */ - return null; -} - -/** - * Gets a context for a `return` statement. - * - * @param {CodePathState} state - A state to get. - * @returns {TryContext|CodePathState} A context for a `return` statement. - */ -function getReturnContext(state) { - let context = state.tryContext; - - while (context) { - if (context.hasFinalizer && context.position !== "finally") { - return context; - } - context = context.upper; - } - - return state; -} - -/** - * Gets a context for a `throw` statement. - * - * @param {CodePathState} state - A state to get. - * @returns {TryContext|CodePathState} A context for a `throw` statement. - */ -function getThrowContext(state) { - let context = state.tryContext; - - while (context) { - if (context.position === "try" || - (context.hasFinalizer && context.position === "catch") - ) { - return context; - } - context = context.upper; - } - - return state; -} - -/** - * Removes a given element from a given array. - * - * @param {any[]} xs - An array to remove the specific element. - * @param {any} x - An element to be removed. - * @returns {void} - */ -function remove(xs, x) { - xs.splice(xs.indexOf(x), 1); -} - -/** - * Disconnect given segments. - * - * This is used in a process for switch statements. - * If there is the "default" chunk before other cases, the order is different - * between node's and running's. - * - * @param {CodePathSegment[]} prevSegments - Forward segments to disconnect. - * @param {CodePathSegment[]} nextSegments - Backward segments to disconnect. - * @returns {void} - */ -function removeConnection(prevSegments, nextSegments) { - for (let i = 0; i < prevSegments.length; ++i) { - const prevSegment = prevSegments[i]; - const nextSegment = nextSegments[i]; - - remove(prevSegment.nextSegments, nextSegment); - remove(prevSegment.allNextSegments, nextSegment); - remove(nextSegment.prevSegments, prevSegment); - remove(nextSegment.allPrevSegments, prevSegment); - } -} - -/** - * Creates looping path. - * - * @param {CodePathState} state - The instance. - * @param {CodePathSegment[]} unflattenedFromSegments - Segments which are source. - * @param {CodePathSegment[]} unflattenedToSegments - Segments which are destination. - * @returns {void} - */ -function makeLooped(state, unflattenedFromSegments, unflattenedToSegments) { - const fromSegments = CodePathSegment.flattenUnusedSegments(unflattenedFromSegments); - const toSegments = CodePathSegment.flattenUnusedSegments(unflattenedToSegments); - - const end = Math.min(fromSegments.length, toSegments.length); - - for (let i = 0; i < end; ++i) { - const fromSegment = fromSegments[i]; - const toSegment = toSegments[i]; - - if (toSegment.reachable) { - fromSegment.nextSegments.push(toSegment); - } - if (fromSegment.reachable) { - toSegment.prevSegments.push(fromSegment); - } - fromSegment.allNextSegments.push(toSegment); - toSegment.allPrevSegments.push(fromSegment); - - if (toSegment.allPrevSegments.length >= 2) { - CodePathSegment.markPrevSegmentAsLooped(toSegment, fromSegment); - } - - state.notifyLooped(fromSegment, toSegment); - } -} - -/** - * Finalizes segments of `test` chunk of a ForStatement. - * - * - Adds `false` paths to paths which are leaving from the loop. - * - Sets `true` paths to paths which go to the body. - * - * @param {LoopContext} context - A loop context to modify. - * @param {ChoiceContext} choiceContext - A choice context of this loop. - * @param {CodePathSegment[]} head - The current head paths. - * @returns {void} - */ -function finalizeTestSegmentsOfFor(context, choiceContext, head) { - if (!choiceContext.processed) { - choiceContext.trueForkContext.add(head); - choiceContext.falseForkContext.add(head); - } - - if (context.test !== true) { - context.brokenForkContext.addAll(choiceContext.falseForkContext); - } - context.endOfTestSegments = choiceContext.trueForkContext.makeNext(0, -1); -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -/** - * A class which manages state to analyze code paths. - */ -class 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. - * @type {CodePathSegment[]} - */ - get headSegments() { - return this.forkContext.head; - } - - /** - * The parent forking context. - * This is used for the root of new forks. - * @type {ForkContext} - */ - get parentForkContext() { - const current = this.forkContext; - - return current && current.upper; - } - - /** - * Creates and stacks new forking context. - * - * @param {boolean} forkLeavingPath - A flag which shows being in a - * "finally" block. - * @returns {ForkContext} The created context. - */ - pushForkContext(forkLeavingPath) { - this.forkContext = ForkContext.newEmpty( - this.forkContext, - forkLeavingPath - ); - - return this.forkContext; - } - - /** - * Pops and merges the last forking context. - * @returns {ForkContext} The last context. - */ - popForkContext() { - const lastContext = this.forkContext; - - this.forkContext = lastContext.upper; - this.forkContext.replaceHead(lastContext.makeNext(0, -1)); - - return lastContext; - } - - /** - * Creates a new path. - * @returns {void} - */ - forkPath() { - this.forkContext.add(this.parentForkContext.makeNext(-1, -1)); - } - - /** - * Creates a bypass path. - * This is used for such as IfStatement which does not have "else" chunk. - * - * @returns {void} - */ - forkBypassPath() { - this.forkContext.add(this.parentForkContext.head); - } - - //-------------------------------------------------------------------------- - // ConditionalExpression, LogicalExpression, IfStatement - //-------------------------------------------------------------------------- - - /** - * Creates a context for ConditionalExpression, LogicalExpression, - * IfStatement, WhileStatement, DoWhileStatement, or ForStatement. - * - * LogicalExpressions have cases that it goes different paths between the - * `true` case and the `false` case. - * - * For Example: - * - * if (a || b) { - * foo(); - * } else { - * bar(); - * } - * - * In this case, `b` is evaluated always in the code path of the `else` - * block, but it's not so in the code path of the `if` block. - * So there are 3 paths. - * - * a -> foo(); - * a -> b -> foo(); - * a -> b -> bar(); - * - * @param {string} kind - A kind string. - * If the new context is LogicalExpression's, this is `"&&"` or `"||"`. - * If it's IfStatement's or ConditionalExpression's, this is `"test"`. - * Otherwise, this is `"loop"`. - * @param {boolean} isForkingAsResult - A flag that shows that goes different - * paths between `true` and `false`. - * @returns {void} - */ - pushChoiceContext(kind, isForkingAsResult) { - this.choiceContext = { - upper: this.choiceContext, - kind, - isForkingAsResult, - trueForkContext: ForkContext.newEmpty(this.forkContext), - falseForkContext: ForkContext.newEmpty(this.forkContext), - processed: false - }; - } - - /** - * Pops the last choice context and finalizes it. - * - * @returns {ChoiceContext} The popped context. - */ - popChoiceContext() { - const context = this.choiceContext; - - this.choiceContext = context.upper; - - const forkContext = this.forkContext; - const headSegments = forkContext.head; - - switch (context.kind) { - case "&&": - case "||": - - /* - * If any result were not transferred from child contexts, - * this sets the head segments to both cases. - * The head segments are the path of the right-hand operand. - */ - if (!context.processed) { - context.trueForkContext.add(headSegments); - context.falseForkContext.add(headSegments); - } - - /* - * Transfers results to upper context if this context is in - * test chunk. - */ - if (context.isForkingAsResult) { - const parentContext = this.choiceContext; - - parentContext.trueForkContext.addAll(context.trueForkContext); - parentContext.falseForkContext.addAll(context.falseForkContext); - parentContext.processed = true; - - return context; - } - - break; - - case "test": - if (!context.processed) { - - /* - * The head segments are the path of the `if` block here. - * Updates the `true` path with the end of the `if` block. - */ - context.trueForkContext.clear(); - context.trueForkContext.add(headSegments); - } else { - - /* - * The head segments are the path of the `else` block here. - * Updates the `false` path with the end of the `else` - * block. - */ - context.falseForkContext.clear(); - context.falseForkContext.add(headSegments); - } - - break; - - case "loop": - - /* - * Loops are addressed in popLoopContext(). - * This is called from popLoopContext(). - */ - return context; - - /* istanbul ignore next */ - default: - throw new Error("unreachable"); - } - - // Merges all paths. - const prevForkContext = context.trueForkContext; - - prevForkContext.addAll(context.falseForkContext); - forkContext.replaceHead(prevForkContext.makeNext(0, -1)); - - return context; - } - - /** - * Makes a code path segment of the right-hand operand of a logical - * expression. - * - * @returns {void} - */ - makeLogicalRight() { - const context = this.choiceContext; - const forkContext = this.forkContext; - - if (context.processed) { - - /* - * This got segments already from the child choice context. - * Creates the next path from own true/false fork context. - */ - const prevForkContext = - context.kind === "&&" ? context.trueForkContext - /* kind === "||" */ : context.falseForkContext; - - forkContext.replaceHead(prevForkContext.makeNext(0, -1)); - prevForkContext.clear(); - - context.processed = false; - } else { - - /* - * This did not get segments from the child choice context. - * So addresses the head segments. - * The head segments are the path of the left-hand operand. - */ - if (context.kind === "&&") { - - // The path does short-circuit if false. - context.falseForkContext.add(forkContext.head); - } else { - - // The path does short-circuit if true. - context.trueForkContext.add(forkContext.head); - } - - forkContext.replaceHead(forkContext.makeNext(-1, -1)); - } - } - - /** - * Makes a code path segment of the `if` block. - * - * @returns {void} - */ - makeIfConsequent() { - const context = this.choiceContext; - const forkContext = this.forkContext; - - /* - * If any result were not transferred from child contexts, - * this sets the head segments to both cases. - * The head segments are the path of the test expression. - */ - if (!context.processed) { - context.trueForkContext.add(forkContext.head); - context.falseForkContext.add(forkContext.head); - } - - context.processed = false; - - // Creates new path from the `true` case. - forkContext.replaceHead( - context.trueForkContext.makeNext(0, -1) - ); - } - - /** - * Makes a code path segment of the `else` block. - * - * @returns {void} - */ - makeIfAlternate() { - const context = this.choiceContext; - const forkContext = this.forkContext; - - /* - * The head segments are the path of the `if` block. - * Updates the `true` path with the end of the `if` block. - */ - context.trueForkContext.clear(); - context.trueForkContext.add(forkContext.head); - context.processed = true; - - // Creates new path from the `false` case. - forkContext.replaceHead( - context.falseForkContext.makeNext(0, -1) - ); - } - - //-------------------------------------------------------------------------- - // SwitchStatement - //-------------------------------------------------------------------------- - - /** - * Creates a context object of SwitchStatement and stacks it. - * - * @param {boolean} hasCase - `true` if the switch statement has one or more - * case parts. - * @param {string|null} label - The label text. - * @returns {void} - */ - pushSwitchContext(hasCase, label) { - this.switchContext = { - upper: this.switchContext, - hasCase, - defaultSegments: null, - defaultBodySegments: null, - foundDefault: false, - lastIsDefault: false, - countForks: 0 - }; - - this.pushBreakContext(true, label); - } - - /** - * Pops the last context of SwitchStatement and finalizes it. - * - * - Disposes all forking stack for `case` and `default`. - * - Creates the next code path segment from `context.brokenForkContext`. - * - If the last `SwitchCase` node is not a `default` part, creates a path - * to the `default` body. - * - * @returns {void} - */ - popSwitchContext() { - const context = this.switchContext; - - this.switchContext = context.upper; - - const forkContext = this.forkContext; - const brokenForkContext = this.popBreakContext().brokenForkContext; - - if (context.countForks === 0) { - - /* - * When there is only one `default` chunk and there is one or more - * `break` statements, even if forks are nothing, it needs to merge - * those. - */ - if (!brokenForkContext.empty) { - brokenForkContext.add(forkContext.makeNext(-1, -1)); - forkContext.replaceHead(brokenForkContext.makeNext(0, -1)); - } - - return; - } - - const lastSegments = forkContext.head; - - this.forkBypassPath(); - const lastCaseSegments = forkContext.head; - - /* - * `brokenForkContext` is used to make the next segment. - * It must add the last segment into `brokenForkContext`. - */ - brokenForkContext.add(lastSegments); - - /* - * A path which is failed in all case test should be connected to path - * of `default` chunk. - */ - if (!context.lastIsDefault) { - if (context.defaultBodySegments) { - - /* - * Remove a link from `default` label to its chunk. - * It's false route. - */ - removeConnection(context.defaultSegments, context.defaultBodySegments); - makeLooped(this, lastCaseSegments, context.defaultBodySegments); - } else { - - /* - * It handles the last case body as broken if `default` chunk - * does not exist. - */ - brokenForkContext.add(lastCaseSegments); - } - } - - // Pops the segment context stack until the entry segment. - for (let i = 0; i < context.countForks; ++i) { - this.forkContext = this.forkContext.upper; - } - - /* - * Creates a path from all brokenForkContext paths. - * This is a path after switch statement. - */ - this.forkContext.replaceHead(brokenForkContext.makeNext(0, -1)); - } - - /** - * Makes a code path segment for a `SwitchCase` node. - * - * @param {boolean} isEmpty - `true` if the body is empty. - * @param {boolean} isDefault - `true` if the body is the default case. - * @returns {void} - */ - makeSwitchCaseBody(isEmpty, isDefault) { - const context = this.switchContext; - - if (!context.hasCase) { - return; - } - - /* - * Merge forks. - * The parent fork context has two segments. - * Those are from the current case and the body of the previous case. - */ - const parentForkContext = this.forkContext; - const forkContext = this.pushForkContext(); - - forkContext.add(parentForkContext.makeNext(0, -1)); - - /* - * Save `default` chunk info. - * If the `default` label is not at the last, we must make a path from - * the last `case` to the `default` chunk. - */ - if (isDefault) { - context.defaultSegments = parentForkContext.head; - if (isEmpty) { - context.foundDefault = true; - } else { - context.defaultBodySegments = forkContext.head; - } - } else { - if (!isEmpty && context.foundDefault) { - context.foundDefault = false; - context.defaultBodySegments = forkContext.head; - } - } - - context.lastIsDefault = isDefault; - context.countForks += 1; - } - - //-------------------------------------------------------------------------- - // TryStatement - //-------------------------------------------------------------------------- - - /** - * Creates a context object of TryStatement and stacks it. - * - * @param {boolean} hasFinalizer - `true` if the try statement has a - * `finally` block. - * @returns {void} - */ - pushTryContext(hasFinalizer) { - this.tryContext = { - upper: this.tryContext, - position: "try", - hasFinalizer, - - returnedForkContext: hasFinalizer - ? ForkContext.newEmpty(this.forkContext) - : null, - - thrownForkContext: ForkContext.newEmpty(this.forkContext), - lastOfTryIsReachable: false, - lastOfCatchIsReachable: false - }; - } - - /** - * Pops the last context of TryStatement and finalizes it. - * - * @returns {void} - */ - popTryContext() { - const context = this.tryContext; - - this.tryContext = context.upper; - - if (context.position === "catch") { - - // Merges two paths from the `try` block and `catch` block merely. - this.popForkContext(); - return; - } - - /* - * The following process is executed only when there is the `finally` - * block. - */ - - const returned = context.returnedForkContext; - const thrown = context.thrownForkContext; - - if (returned.empty && thrown.empty) { - return; - } - - // Separate head to normal paths and leaving paths. - const headSegments = this.forkContext.head; - - this.forkContext = this.forkContext.upper; - const normalSegments = headSegments.slice(0, headSegments.length / 2 | 0); - const leavingSegments = headSegments.slice(headSegments.length / 2 | 0); - - // Forwards the leaving path to upper contexts. - if (!returned.empty) { - getReturnContext(this).returnedForkContext.add(leavingSegments); - } - if (!thrown.empty) { - getThrowContext(this).thrownForkContext.add(leavingSegments); - } - - // Sets the normal path as the next. - this.forkContext.replaceHead(normalSegments); - - /* - * If both paths of the `try` block and the `catch` block are - * unreachable, the next path becomes unreachable as well. - */ - if (!context.lastOfTryIsReachable && !context.lastOfCatchIsReachable) { - this.forkContext.makeUnreachable(); - } - } - - /** - * Makes a code path segment for a `catch` block. - * - * @returns {void} - */ - makeCatchBlock() { - const context = this.tryContext; - const forkContext = this.forkContext; - const thrown = context.thrownForkContext; - - // Update state. - context.position = "catch"; - context.thrownForkContext = ForkContext.newEmpty(forkContext); - context.lastOfTryIsReachable = forkContext.reachable; - - // Merge thrown paths. - thrown.add(forkContext.head); - const thrownSegments = thrown.makeNext(0, -1); - - // Fork to a bypass and the merged thrown path. - this.pushForkContext(); - this.forkBypassPath(); - this.forkContext.add(thrownSegments); - } - - /** - * Makes a code path segment for a `finally` block. - * - * In the `finally` block, parallel paths are created. The parallel paths - * are used as leaving-paths. The leaving-paths are paths from `return` - * statements and `throw` statements in a `try` block or a `catch` block. - * - * @returns {void} - */ - makeFinallyBlock() { - const context = this.tryContext; - let forkContext = this.forkContext; - const returned = context.returnedForkContext; - const thrown = context.thrownForkContext; - const headOfLeavingSegments = forkContext.head; - - // Update state. - if (context.position === "catch") { - - // Merges two paths from the `try` block and `catch` block. - this.popForkContext(); - forkContext = this.forkContext; - - context.lastOfCatchIsReachable = forkContext.reachable; - } else { - context.lastOfTryIsReachable = forkContext.reachable; - } - context.position = "finally"; - - if (returned.empty && thrown.empty) { - - // This path does not leave. - return; - } - - /* - * Create a parallel segment from merging returned and thrown. - * This segment will leave at the end of this finally block. - */ - const segments = forkContext.makeNext(-1, -1); - - for (let i = 0; i < forkContext.count; ++i) { - const prevSegsOfLeavingSegment = [headOfLeavingSegments[i]]; - - for (let j = 0; j < returned.segmentsList.length; ++j) { - prevSegsOfLeavingSegment.push(returned.segmentsList[j][i]); - } - for (let j = 0; j < thrown.segmentsList.length; ++j) { - prevSegsOfLeavingSegment.push(thrown.segmentsList[j][i]); - } - - segments.push( - CodePathSegment.newNext( - this.idGenerator.next(), - prevSegsOfLeavingSegment - ) - ); - } - - this.pushForkContext(true); - this.forkContext.add(segments); - } - - /** - * Makes a code path segment from the first throwable node to the `catch` - * block or the `finally` block. - * - * @returns {void} - */ - makeFirstThrowablePathInTryBlock() { - const forkContext = this.forkContext; - - if (!forkContext.reachable) { - return; - } - - const context = getThrowContext(this); - - if (context === this || - context.position !== "try" || - !context.thrownForkContext.empty - ) { - return; - } - - context.thrownForkContext.add(forkContext.head); - forkContext.replaceHead(forkContext.makeNext(-1, -1)); - } - - //-------------------------------------------------------------------------- - // Loop Statements - //-------------------------------------------------------------------------- - - /** - * Creates a context object of a loop statement and stacks it. - * - * @param {string} type - The type of the node which was triggered. One of - * `WhileStatement`, `DoWhileStatement`, `ForStatement`, `ForInStatement`, - * and `ForStatement`. - * @param {string|null} label - A label of the node which was triggered. - * @returns {void} - */ - pushLoopContext(type, label) { - const forkContext = this.forkContext; - const breakContext = this.pushBreakContext(true, label); - - switch (type) { - case "WhileStatement": - this.pushChoiceContext("loop", false); - this.loopContext = { - upper: this.loopContext, - type, - label, - test: void 0, - continueDestSegments: null, - brokenForkContext: breakContext.brokenForkContext - }; - break; - - case "DoWhileStatement": - this.pushChoiceContext("loop", false); - this.loopContext = { - upper: this.loopContext, - type, - label, - test: void 0, - entrySegments: null, - continueForkContext: ForkContext.newEmpty(forkContext), - brokenForkContext: breakContext.brokenForkContext - }; - break; - - case "ForStatement": - this.pushChoiceContext("loop", false); - this.loopContext = { - upper: this.loopContext, - type, - label, - test: void 0, - endOfInitSegments: null, - testSegments: null, - endOfTestSegments: null, - updateSegments: null, - endOfUpdateSegments: null, - continueDestSegments: null, - brokenForkContext: breakContext.brokenForkContext - }; - break; - - case "ForInStatement": - case "ForOfStatement": - this.loopContext = { - upper: this.loopContext, - type, - label, - prevSegments: null, - leftSegments: null, - endOfLeftSegments: null, - continueDestSegments: null, - brokenForkContext: breakContext.brokenForkContext - }; - break; - - /* istanbul ignore next */ - default: - throw new Error(`unknown type: "${type}"`); - } - } - - /** - * Pops the last context of a loop statement and finalizes it. - * - * @returns {void} - */ - popLoopContext() { - const context = this.loopContext; - - this.loopContext = context.upper; - - const forkContext = this.forkContext; - const brokenForkContext = this.popBreakContext().brokenForkContext; - - // Creates a looped path. - switch (context.type) { - case "WhileStatement": - case "ForStatement": - this.popChoiceContext(); - makeLooped( - this, - forkContext.head, - context.continueDestSegments - ); - break; - - case "DoWhileStatement": { - const choiceContext = this.popChoiceContext(); - - if (!choiceContext.processed) { - choiceContext.trueForkContext.add(forkContext.head); - choiceContext.falseForkContext.add(forkContext.head); - } - if (context.test !== true) { - brokenForkContext.addAll(choiceContext.falseForkContext); - } - - // `true` paths go to looping. - const segmentsList = choiceContext.trueForkContext.segmentsList; - - for (let i = 0; i < segmentsList.length; ++i) { - makeLooped( - this, - segmentsList[i], - context.entrySegments - ); - } - break; - } - - case "ForInStatement": - case "ForOfStatement": - brokenForkContext.add(forkContext.head); - makeLooped( - this, - forkContext.head, - context.leftSegments - ); - break; - - /* istanbul ignore next */ - default: - throw new Error("unreachable"); - } - - // Go next. - if (brokenForkContext.empty) { - forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); - } else { - forkContext.replaceHead(brokenForkContext.makeNext(0, -1)); - } - } - - /** - * Makes a code path segment for the test part of a WhileStatement. - * - * @param {boolean|undefined} test - The test value (only when constant). - * @returns {void} - */ - makeWhileTest(test) { - const context = this.loopContext; - const forkContext = this.forkContext; - const testSegments = forkContext.makeNext(0, -1); - - // Update state. - context.test = test; - context.continueDestSegments = testSegments; - forkContext.replaceHead(testSegments); - } - - /** - * Makes a code path segment for the body part of a WhileStatement. - * - * @returns {void} - */ - makeWhileBody() { - const context = this.loopContext; - const choiceContext = this.choiceContext; - const forkContext = this.forkContext; - - if (!choiceContext.processed) { - choiceContext.trueForkContext.add(forkContext.head); - choiceContext.falseForkContext.add(forkContext.head); - } - - // Update state. - if (context.test !== true) { - context.brokenForkContext.addAll(choiceContext.falseForkContext); - } - forkContext.replaceHead(choiceContext.trueForkContext.makeNext(0, -1)); - } - - /** - * Makes a code path segment for the body part of a DoWhileStatement. - * - * @returns {void} - */ - makeDoWhileBody() { - const context = this.loopContext; - const forkContext = this.forkContext; - const bodySegments = forkContext.makeNext(-1, -1); - - // Update state. - context.entrySegments = bodySegments; - forkContext.replaceHead(bodySegments); - } - - /** - * Makes a code path segment for the test part of a DoWhileStatement. - * - * @param {boolean|undefined} test - The test value (only when constant). - * @returns {void} - */ - makeDoWhileTest(test) { - const context = this.loopContext; - const forkContext = this.forkContext; - - context.test = test; - - // Creates paths of `continue` statements. - if (!context.continueForkContext.empty) { - context.continueForkContext.add(forkContext.head); - const testSegments = context.continueForkContext.makeNext(0, -1); - - forkContext.replaceHead(testSegments); - } - } - - /** - * Makes a code path segment for the test part of a ForStatement. - * - * @param {boolean|undefined} test - The test value (only when constant). - * @returns {void} - */ - makeForTest(test) { - const context = this.loopContext; - const forkContext = this.forkContext; - const endOfInitSegments = forkContext.head; - const testSegments = forkContext.makeNext(-1, -1); - - // Update state. - context.test = test; - context.endOfInitSegments = endOfInitSegments; - context.continueDestSegments = context.testSegments = testSegments; - forkContext.replaceHead(testSegments); - } - - /** - * Makes a code path segment for the update part of a ForStatement. - * - * @returns {void} - */ - makeForUpdate() { - const context = this.loopContext; - const choiceContext = this.choiceContext; - const forkContext = this.forkContext; - - // Make the next paths of the test. - if (context.testSegments) { - finalizeTestSegmentsOfFor( - context, - choiceContext, - forkContext.head - ); - } else { - context.endOfInitSegments = forkContext.head; - } - - // Update state. - const updateSegments = forkContext.makeDisconnected(-1, -1); - - context.continueDestSegments = context.updateSegments = updateSegments; - forkContext.replaceHead(updateSegments); - } - - /** - * Makes a code path segment for the body part of a ForStatement. - * - * @returns {void} - */ - makeForBody() { - const context = this.loopContext; - const choiceContext = this.choiceContext; - const forkContext = this.forkContext; - - // Update state. - if (context.updateSegments) { - context.endOfUpdateSegments = forkContext.head; - - // `update` -> `test` - if (context.testSegments) { - makeLooped( - this, - context.endOfUpdateSegments, - context.testSegments - ); - } - } else if (context.testSegments) { - finalizeTestSegmentsOfFor( - context, - choiceContext, - forkContext.head - ); - } else { - context.endOfInitSegments = forkContext.head; - } - - let bodySegments = context.endOfTestSegments; - - if (!bodySegments) { - - /* - * If there is not the `test` part, the `body` path comes from the - * `init` part and the `update` part. - */ - const prevForkContext = ForkContext.newEmpty(forkContext); - - prevForkContext.add(context.endOfInitSegments); - if (context.endOfUpdateSegments) { - prevForkContext.add(context.endOfUpdateSegments); - } - - bodySegments = prevForkContext.makeNext(0, -1); - } - context.continueDestSegments = context.continueDestSegments || bodySegments; - forkContext.replaceHead(bodySegments); - } - - /** - * Makes a code path segment for the left part of a ForInStatement and a - * ForOfStatement. - * - * @returns {void} - */ - makeForInOfLeft() { - const context = this.loopContext; - const forkContext = this.forkContext; - const leftSegments = forkContext.makeDisconnected(-1, -1); - - // Update state. - 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 - * ForOfStatement. - * - * @returns {void} - */ - makeForInOfRight() { - const context = this.loopContext; - const forkContext = this.forkContext; - const temp = ForkContext.newEmpty(forkContext); - - temp.add(context.prevSegments); - const rightSegments = temp.makeNext(-1, -1); - - // Update state. - context.endOfLeftSegments = forkContext.head; - forkContext.replaceHead(rightSegments); - } - - /** - * Makes a code path segment for the body part of a ForInStatement and a - * ForOfStatement. - * - * @returns {void} - */ - makeForInOfBody() { - const context = this.loopContext; - const forkContext = this.forkContext; - const temp = ForkContext.newEmpty(forkContext); - - temp.add(context.endOfLeftSegments); - const bodySegments = temp.makeNext(-1, -1); - - // Make a path: `right` -> `left`. - makeLooped(this, forkContext.head, context.leftSegments); - - // Update state. - context.brokenForkContext.add(forkContext.head); - forkContext.replaceHead(bodySegments); - } - - //-------------------------------------------------------------------------- - // Control Statements - //-------------------------------------------------------------------------- - - /** - * Creates new context for BreakStatement. - * - * @param {boolean} breakable - The flag to indicate it can break by - * an unlabeled BreakStatement. - * @param {string|null} label - The label of this context. - * @returns {Object} The new context. - */ - pushBreakContext(breakable, label) { - this.breakContext = { - upper: this.breakContext, - breakable, - label, - brokenForkContext: ForkContext.newEmpty(this.forkContext) - }; - return this.breakContext; - } - - /** - * Removes the top item of the break context stack. - * - * @returns {Object} The removed context. - */ - popBreakContext() { - const context = this.breakContext; - const forkContext = this.forkContext; - - this.breakContext = context.upper; - - // Process this context here for other than switches and loops. - if (!context.breakable) { - const brokenForkContext = context.brokenForkContext; - - if (!brokenForkContext.empty) { - brokenForkContext.add(forkContext.head); - forkContext.replaceHead(brokenForkContext.makeNext(0, -1)); - } - } - - return context; - } - - /** - * Makes a path for a `break` statement. - * - * It registers the head segment to a context of `break`. - * It makes new unreachable segment, then it set the head with the segment. - * - * @param {string} label - A label of the break statement. - * @returns {void} - */ - makeBreak(label) { - const forkContext = this.forkContext; - - if (!forkContext.reachable) { - return; - } - - const context = getBreakContext(this, label); - - /* istanbul ignore else: foolproof (syntax error) */ - if (context) { - context.brokenForkContext.add(forkContext.head); - } - - forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); - } - - /** - * Makes a path for a `continue` statement. - * - * It makes a looping path. - * It makes new unreachable segment, then it set the head with the segment. - * - * @param {string} label - A label of the continue statement. - * @returns {void} - */ - makeContinue(label) { - const forkContext = this.forkContext; - - if (!forkContext.reachable) { - return; - } - - const context = getContinueContext(this, label); - - /* istanbul ignore else: foolproof (syntax error) */ - if (context) { - if (context.continueDestSegments) { - makeLooped(this, forkContext.head, context.continueDestSegments); - - // If the context is a for-in/of loop, this effects a break also. - if (context.type === "ForInStatement" || - context.type === "ForOfStatement" - ) { - context.brokenForkContext.add(forkContext.head); - } - } else { - context.continueForkContext.add(forkContext.head); - } - } - forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); - } - - /** - * Makes a path for a `return` statement. - * - * It registers the head segment to a context of `return`. - * It makes new unreachable segment, then it set the head with the segment. - * - * @returns {void} - */ - makeReturn() { - const forkContext = this.forkContext; - - if (forkContext.reachable) { - getReturnContext(this).returnedForkContext.add(forkContext.head); - forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); - } - } - - /** - * Makes a path for a `throw` statement. - * - * It registers the head segment to a context of `throw`. - * It makes new unreachable segment, then it set the head with the segment. - * - * @returns {void} - */ - makeThrow() { - const forkContext = this.forkContext; - - if (forkContext.reachable) { - getThrowContext(this).thrownForkContext.add(forkContext.head); - forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); - } - } - - /** - * Makes the final path. - * @returns {void} - */ - makeFinal() { - const segments = this.currentSegments; - - if (segments.length > 0 && segments[0].reachable) { - this.returnedForkContext.add(segments); - } - } -} - -module.exports = CodePathState; diff --git a/tools/node_modules/eslint/lib/code-path-analysis/code-path.js b/tools/node_modules/eslint/lib/code-path-analysis/code-path.js deleted file mode 100644 index cb26ea18a3ee67..00000000000000 --- a/tools/node_modules/eslint/lib/code-path-analysis/code-path.js +++ /dev/null @@ -1,239 +0,0 @@ -/** - * @fileoverview A class of the code path. - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const CodePathState = require("./code-path-state"); -const IdGenerator = require("./id-generator"); - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -/** - * A code path. - */ -class CodePath { - - /** - * @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. - */ - constructor(id, upper, onLooped) { - - /** - * The identifier of this code path. - * Rules use it to store additional information of each rule. - * @type {string} - */ - this.id = id; - - /** - * 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) } - ); - - // Adds this into `childCodePaths` of `upper`. - if (upper) { - upper.childCodePaths.push(this); - } - } - - /** - * 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. - * @type {CodePathSegment} - */ - get initialSegment() { - return this.internal.initialSegment; - } - - /** - * Final code path segments. - * This array is a mix of `returnedSegments` and `thrownSegments`. - * @type {CodePathSegment[]} - */ - get finalSegments() { - return this.internal.finalSegments; - } - - /** - * Final code path segments which is with `return` statements. - * This array contains the last path segment if it's reachable. - * Since the reachable last path returns `undefined`. - * @type {CodePathSegment[]} - */ - get returnedSegments() { - return this.internal.returnedForkContext; - } - - /** - * Final code path segments which is with `throw` statements. - * @type {CodePathSegment[]} - */ - get thrownSegments() { - return this.internal.thrownForkContext; - } - - /** - * Current code path segments. - * @type {CodePathSegment[]} - */ - get currentSegments() { - return this.internal.currentSegments; - } - - /** - * Traverses all segments in this code path. - * - * codePath.traverseSegments(function(segment, controller) { - * // do something. - * }); - * - * This method enumerates segments in order from the head. - * - * The `controller` object has two methods. - * - * - `controller.skip()` - Skip the following segments in this branch. - * - `controller.break()` - Skip all following segments. - * - * @param {Object} [options] - Omittable. - * @param {CodePathSegment} [options.first] - The first segment to traverse. - * @param {CodePathSegment} [options.last] - The last segment to traverse. - * @param {Function} callback - A callback function. - * @returns {void} - */ - traverseSegments(options, callback) { - let resolvedOptions; - let resolvedCallback; - - if (typeof options === "function") { - resolvedCallback = options; - resolvedOptions = {}; - } else { - resolvedOptions = options || {}; - resolvedCallback = callback; - } - - const startSegment = resolvedOptions.first || this.internal.initialSegment; - const lastSegment = resolvedOptions.last; - - let item = null; - let index = 0; - let end = 0; - let segment = null; - const visited = Object.create(null); - const stack = [[startSegment, 0]]; - let skippedSegment = null; - let broken = false; - const controller = { - skip() { - if (stack.length <= 1) { - broken = true; - } else { - skippedSegment = stack[stack.length - 2][0]; - } - }, - break() { - broken = true; - } - }; - - /** - * Checks a given previous segment has been visited. - * @param {CodePathSegment} prevSegment - A previous segment to check. - * @returns {boolean} `true` if the segment has been visited. - */ - function isVisited(prevSegment) { - return ( - visited[prevSegment.id] || - segment.isLoopedPrevSegment(prevSegment) - ); - } - - while (stack.length > 0) { - item = stack[stack.length - 1]; - segment = item[0]; - index = item[1]; - - if (index === 0) { - - // Skip if this segment has been visited already. - if (visited[segment.id]) { - stack.pop(); - continue; - } - - // Skip if all previous segments have not been visited. - if (segment !== startSegment && - segment.prevSegments.length > 0 && - !segment.prevSegments.every(isVisited) - ) { - stack.pop(); - continue; - } - - // Reset the flag of skipping if all branches have been skipped. - if (skippedSegment && segment.prevSegments.indexOf(skippedSegment) !== -1) { - skippedSegment = null; - } - visited[segment.id] = true; - - // Call the callback when the first time. - if (!skippedSegment) { - resolvedCallback.call(this, segment, controller); - if (segment === lastSegment) { - controller.skip(); - } - if (broken) { - break; - } - } - } - - // Update the stack. - end = segment.nextSegments.length - 1; - if (index < end) { - item[1] += 1; - stack.push([segment.nextSegments[index], 0]); - } else if (index === end) { - item[0] = segment.nextSegments[index]; - item[1] = 0; - } else { - stack.pop(); - } - } - } -} - -module.exports = CodePath; diff --git a/tools/node_modules/eslint/lib/code-path-analysis/debug-helpers.js b/tools/node_modules/eslint/lib/code-path-analysis/debug-helpers.js deleted file mode 100644 index 9af985ce85f56e..00000000000000 --- a/tools/node_modules/eslint/lib/code-path-analysis/debug-helpers.js +++ /dev/null @@ -1,200 +0,0 @@ -/** - * @fileoverview Helpers to debug for code path analysis. - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const debug = require("debug")("eslint:code-path"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Gets id of a given segment. - * @param {CodePathSegment} segment - A segment to get. - * @returns {string} Id of the segment. - */ -/* istanbul ignore next */ -function getId(segment) { // eslint-disable-line require-jsdoc - return segment.id + (segment.reachable ? "" : "!"); -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = { - - /** - * A flag that debug dumping is enabled or not. - * @type {boolean} - */ - enabled: debug.enabled, - - /** - * Dumps given objects. - * - * @param {...any} args - objects to dump. - * @returns {void} - */ - dump: debug, - - /** - * Dumps the current analyzing state. - * - * @param {ASTNode} node - A node to dump. - * @param {CodePathState} state - A state to dump. - * @param {boolean} leaving - A flag whether or not it's leaving - * @returns {void} - */ - dumpState: !debug.enabled ? debug : /* istanbul ignore next */ function(node, state, leaving) { - for (let i = 0; i < state.currentSegments.length; ++i) { - const segInternal = state.currentSegments[i].internal; - - if (leaving) { - segInternal.exitNodes.push(node); - } else { - segInternal.nodes.push(node); - } - } - - debug([ - `${state.currentSegments.map(getId).join(",")})`, - `${node.type}${leaving ? ":exit" : ""}` - ].join(" ")); - }, - - /** - * Dumps a DOT code of a given code path. - * The DOT code can be visialized with Graphvis. - * - * @param {CodePath} codePath - A code path to dump. - * @returns {void} - * @see http://www.graphviz.org - * @see http://www.webgraphviz.com - */ - dumpDot: !debug.enabled ? debug : /* istanbul ignore next */ function(codePath) { - let text = - "\n" + - "digraph {\n" + - "node[shape=box,style=\"rounded,filled\",fillcolor=white];\n" + - "initial[label=\"\",shape=circle,style=filled,fillcolor=black,width=0.25,height=0.25];\n"; - - if (codePath.returnedSegments.length > 0) { - text += "final[label=\"\",shape=doublecircle,style=filled,fillcolor=black,width=0.25,height=0.25];\n"; - } - if (codePath.thrownSegments.length > 0) { - text += "thrown[label=\"✘\",shape=circle,width=0.3,height=0.3,fixedsize];\n"; - } - - const traceMap = Object.create(null); - const arrows = this.makeDotArrows(codePath, traceMap); - - for (const id in traceMap) { // eslint-disable-line guard-for-in - const segment = traceMap[id]; - - text += `${id}[`; - - if (segment.reachable) { - text += "label=\""; - } else { - text += "style=\"rounded,dashed,filled\",fillcolor=\"#FF9800\",label=\"<>\\n"; - } - - if (segment.internal.nodes.length > 0 || segment.internal.exitNodes.length > 0) { - text += [].concat( - segment.internal.nodes.map(node => { - switch (node.type) { - case "Identifier": return `${node.type} (${node.name})`; - case "Literal": return `${node.type} (${node.value})`; - default: return node.type; - } - }), - segment.internal.exitNodes.map(node => { - switch (node.type) { - case "Identifier": return `${node.type}:exit (${node.name})`; - case "Literal": return `${node.type}:exit (${node.value})`; - default: return `${node.type}:exit`; - } - }) - ).join("\\n"); - } else { - text += "????"; - } - - text += "\"];\n"; - } - - text += `${arrows}\n`; - text += "}"; - debug("DOT", text); - }, - - /** - * Makes a DOT code of a given code path. - * The DOT code can be visialized with Graphvis. - * - * @param {CodePath} codePath - A code path to make DOT. - * @param {Object} traceMap - Optional. A map to check whether or not segments had been done. - * @returns {string} A DOT code of the code path. - */ - makeDotArrows(codePath, traceMap) { - const stack = [[codePath.initialSegment, 0]]; - const done = traceMap || Object.create(null); - let lastId = codePath.initialSegment.id; - let text = `initial->${codePath.initialSegment.id}`; - - while (stack.length > 0) { - const item = stack.pop(); - const segment = item[0]; - const index = item[1]; - - if (done[segment.id] && index === 0) { - continue; - } - done[segment.id] = segment; - - const nextSegment = segment.allNextSegments[index]; - - if (!nextSegment) { - continue; - } - - if (lastId === segment.id) { - text += `->${nextSegment.id}`; - } else { - text += `;\n${segment.id}->${nextSegment.id}`; - } - lastId = nextSegment.id; - - stack.unshift([segment, 1 + index]); - stack.push([nextSegment, 0]); - } - - codePath.returnedSegments.forEach(finalSegment => { - if (lastId === finalSegment.id) { - text += "->final"; - } else { - text += `;\n${finalSegment.id}->final`; - } - lastId = null; - }); - - codePath.thrownSegments.forEach(finalSegment => { - if (lastId === finalSegment.id) { - text += "->thrown"; - } else { - text += `;\n${finalSegment.id}->thrown`; - } - lastId = null; - }); - - return `${text};`; - } -}; diff --git a/tools/node_modules/eslint/lib/code-path-analysis/fork-context.js b/tools/node_modules/eslint/lib/code-path-analysis/fork-context.js deleted file mode 100644 index 939ed2d0d9af11..00000000000000 --- a/tools/node_modules/eslint/lib/code-path-analysis/fork-context.js +++ /dev/null @@ -1,260 +0,0 @@ -/** - * @fileoverview A class to operate forking. - * - * This is state of forking. - * This has a fork list and manages it. - * - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const assert = require("assert"), - CodePathSegment = require("./code-path-segment"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Gets whether or not a given segment is reachable. - * - * @param {CodePathSegment} segment - A segment to get. - * @returns {boolean} `true` if the segment is reachable. - */ -function isReachable(segment) { - return segment.reachable; -} - -/** - * Creates new segments from the specific range of `context.segmentsList`. - * - * When `context.segmentsList` is `[[a, b], [c, d], [e, f]]`, `begin` is `0`, and - * `end` is `-1`, this creates `[g, h]`. This `g` is from `a`, `c`, and `e`. - * This `h` is from `b`, `d`, and `f`. - * - * @param {ForkContext} context - An instance. - * @param {number} begin - The first index of the previous segments. - * @param {number} end - The last index of the previous segments. - * @param {Function} create - A factory function of new segments. - * @returns {CodePathSegment[]} New segments. - */ -function makeSegments(context, begin, end, create) { - const list = context.segmentsList; - - const normalizedBegin = begin >= 0 ? begin : list.length + begin; - const normalizedEnd = end >= 0 ? end : list.length + end; - - const segments = []; - - for (let i = 0; i < context.count; ++i) { - const allPrevSegments = []; - - for (let j = normalizedBegin; j <= normalizedEnd; ++j) { - allPrevSegments.push(list[j][i]); - } - - segments.push(create(context.idGenerator.next(), allPrevSegments)); - } - - return segments; -} - -/** - * `segments` becomes doubly in a `finally` block. Then if a code path exits by a - * control statement (such as `break`, `continue`) from the `finally` block, the - * destination's segments may be half of the source segments. In that case, this - * merges segments. - * - * @param {ForkContext} context - An instance. - * @param {CodePathSegment[]} segments - Segments to merge. - * @returns {CodePathSegment[]} The merged segments. - */ -function mergeExtraSegments(context, segments) { - let currentSegments = segments; - - while (currentSegments.length > context.count) { - const merged = []; - - for (let i = 0, length = currentSegments.length / 2 | 0; i < length; ++i) { - merged.push(CodePathSegment.newNext( - context.idGenerator.next(), - [currentSegments[i], currentSegments[i + length]] - )); - } - currentSegments = merged; - } - return currentSegments; -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -/** - * A class to manage forking. - */ -class 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. - * @type {CodePathSegment[]} - */ - get head() { - const list = this.segmentsList; - - return list.length === 0 ? [] : list[list.length - 1]; - } - - /** - * A flag which shows empty. - * @type {boolean} - */ - get empty() { - return this.segmentsList.length === 0; - } - - /** - * A flag which shows reachable. - * @type {boolean} - */ - get reachable() { - const segments = this.head; - - return segments.length > 0 && segments.some(isReachable); - } - - /** - * Creates new segments from this context. - * - * @param {number} begin - The first index of previous segments. - * @param {number} end - The last index of previous segments. - * @returns {CodePathSegment[]} New segments. - */ - makeNext(begin, end) { - return makeSegments(this, begin, end, CodePathSegment.newNext); - } - - /** - * Creates new segments from this context. - * The new segments is always unreachable. - * - * @param {number} begin - The first index of previous segments. - * @param {number} end - The last index of previous segments. - * @returns {CodePathSegment[]} New segments. - */ - makeUnreachable(begin, end) { - return makeSegments(this, begin, end, CodePathSegment.newUnreachable); - } - - /** - * Creates new segments from this context. - * The new segments don't have connections for previous segments. - * But these inherit the reachable flag from this context. - * - * @param {number} begin - The first index of previous segments. - * @param {number} end - The last index of previous segments. - * @returns {CodePathSegment[]} New segments. - */ - makeDisconnected(begin, end) { - return makeSegments(this, begin, end, CodePathSegment.newDisconnected); - } - - /** - * Adds segments into this context. - * The added segments become the head. - * - * @param {CodePathSegment[]} segments - Segments to add. - * @returns {void} - */ - add(segments) { - assert(segments.length >= this.count, `${segments.length} >= ${this.count}`); - - this.segmentsList.push(mergeExtraSegments(this, segments)); - } - - /** - * Replaces the head segments with given segments. - * The current head segments are removed. - * - * @param {CodePathSegment[]} segments - Segments to add. - * @returns {void} - */ - replaceHead(segments) { - 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. - * - * @param {ForkContext} context - A fork context to add. - * @returns {void} - */ - addAll(context) { - assert(context.count === this.count); - - const source = context.segmentsList; - - for (let i = 0; i < source.length; ++i) { - this.segmentsList.push(source[i]); - } - } - - /** - * Clears all secments in this context. - * - * @returns {void} - */ - clear() { - this.segmentsList = []; - } - - /** - * 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())]); - - 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. - */ - static newEmpty(parentContext, forkLeavingPath) { - return new ForkContext( - parentContext.idGenerator, - parentContext, - (forkLeavingPath ? 2 : 1) * parentContext.count - ); - } -} - -module.exports = ForkContext; diff --git a/tools/node_modules/eslint/lib/code-path-analysis/id-generator.js b/tools/node_modules/eslint/lib/code-path-analysis/id-generator.js deleted file mode 100644 index 062058ddc12639..00000000000000 --- a/tools/node_modules/eslint/lib/code-path-analysis/id-generator.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * @fileoverview A class of identifiers generator for code path segments. - * - * Each rule uses the identifier of code path segments to store additional - * information of the code path. - * - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -/** - * A generator for unique ids. - */ -class IdGenerator { - - /** - * @param {string} prefix - Optional. A prefix of generated ids. - */ - constructor(prefix) { - this.prefix = String(prefix); - this.n = 0; - } - - /** - * 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/node_modules/eslint/lib/config.js b/tools/node_modules/eslint/lib/config.js deleted file mode 100644 index 9c8438859ea57f..00000000000000 --- a/tools/node_modules/eslint/lib/config.js +++ /dev/null @@ -1,377 +0,0 @@ -/** - * @fileoverview Responsible for loading config files - * @author Seth McLaughlin - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const path = require("path"), - os = require("os"), - ConfigOps = require("./config/config-ops"), - ConfigFile = require("./config/config-file"), - ConfigCache = require("./config/config-cache"), - Plugins = require("./config/plugins"), - FileFinder = require("./util/file-finder"); - -const debug = require("debug")("eslint:config"); - -//------------------------------------------------------------------------------ -// Constants -//------------------------------------------------------------------------------ - -const PERSONAL_CONFIG_DIR = os.homedir(); -const SUBCONFIG_SEP = ":"; - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Determines if any rules were explicitly passed in as options. - * @param {Object} options The options used to create our configuration. - * @returns {boolean} True if rules were passed in as options, false otherwise. - * @private - */ -function hasRules(options) { - return options.rules && Object.keys(options.rules).length > 0; -} - -/** - * Determines if a module is can be resolved. - * @param {string} moduleId The ID (name) of the module - * @returns {boolean} True if it is resolvable; False otherwise. - */ -function isResolvable(moduleId) { - try { - require.resolve(moduleId); - return true; - } catch (err) { - return false; - } -} - -//------------------------------------------------------------------------------ -// API -//------------------------------------------------------------------------------ - -/** - * Configuration class - */ -class Config { - - /** - * @param {Object} providedOptions Options to be passed in - * @param {Linter} linterContext Linter instance object - */ - constructor(providedOptions, linterContext) { - const options = providedOptions || {}; - - this.linterContext = linterContext; - this.plugins = new Plugins(linterContext.environments, linterContext.defineRule.bind(linterContext)); - - this.options = options; - this.ignore = options.ignore; - this.ignorePath = options.ignorePath; - this.parser = options.parser; - this.parserOptions = options.parserOptions || {}; - - this.configCache = new ConfigCache(); - - this.baseConfig = options.baseConfig - ? ConfigOps.merge({}, ConfigFile.loadObject(options.baseConfig, this)) - : { rules: {} }; - this.baseConfig.filePath = ""; - this.baseConfig.baseDirectory = this.options.cwd; - - this.configCache.setConfig(this.baseConfig.filePath, this.baseConfig); - this.configCache.setMergedVectorConfig(this.baseConfig.filePath, this.baseConfig); - - this.useEslintrc = (options.useEslintrc !== false); - - this.env = (options.envs || []).reduce((envs, name) => { - envs[name] = true; - return envs; - }, {}); - - /* - * 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(SUBCONFIG_SEP); - - globals[parts[0]] = (parts.length > 1 && parts[1] === "true"); - - return globals; - }, {}); - - this.loadSpecificConfig(options.configFile); - - // Empty values in configs don't merge properly - const cliConfigOptions = { - env: this.env, - rules: this.options.rules, - globals: this.globals, - parserOptions: this.parserOptions, - plugins: this.options.plugins - }; - - this.cliConfig = {}; - Object.keys(cliConfigOptions).forEach(configKey => { - const value = cliConfigOptions[configKey]; - - if (value) { - this.cliConfig[configKey] = value; - } - }); - } - - /** - * Loads the config options from a config specified on the command line. - * @param {string} [config] A shareable named config or path to a config file. - * @returns {void} - */ - loadSpecificConfig(config) { - if (config) { - debug(`Using command line config ${config}`); - const isNamedConfig = - isResolvable(config) || - isResolvable(`eslint-config-${config}`) || - config.charAt(0) === "@"; - - this.specificConfig = ConfigFile.load( - isNamedConfig ? config : path.resolve(this.options.cwd, config), - this - ); - } - } - - /** - * Gets the personal config object from user's home directory. - * @returns {Object} the personal config object (null if there is no personal config) - * @private - */ - getPersonalConfig() { - if (typeof this.personalConfig === "undefined") { - let config; - const filename = ConfigFile.getFilenameForDirectory(PERSONAL_CONFIG_DIR); - - if (filename) { - debug("Using personal config"); - config = ConfigFile.load(filename, this); - } - - this.personalConfig = config || null; - } - - return this.personalConfig; - } - - /** - * Builds a hierarchy of config objects, including the base config, all local configs from the directory tree, - * and a config file specified on the command line, if applicable. - * @param {string} directory a file in whose directory we start looking for a local config - * @returns {Object[]} The config objects, in ascending order of precedence - * @private - */ - getConfigHierarchy(directory) { - debug(`Constructing config file hierarchy for ${directory}`); - - // Step 1: Always include baseConfig - let configs = [this.baseConfig]; - - // Step 2: Add user-specified config from .eslintrc.* and package.json files - if (this.useEslintrc) { - debug("Using .eslintrc and package.json files"); - configs = configs.concat(this.getLocalConfigHierarchy(directory)); - } else { - debug("Not using .eslintrc or package.json files"); - } - - // Step 3: Merge in command line config file - if (this.specificConfig) { - debug("Using command line config file"); - configs.push(this.specificConfig); - } - - return configs; - } - - /** - * Gets a list of config objects extracted from local config files that apply to the current directory, in - * descending order, beginning with the config that is highest in the directory tree. - * @param {string} directory The directory to start looking in for local config files. - * @returns {Object[]} The shallow local config objects, in ascending order of precedence (closest to the current - * directory at the end), or an empty array if there are no local configs. - * @private - */ - getLocalConfigHierarchy(directory) { - const localConfigFiles = this.findLocalConfigFiles(directory), - projectConfigPath = ConfigFile.getFilenameForDirectory(this.options.cwd), - searched = [], - configs = []; - - for (const localConfigFile of localConfigFiles) { - const localConfigDirectory = path.dirname(localConfigFile); - const localConfigHierarchyCache = this.configCache.getHierarchyLocalConfigs(localConfigDirectory); - - if (localConfigHierarchyCache) { - const localConfigHierarchy = localConfigHierarchyCache.concat(configs); - - this.configCache.setHierarchyLocalConfigs(searched, localConfigHierarchy); - return localConfigHierarchy; - } - - /* - * Don't consider the personal config file in the home directory, - * except if the home directory is the same as the current working directory - */ - if (localConfigDirectory === PERSONAL_CONFIG_DIR && localConfigFile !== projectConfigPath) { - continue; - } - - debug(`Loading ${localConfigFile}`); - const localConfig = ConfigFile.load(localConfigFile, this); - - // Ignore empty config files - if (!localConfig) { - continue; - } - - debug(`Using ${localConfigFile}`); - configs.unshift(localConfig); - searched.push(localConfigDirectory); - - // Stop traversing if a config is found with the root flag set - if (localConfig.root) { - break; - } - } - - if (!configs.length && !this.specificConfig) { - - // Fall back on the personal config from ~/.eslintrc - debug("Using personal config file"); - const personalConfig = this.getPersonalConfig(); - - if (personalConfig) { - configs.unshift(personalConfig); - } else if (!hasRules(this.options) && !this.options.baseConfig) { - - // No config file, no manual configuration, and no rules, so error. - const noConfigError = new Error("No ESLint configuration found."); - - noConfigError.messageTemplate = "no-config-found"; - noConfigError.messageData = { - directory, - filesExamined: localConfigFiles - }; - - throw noConfigError; - } - } - - // Set the caches for the parent directories - this.configCache.setHierarchyLocalConfigs(searched, configs); - - return configs; - } - - /** - * Gets the vector of applicable configs and subconfigs from the hierarchy for a given file. A vector is an array of - * entries, each of which in an object specifying a config file path and an array of override indices corresponding - * to entries in the config file's overrides section whose glob patterns match the specified file path; e.g., the - * vector entry { configFile: '/home/john/app/.eslintrc', matchingOverrides: [0, 2] } would indicate that the main - * project .eslintrc file and its first and third override blocks apply to the current file. - * @param {string} filePath The file path for which to build the hierarchy and config vector. - * @returns {Array} config vector applicable to the specified path - * @private - */ - getConfigVector(filePath) { - const directory = filePath ? path.dirname(filePath) : this.options.cwd; - - return this.getConfigHierarchy(directory).map(config => { - const vectorEntry = { - filePath: config.filePath, - matchingOverrides: [] - }; - - if (config.overrides) { - const relativePath = path.relative(config.baseDirectory, filePath || directory); - - config.overrides.forEach((override, i) => { - if (ConfigOps.pathMatchesGlobs(relativePath, override.files, override.excludedFiles)) { - vectorEntry.matchingOverrides.push(i); - } - }); - } - - return vectorEntry; - }); - } - - /** - * Finds local config files from the specified directory and its parent directories. - * @param {string} directory The directory to start searching from. - * @returns {GeneratorFunction} The paths of local config files found. - */ - findLocalConfigFiles(directory) { - if (!this.localConfigFinder) { - this.localConfigFinder = new FileFinder(ConfigFile.CONFIG_FILES, this.options.cwd); - } - - return this.localConfigFinder.findAllInDirectoryAndParents(directory); - } - - /** - * Builds the authoritative config object for the specified file path by merging the hierarchy of config objects - * that apply to the current file, including the base config (conf/eslint-recommended), the user's personal config - * from their homedir, all local configs from the directory tree, any specific config file passed on the command - * line, any configuration overrides set directly on the command line, and finally the environment configs - * (conf/environments). - * @param {string} filePath a file in whose directory we start looking for a local config - * @returns {Object} config object - */ - getConfig(filePath) { - const vector = this.getConfigVector(filePath); - let config = this.configCache.getMergedConfig(vector); - - if (config) { - debug("Using config from cache"); - return config; - } - - // Step 1: Merge in the filesystem configurations (base, local, and personal) - config = ConfigOps.getConfigFromVector(vector, this.configCache); - - // Step 2: Merge in command line configurations - config = ConfigOps.merge(config, this.cliConfig); - - if (this.cliConfig.plugins) { - this.plugins.loadAll(this.cliConfig.plugins); - } - - /* - * Step 3: Override parser only 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 }); - } - - // Step 4: Apply environments to the config - config = ConfigOps.applyEnvironments(config, this.linterContext.environments); - - this.configCache.setMergedConfig(vector, config); - - return config; - } -} - -module.exports = Config; diff --git a/tools/node_modules/eslint/lib/config/autoconfig.js b/tools/node_modules/eslint/lib/config/autoconfig.js deleted file mode 100644 index f2c707be843876..00000000000000 --- a/tools/node_modules/eslint/lib/config/autoconfig.js +++ /dev/null @@ -1,358 +0,0 @@ -/** - * @fileoverview Used for creating a suggested configuration based on project code. - * @author Ian VanSchooten - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const lodash = require("lodash"), - Linter = require("../linter"), - configRule = require("./config-rule"), - ConfigOps = require("./config-ops"), - recConfig = require("../../conf/eslint-recommended"); - -const debug = require("debug")("eslint:autoconfig"); -const linter = new Linter(); - -//------------------------------------------------------------------------------ -// Data -//------------------------------------------------------------------------------ - -const MAX_CONFIG_COMBINATIONS = 17, // 16 combinations + 1 for severity only - RECOMMENDED_CONFIG_NAME = "eslint:recommended"; - -//------------------------------------------------------------------------------ -// Private -//------------------------------------------------------------------------------ - -/** - * Information about a rule configuration, in the context of a Registry. - * - * @typedef {Object} registryItem - * @param {ruleConfig} config A valid configuration for the rule - * @param {number} specificity The number of elements in the ruleConfig array - * @param {number} errorCount The number of errors encountered when linting with the config - */ - -/** - * This callback is used to measure execution status in a progress bar - * @callback progressCallback - * @param {number} The total number of times the callback will be called. - */ - -/** - * Create registryItems for rules - * @param {rulesConfig} rulesConfig Hash of rule names and arrays of ruleConfig items - * @returns {Object} registryItems for each rule in provided rulesConfig - */ -function makeRegistryItems(rulesConfig) { - return Object.keys(rulesConfig).reduce((accumulator, ruleId) => { - accumulator[ruleId] = rulesConfig[ruleId].map(config => ({ - config, - specificity: config.length || 1, - errorCount: void 0 - })); - return accumulator; - }, {}); -} - -/** - * Creates an object in which to store rule configs and error counts - * - * Unless a rulesConfig is provided at construction, the registry will not contain - * any rules, only methods. This will be useful for building up registries manually. - * - * Registry class - */ -class Registry { - - /** - * @param {rulesConfig} [rulesConfig] Hash of rule names and arrays of possible configurations - */ - constructor(rulesConfig) { - this.rules = (rulesConfig) ? makeRegistryItems(rulesConfig) : {}; - } - - /** - * Populate the registry with core rule configs. - * - * It will set the registry's `rule` property to an object having rule names - * as keys and an array of registryItems as values. - * - * @returns {void} - */ - populateFromCoreRules() { - const rulesConfig = configRule.createCoreRuleConfigs(); - - this.rules = makeRegistryItems(rulesConfig); - } - - /** - * Creates sets of rule configurations which can be used for linting - * and initializes registry errors to zero for those configurations (side effect). - * - * This combines as many rules together as possible, such that the first sets - * in the array will have the highest number of rules configured, and later sets - * will have fewer and fewer, as not all rules have the same number of possible - * configurations. - * - * The length of the returned array will be <= MAX_CONFIG_COMBINATIONS. - * - * @returns {Object[]} "rules" configurations to use for linting - */ - buildRuleSets() { - let idx = 0; - const ruleIds = Object.keys(this.rules), - ruleSets = []; - - /** - * Add a rule configuration from the registry to the ruleSets - * - * This is broken out into its own function so that it doesn't need to be - * created inside of the while loop. - * - * @param {string} rule The ruleId to add. - * @returns {void} - */ - const addRuleToRuleSet = function(rule) { - - /* - * This check ensures that there is a rule configuration and that - * it has fewer than the max combinations allowed. - * If it has too many configs, we will only use the most basic of - * the possible configurations. - */ - const hasFewCombos = (this.rules[rule].length <= MAX_CONFIG_COMBINATIONS); - - if (this.rules[rule][idx] && (hasFewCombos || this.rules[rule][idx].specificity <= 2)) { - - /* - * If the rule has too many possible combinations, only take - * simple ones, avoiding objects. - */ - if (!hasFewCombos && typeof this.rules[rule][idx].config[1] === "object") { - return; - } - - ruleSets[idx] = ruleSets[idx] || {}; - ruleSets[idx][rule] = this.rules[rule][idx].config; - - /* - * Initialize errorCount to zero, since this is a config which - * will be linted. - */ - this.rules[rule][idx].errorCount = 0; - } - }.bind(this); - - while (ruleSets.length === idx) { - ruleIds.forEach(addRuleToRuleSet); - idx += 1; - } - - return ruleSets; - } - - /** - * Remove all items from the registry with a non-zero number of errors - * - * Note: this also removes rule configurations which were not linted - * (meaning, they have an undefined errorCount). - * - * @returns {void} - */ - stripFailingConfigs() { - const ruleIds = Object.keys(this.rules), - newRegistry = new Registry(); - - newRegistry.rules = Object.assign({}, this.rules); - ruleIds.forEach(ruleId => { - const errorFreeItems = newRegistry.rules[ruleId].filter(registryItem => (registryItem.errorCount === 0)); - - if (errorFreeItems.length > 0) { - newRegistry.rules[ruleId] = errorFreeItems; - } else { - delete newRegistry.rules[ruleId]; - } - }); - - return newRegistry; - } - - /** - * Removes rule configurations which were not included in a ruleSet - * - * @returns {void} - */ - stripExtraConfigs() { - const ruleIds = Object.keys(this.rules), - newRegistry = new Registry(); - - newRegistry.rules = Object.assign({}, this.rules); - ruleIds.forEach(ruleId => { - newRegistry.rules[ruleId] = newRegistry.rules[ruleId].filter(registryItem => (typeof registryItem.errorCount !== "undefined")); - }); - - return newRegistry; - } - - /** - * Creates a registry of rules which had no error-free configs. - * The new registry is intended to be analyzed to determine whether its rules - * should be disabled or set to warning. - * - * @returns {Registry} A registry of failing rules. - */ - getFailingRulesRegistry() { - const ruleIds = Object.keys(this.rules), - failingRegistry = new Registry(); - - 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; - } - }); - - return failingRegistry; - } - - /** - * Create an eslint config for any rules which only have one configuration - * in the registry. - * - * @returns {Object} An eslint config with rules section populated - */ - createConfig() { - const ruleIds = Object.keys(this.rules), - config = { rules: {} }; - - ruleIds.forEach(ruleId => { - if (this.rules[ruleId].length === 1) { - config.rules[ruleId] = this.rules[ruleId][0].config; - } - }); - - return config; - } - - /** - * Return a cloned registry containing only configs with a desired specificity - * - * @param {number} specificity Only keep configs with this specificity - * @returns {Registry} A registry of rules - */ - filterBySpecificity(specificity) { - const ruleIds = Object.keys(this.rules), - newRegistry = new Registry(); - - newRegistry.rules = Object.assign({}, this.rules); - ruleIds.forEach(ruleId => { - newRegistry.rules[ruleId] = this.rules[ruleId].filter(registryItem => (registryItem.specificity === specificity)); - }); - - return newRegistry; - } - - /** - * Lint SourceCodes against all configurations in the registry, and record results - * - * @param {Object[]} sourceCodes SourceCode objects for each filename - * @param {Object} config ESLint config object - * @param {progressCallback} [cb] Optional callback for reporting execution status - * @returns {Registry} New registry with errorCount populated - */ - lintSourceCode(sourceCodes, config, cb) { - let lintedRegistry = new Registry(); - - lintedRegistry.rules = Object.assign({}, this.rules); - - const ruleSets = lintedRegistry.buildRuleSets(); - - lintedRegistry = lintedRegistry.stripExtraConfigs(); - - debug("Linting with all possible rule combinations"); - - const filenames = Object.keys(sourceCodes); - const totalFilesLinting = filenames.length * ruleSets.length; - - filenames.forEach(filename => { - debug(`Linting file: ${filename}`); - - let ruleSetIdx = 0; - - ruleSets.forEach(ruleSet => { - const lintConfig = Object.assign({}, config, { rules: ruleSet }); - const lintResults = linter.verify(sourceCodes[filename], lintConfig); - - 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 - * set in this ruleSetIdx. - * (https://github.com/eslint/eslint/issues/5992) - * (https://github.com/eslint/eslint/issues/7860) - */ - if ( - lintedRegistry.rules[result.ruleId] && - lintedRegistry.rules[result.ruleId][ruleSetIdx] - ) { - lintedRegistry.rules[result.ruleId][ruleSetIdx].errorCount += 1; - } - }); - - ruleSetIdx += 1; - - if (cb) { - cb(totalFilesLinting); // eslint-disable-line callback-return - } - }); - - // Deallocate for GC - sourceCodes[filename] = null; - }); - - return lintedRegistry; - } -} - -/** - * Extract rule configuration into eslint:recommended where possible. - * - * This will return a new config with `"extends": "eslint:recommended"` and - * only the rules which have configurations different from the recommended config. - * - * @param {Object} config config object - * @returns {Object} config object using `"extends": "eslint:recommended"` - */ -function extendFromRecommended(config) { - const newConfig = Object.assign({}, config); - - ConfigOps.normalizeToStrings(newConfig); - - const recRules = Object.keys(recConfig.rules).filter(ruleId => ConfigOps.isErrorSeverity(recConfig.rules[ruleId])); - - recRules.forEach(ruleId => { - if (lodash.isEqual(recConfig.rules[ruleId], newConfig.rules[ruleId])) { - delete newConfig.rules[ruleId]; - } - }); - newConfig.extends = RECOMMENDED_CONFIG_NAME; - return newConfig; -} - - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = { - Registry, - extendFromRecommended -}; diff --git a/tools/node_modules/eslint/lib/config/config-cache.js b/tools/node_modules/eslint/lib/config/config-cache.js deleted file mode 100644 index 07436a87c8fc2c..00000000000000 --- a/tools/node_modules/eslint/lib/config/config-cache.js +++ /dev/null @@ -1,130 +0,0 @@ -/** - * @fileoverview Responsible for caching config files - * @author Sylvan Mably - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Get a string hash for a config vector - * @param {Array} vector config vector to hash - * @returns {string} hash of the vector values - * @private - */ -function hash(vector) { - return JSON.stringify(vector); -} - -//------------------------------------------------------------------------------ -// API -//------------------------------------------------------------------------------ - -/** - * Configuration caching class - */ -module.exports = class ConfigCache { - - constructor() { - this.configFullNameCache = new Map(); - this.localHierarchyCache = new Map(); - this.mergedVectorCache = new Map(); - this.mergedCache = new Map(); - } - - /** - * Gets a config object from the cache for the specified config file path. - * @param {string} configFullName the name of the configuration as used in the eslint config(e.g. 'plugin:node/recommended'), - * or the absolute path to a config file. This should uniquely identify a config. - * @returns {Object|null} config object, if found in the cache, otherwise null - * @private - */ - getConfig(configFullName) { - return this.configFullNameCache.get(configFullName); - } - - /** - * Sets a config object in the cache for the specified config file path. - * @param {string} configFullName the name of the configuration as used in the eslint config(e.g. 'plugin:node/recommended'), - * or the absolute path to a config file. This should uniquely identify a config. - * @param {Object} config the config object to add to the cache - * @returns {void} - * @private - */ - setConfig(configFullName, config) { - this.configFullNameCache.set(configFullName, config); - } - - /** - * Gets a list of hierarchy-local config objects that apply to the specified directory. - * @param {string} directory the path to the directory - * @returns {Object[]|null} a list of config objects, if found in the cache, otherwise null - * @private - */ - getHierarchyLocalConfigs(directory) { - return this.localHierarchyCache.get(directory); - } - - /** - * For each of the supplied parent directories, sets the list of config objects for that directory to the - * appropriate subset of the supplied parent config objects. - * @param {string[]} parentDirectories a list of parent directories to add to the config cache - * @param {Object[]} parentConfigs a list of config objects that apply to the lowest directory in parentDirectories - * @returns {void} - * @private - */ - setHierarchyLocalConfigs(parentDirectories, parentConfigs) { - parentDirectories.forEach((localConfigDirectory, i) => { - const directoryParentConfigs = parentConfigs.slice(0, parentConfigs.length - i); - - this.localHierarchyCache.set(localConfigDirectory, directoryParentConfigs); - }); - } - - /** - * Gets a merged config object corresponding to the supplied vector. - * @param {Array} vector the vector to find a merged config for - * @returns {Object|null} a merged config object, if found in the cache, otherwise null - * @private - */ - getMergedVectorConfig(vector) { - return this.mergedVectorCache.get(hash(vector)); - } - - /** - * Sets a merged config object in the cache for the supplied vector. - * @param {Array} vector the vector to save a merged config for - * @param {Object} config the merged config object to add to the cache - * @returns {void} - * @private - */ - setMergedVectorConfig(vector, config) { - this.mergedVectorCache.set(hash(vector), config); - } - - /** - * Gets a merged config object corresponding to the supplied vector, including configuration options from outside - * the vector. - * @param {Array} vector the vector to find a merged config for - * @returns {Object|null} a merged config object, if found in the cache, otherwise null - * @private - */ - getMergedConfig(vector) { - return this.mergedCache.get(hash(vector)); - } - - /** - * Sets a merged config object in the cache for the supplied vector, including configuration options from outside - * the vector. - * @param {Array} vector the vector to save a merged config for - * @param {Object} config the merged config object to add to the cache - * @returns {void} - * @private - */ - setMergedConfig(vector, config) { - this.mergedCache.set(hash(vector), config); - } -}; diff --git a/tools/node_modules/eslint/lib/config/config-file.js b/tools/node_modules/eslint/lib/config/config-file.js deleted file mode 100644 index f76b92830c447c..00000000000000 --- a/tools/node_modules/eslint/lib/config/config-file.js +++ /dev/null @@ -1,640 +0,0 @@ -/** - * @fileoverview Helper to locate and load configuration files. - * @author Nicholas C. Zakas - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const fs = require("fs"), - path = require("path"), - ConfigOps = require("./config-ops"), - validator = require("./config-validator"), - ModuleResolver = require("../util/module-resolver"), - naming = require("../util/naming"), - pathIsInside = require("path-is-inside"), - stripComments = require("strip-json-comments"), - stringify = require("json-stable-stringify-without-jsonify"), - importFresh = require("import-fresh"); - -const debug = require("debug")("eslint:config-file"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Determines sort order for object keys for json-stable-stringify - * - * see: https://github.com/samn/json-stable-stringify#cmp - * - * @param {Object} a The first comparison object ({key: akey, value: avalue}) - * @param {Object} b The second comparison object ({key: bkey, value: bvalue}) - * @returns {number} 1 or -1, used in stringify cmp method - */ -function sortByKey(a, b) { - return a.key > b.key ? 1 : -1; -} - -//------------------------------------------------------------------------------ -// Private -//------------------------------------------------------------------------------ - -const CONFIG_FILES = [ - ".eslintrc.js", - ".eslintrc.yaml", - ".eslintrc.yml", - ".eslintrc.json", - ".eslintrc", - "package.json" -]; - -const resolver = new ModuleResolver(); - -/** - * Convenience wrapper for synchronously reading file contents. - * @param {string} filePath The filename to read. - * @returns {string} The file contents, with the BOM removed. - * @private - */ -function readFile(filePath) { - return fs.readFileSync(filePath, "utf8").replace(/^\ufeff/, ""); -} - -/** - * Determines if a given string represents a filepath or not using the same - * conventions as require(), meaning that the first character must be nonalphanumeric - * and not the @ sign which is used for scoped packages to be considered a file path. - * @param {string} filePath The string to check. - * @returns {boolean} True if it's a filepath, false if not. - * @private - */ -function isFilePath(filePath) { - return path.isAbsolute(filePath) || !/\w|@/.test(filePath.charAt(0)); -} - -/** - * Loads a YAML configuration from a file. - * @param {string} filePath The filename to load. - * @returns {Object} The configuration object from the file. - * @throws {Error} If the file cannot be read. - * @private - */ -function loadYAMLConfigFile(filePath) { - debug(`Loading YAML config file: ${filePath}`); - - // lazy load YAML to improve performance when not used - const yaml = require("js-yaml"); - - try { - - // empty YAML file can be null, so always use - return yaml.safeLoad(readFile(filePath)) || {}; - } catch (e) { - debug(`Error reading YAML file: ${filePath}`); - e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`; - throw e; - } -} - -/** - * Loads a JSON configuration from a file. - * @param {string} filePath The filename to load. - * @returns {Object} The configuration object from the file. - * @throws {Error} If the file cannot be read. - * @private - */ -function loadJSONConfigFile(filePath) { - debug(`Loading JSON config file: ${filePath}`); - - try { - return JSON.parse(stripComments(readFile(filePath))); - } catch (e) { - debug(`Error reading JSON file: ${filePath}`); - e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`; - e.messageTemplate = "failed-to-read-json"; - e.messageData = { - path: filePath, - message: e.message - }; - throw e; - } -} - -/** - * Loads a legacy (.eslintrc) configuration from a file. - * @param {string} filePath The filename to load. - * @returns {Object} The configuration object from the file. - * @throws {Error} If the file cannot be read. - * @private - */ -function loadLegacyConfigFile(filePath) { - debug(`Loading config file: ${filePath}`); - - // lazy load YAML to improve performance when not used - const yaml = require("js-yaml"); - - try { - return yaml.safeLoad(stripComments(readFile(filePath))) || /* istanbul ignore next */ {}; - } catch (e) { - debug(`Error reading YAML file: ${filePath}`); - e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`; - throw e; - } -} - -/** - * Loads a JavaScript configuration from a file. - * @param {string} filePath The filename to load. - * @returns {Object} The configuration object from the file. - * @throws {Error} If the file cannot be read. - * @private - */ -function loadJSConfigFile(filePath) { - debug(`Loading JS config file: ${filePath}`); - try { - return importFresh(filePath); - } catch (e) { - debug(`Error reading JavaScript file: ${filePath}`); - e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`; - throw e; - } -} - -/** - * Loads a configuration from a package.json file. - * @param {string} filePath The filename to load. - * @returns {Object} The configuration object from the file. - * @throws {Error} If the file cannot be read. - * @private - */ -function loadPackageJSONConfigFile(filePath) { - debug(`Loading package.json config file: ${filePath}`); - try { - return loadJSONConfigFile(filePath).eslintConfig || null; - } catch (e) { - debug(`Error reading package.json file: ${filePath}`); - e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`; - throw e; - } -} - -/** - * Creates an error to notify about a missing config to extend from. - * @param {string} configName The name of the missing config. - * @returns {Error} The error object to throw - * @private - */ -function configMissingError(configName) { - const error = new Error(`Failed to load config "${configName}" to extend from.`); - - error.messageTemplate = "extend-config-missing"; - error.messageData = { - configName - }; - return error; -} - -/** - * Loads a configuration file regardless of the source. Inspects the file path - * to determine the correctly way to load the config file. - * @param {Object} file The path to the configuration. - * @returns {Object} The configuration information. - * @private - */ -function loadConfigFile(file) { - const filePath = file.filePath; - let config; - - switch (path.extname(filePath)) { - case ".js": - config = loadJSConfigFile(filePath); - if (file.configName) { - config = config.configs[file.configName]; - if (!config) { - throw configMissingError(file.configFullName); - } - } - break; - - case ".json": - if (path.basename(filePath) === "package.json") { - config = loadPackageJSONConfigFile(filePath); - if (config === null) { - return null; - } - } else { - config = loadJSONConfigFile(filePath); - } - break; - - case ".yaml": - case ".yml": - config = loadYAMLConfigFile(filePath); - break; - - default: - config = loadLegacyConfigFile(filePath); - } - - return ConfigOps.merge(ConfigOps.createEmptyConfig(), config); -} - -/** - * Writes a configuration file in JSON format. - * @param {Object} config The configuration object to write. - * @param {string} filePath The filename to write to. - * @returns {void} - * @private - */ -function writeJSONConfigFile(config, filePath) { - debug(`Writing JSON config file: ${filePath}`); - - const content = stringify(config, { cmp: sortByKey, space: 4 }); - - fs.writeFileSync(filePath, content, "utf8"); -} - -/** - * Writes a configuration file in YAML format. - * @param {Object} config The configuration object to write. - * @param {string} filePath The filename to write to. - * @returns {void} - * @private - */ -function writeYAMLConfigFile(config, filePath) { - debug(`Writing YAML config file: ${filePath}`); - - // lazy load YAML to improve performance when not used - const yaml = require("js-yaml"); - - const content = yaml.safeDump(config, { sortKeys: true }); - - fs.writeFileSync(filePath, content, "utf8"); -} - -/** - * Writes a configuration file in JavaScript format. - * @param {Object} config The configuration object to write. - * @param {string} filePath The filename to write to. - * @throws {Error} If an error occurs linting the config file contents. - * @returns {void} - * @private - */ -function writeJSConfigFile(config, filePath) { - debug(`Writing JS config file: ${filePath}`); - - let contentToWrite; - const stringifiedContent = `module.exports = ${stringify(config, { cmp: sortByKey, space: 4 })};`; - - try { - const CLIEngine = require("../cli-engine"); - const linter = new CLIEngine({ - baseConfig: config, - fix: true, - useEslintrc: false - }); - const report = linter.executeOnText(stringifiedContent); - - contentToWrite = report.results[0].output || stringifiedContent; - } catch (e) { - debug("Error linting JavaScript config file, writing unlinted version"); - const errorMessage = e.message; - - contentToWrite = stringifiedContent; - e.message = "An error occurred while generating your JavaScript config file. "; - e.message += "A config file was still generated, but the config file itself may not follow your linting rules."; - e.message += `\nError: ${errorMessage}`; - throw e; - } finally { - fs.writeFileSync(filePath, contentToWrite, "utf8"); - } -} - -/** - * Writes a configuration file. - * @param {Object} config The configuration object to write. - * @param {string} filePath The filename to write to. - * @returns {void} - * @throws {Error} When an unknown file type is specified. - * @private - */ -function write(config, filePath) { - switch (path.extname(filePath)) { - case ".js": - writeJSConfigFile(config, filePath); - break; - - case ".json": - writeJSONConfigFile(config, filePath); - break; - - case ".yaml": - case ".yml": - writeYAMLConfigFile(config, filePath); - break; - - default: - throw new Error("Can't write to unknown file type."); - } -} - -/** - * Determines the base directory for node packages referenced in a config file. - * This does not include node_modules in the path so it can be used for all - * references relative to a config file. - * @param {string} configFilePath The config file referencing the file. - * @returns {string} The base directory for the file path. - * @private - */ -function getBaseDir(configFilePath) { - - // calculates the path of the project including ESLint as dependency - const projectPath = path.resolve(__dirname, "../../../"); - - if (configFilePath && pathIsInside(configFilePath, projectPath)) { - - // be careful of https://github.com/substack/node-resolve/issues/78 - return path.join(path.resolve(configFilePath)); - } - - /* - * default to ESLint project path since it's unlikely that plugins will be - * in this directory - */ - return path.join(projectPath); -} - -/** - * Determines the lookup path, including node_modules, for package - * references relative to a config file. - * @param {string} configFilePath The config file referencing the file. - * @returns {string} The lookup path for the file path. - * @private - */ -function getLookupPath(configFilePath) { - const basedir = getBaseDir(configFilePath); - - return path.join(basedir, "node_modules"); -} - -/** - * Resolves a eslint core config path - * @param {string} name The eslint config name. - * @returns {string} The resolved path of the config. - * @private - */ -function getEslintCoreConfigPath(name) { - if (name === "eslint:recommended") { - - /* - * Add an explicit substitution for eslint:recommended to - * conf/eslint-recommended.js. - */ - return path.resolve(__dirname, "../../conf/eslint-recommended.js"); - } - - if (name === "eslint:all") { - - /* - * Add an explicit substitution for eslint:all to conf/eslint-all.js - */ - return path.resolve(__dirname, "../../conf/eslint-all.js"); - } - - throw configMissingError(name); -} - -/** - * Applies values from the "extends" field in a configuration file. - * @param {Object} config The configuration information. - * @param {Config} configContext Plugin context for the config instance - * @param {string} filePath The file path from which the configuration information - * was loaded. - * @param {string} [relativeTo] The path to resolve relative to. - * @returns {Object} A new configuration object with all of the "extends" fields - * loaded and merged. - * @private - */ -function applyExtends(config, configContext, filePath, relativeTo) { - let configExtends = config.extends; - - // normalize into an array for easier handling - if (!Array.isArray(config.extends)) { - configExtends = [config.extends]; - } - - // Make the last element in an array take the highest precedence - return configExtends.reduceRight((previousValue, parentPath) => { - try { - let extensionPath; - - if (parentPath.startsWith("eslint:")) { - extensionPath = getEslintCoreConfigPath(parentPath); - } else if (isFilePath(parentPath)) { - - /* - * If the `extends` path is relative, use the directory of the current configuration - * file as the reference point. Otherwise, use as-is. - */ - extensionPath = (path.isAbsolute(parentPath) - ? parentPath - : path.join(relativeTo || path.dirname(filePath), parentPath) - ); - } else { - extensionPath = parentPath; - } - debug(`Loading ${extensionPath}`); - - // eslint-disable-next-line no-use-before-define - return ConfigOps.merge(load(extensionPath, configContext, relativeTo), previousValue); - } catch (e) { - - /* - * If the file referenced by `extends` failed to load, add the path - * to the configuration file that referenced it to the error - * message so the user is able to see where it was referenced from, - * then re-throw. - */ - e.message += `\nReferenced from: ${filePath}`; - throw e; - } - - }, config); -} - -/** - * Resolves a configuration file path into the fully-formed path, whether filename - * or package name. - * @param {string} filePath The filepath to resolve. - * @param {string} [relativeTo] The path to resolve relative to. - * @returns {Object} An object containing 3 properties: - * - 'filePath' (required) the resolved path that can be used directly to load the configuration. - * - 'configName' the name of the configuration inside the plugin. - * - 'configFullName' (required) the name of the configuration as used in the eslint config(e.g. 'plugin:node/recommended'), - * or the absolute path to a config file. This should uniquely identify a config. - * @private - */ -function resolve(filePath, relativeTo) { - if (isFilePath(filePath)) { - const fullPath = path.resolve(relativeTo || "", filePath); - - return { filePath: fullPath, configFullName: fullPath }; - } - let normalizedPackageName; - - if (filePath.startsWith("plugin:")) { - const configFullName = filePath; - const pluginName = filePath.slice(7, filePath.lastIndexOf("/")); - const configName = filePath.slice(filePath.lastIndexOf("/") + 1); - - normalizedPackageName = naming.normalizePackageName(pluginName, "eslint-plugin"); - debug(`Attempting to resolve ${normalizedPackageName}`); - - return { - filePath: require.resolve(normalizedPackageName), - configName, - configFullName - }; - } - normalizedPackageName = naming.normalizePackageName(filePath, "eslint-config"); - debug(`Attempting to resolve ${normalizedPackageName}`); - - return { - filePath: resolver.resolve(normalizedPackageName, getLookupPath(relativeTo)), - configFullName: filePath - }; - - -} - -/** - * Loads a configuration file from the given file path. - * @param {Object} resolvedPath The value from calling resolve() on a filename or package name. - * @param {Config} configContext Plugins context - * @returns {Object} The configuration information. - */ -function loadFromDisk(resolvedPath, configContext) { - const dirname = path.dirname(resolvedPath.filePath), - lookupPath = getLookupPath(dirname); - let config = loadConfigFile(resolvedPath); - - if (config) { - - // ensure plugins are properly loaded first - if (config.plugins) { - configContext.plugins.loadAll(config.plugins); - } - - // include full path of parser if present - if (config.parser) { - if (isFilePath(config.parser)) { - config.parser = path.resolve(dirname || "", config.parser); - } else { - config.parser = resolver.resolve(config.parser, lookupPath); - } - } - - const ruleMap = configContext.linterContext.getRules(); - - // validate the configuration before continuing - validator.validate(config, resolvedPath.configFullName, ruleMap.get.bind(ruleMap), configContext.linterContext.environments); - - /* - * If an `extends` property is defined, it represents a configuration file to use as - * a "parent". Load the referenced file and merge the configuration recursively. - */ - if (config.extends) { - config = applyExtends(config, configContext, resolvedPath.filePath, dirname); - } - } - - return config; -} - -/** - * Loads a config object, applying extends if present. - * @param {Object} configObject a config object to load - * @param {Config} configContext Context for the config instance - * @returns {Object} the config object with extends applied if present, or the passed config if not - * @private - */ -function loadObject(configObject, configContext) { - return configObject.extends ? applyExtends(configObject, configContext, "") : configObject; -} - -/** - * Loads a config object from the config cache based on its filename, falling back to the disk if the file is not yet - * cached. - * @param {string} filePath the path to the config file - * @param {Config} configContext Context for the config instance - * @param {string} [relativeTo] The path to resolve relative to. - * @returns {Object} the parsed config object (empty object if there was a parse error) - * @private - */ -function load(filePath, configContext, relativeTo) { - const resolvedPath = resolve(filePath, relativeTo); - - const cachedConfig = configContext.configCache.getConfig(resolvedPath.configFullName); - - if (cachedConfig) { - return cachedConfig; - } - - const config = loadFromDisk(resolvedPath, configContext); - - if (config) { - config.filePath = resolvedPath.filePath; - config.baseDirectory = path.dirname(resolvedPath.filePath); - configContext.configCache.setConfig(resolvedPath.configFullName, config); - } - - return config; -} - -/** - * Checks whether the given filename points to a file - * @param {string} filename A path to a file - * @returns {boolean} `true` if a file exists at the given location - */ -function isExistingFile(filename) { - try { - return fs.statSync(filename).isFile(); - } catch (err) { - if (err.code === "ENOENT") { - return false; - } - throw err; - } -} - - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = { - - getBaseDir, - getLookupPath, - load, - loadObject, - resolve, - write, - applyExtends, - CONFIG_FILES, - - /** - * Retrieves the configuration filename for a given directory. It loops over all - * of the valid configuration filenames in order to find the first one that exists. - * @param {string} directory The directory to check for a config file. - * @returns {?string} The filename of the configuration file for the directory - * or null if there is no configuration file in the directory. - */ - getFilenameForDirectory(directory) { - return CONFIG_FILES.map(filename => path.join(directory, filename)).find(isExistingFile) || null; - } -}; diff --git a/tools/node_modules/eslint/lib/config/config-initializer.js b/tools/node_modules/eslint/lib/config/config-initializer.js deleted file mode 100644 index b8126d4735c3c1..00000000000000 --- a/tools/node_modules/eslint/lib/config/config-initializer.js +++ /dev/null @@ -1,654 +0,0 @@ -/** - * @fileoverview Config initialization wizard. - * @author Ilya Volodin - */ - - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const util = require("util"), - inquirer = require("inquirer"), - ProgressBar = require("progress"), - semver = require("semver"), - autoconfig = require("./autoconfig.js"), - ConfigFile = require("./config-file"), - ConfigOps = require("./config-ops"), - getSourceCodeOfFiles = require("../util/source-code-utils").getSourceCodeOfFiles, - ModuleResolver = require("../util/module-resolver"), - npmUtils = require("../util/npm-utils"), - recConfig = require("../../conf/eslint-recommended"), - log = require("../util/logging"); - -const debug = require("debug")("eslint:config-initializer"); - -//------------------------------------------------------------------------------ -// Private -//------------------------------------------------------------------------------ - -const DEFAULT_ECMA_VERSION = 2018; - -/* istanbul ignore next: hard to test fs function */ -/** - * Create .eslintrc file in the current working directory - * @param {Object} config object that contains user's answers - * @param {string} format The file format to write to. - * @returns {void} - */ -function writeFile(config, format) { - - // default is .js - let extname = ".js"; - - if (format === "YAML") { - extname = ".yml"; - } else if (format === "JSON") { - 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 (installedESLint) { - log.info("ESLint was installed locally. We recommend using this local copy instead of your globally-installed copy."); - } -} - -/** - * Get the peer dependencies of the given module. - * This adds the gotten value to cache at the first time, then reuses it. - * In a process, this function is called twice, but `npmUtils.fetchPeerDependencies` needs to access network which is relatively slow. - * @param {string} moduleName The module name to get. - * @returns {Object} The peer dependencies of the given module. - * This object is the object of `peerDependencies` field of `package.json`. - * Returns null if npm was not found. - */ -function getPeerDependencies(moduleName) { - let result = getPeerDependencies.cache.get(moduleName); - - if (!result) { - log.info(`Checking peerDependencies of ${moduleName}`); - - result = npmUtils.fetchPeerDependencies(moduleName); - getPeerDependencies.cache.set(moduleName, result); - } - - return result; -} -getPeerDependencies.cache = new Map(); - -/** - * Return necessary plugins, configs, parsers, etc. based on the config - * @param {Object} config config object - * @param {boolean} [installESLint=true] If `false` is given, it does not install eslint. - * @returns {string[]} An array of modules to be installed. - */ -function getModulesList(config, installESLint) { - const modules = {}; - - // Create a list of modules which should be installed based on config - if (config.plugins) { - for (const plugin of config.plugins) { - modules[`eslint-plugin-${plugin}`] = "latest"; - } - } - if (config.extends && config.extends.indexOf("eslint:") === -1) { - const moduleName = `eslint-config-${config.extends}`; - - modules[moduleName] = "latest"; - Object.assign( - modules, - getPeerDependencies(`${moduleName}@latest`) - ); - } - - if (installESLint === false) { - delete modules.eslint; - } else { - const installStatus = npmUtils.checkDevDeps(["eslint"]); - - // Mark to show messages if it's new installation of eslint. - if (installStatus.eslint === false) { - log.info("Local ESLint installation not found."); - modules.eslint = modules.eslint || "latest"; - config.installedESLint = true; - } - } - - return Object.keys(modules).map(name => `${name}@${modules[name]}`); -} - -/** - * Set the `rules` of a config by examining a user's source code - * - * Note: This clones the config object and returns a new config to avoid mutating - * the original config parameter. - * - * @param {Object} answers answers received from inquirer - * @param {Object} config config object - * @returns {Object} config object with configured rules - */ -function configureRules(answers, config) { - const BAR_TOTAL = 20, - BAR_SOURCE_CODE_TOTAL = 4, - newConfig = Object.assign({}, config), - disabledConfigs = {}; - let sourceCodes, - registry; - - // Set up a progress bar, as this process can take a long time - const bar = new ProgressBar("Determining Config: :percent [:bar] :elapseds elapsed, eta :etas ", { - width: 30, - total: BAR_TOTAL - }); - - bar.tick(0); // Shows the progress bar - - // Get the SourceCode of all chosen files - const patterns = answers.patterns.split(/[\s]+/); - - try { - sourceCodes = getSourceCodeOfFiles(patterns, { baseConfig: newConfig, useEslintrc: false }, total => { - bar.tick((BAR_SOURCE_CODE_TOTAL / total)); - }); - } catch (e) { - log.info("\n"); - throw e; - } - const fileQty = Object.keys(sourceCodes).length; - - if (fileQty === 0) { - log.info("\n"); - throw new Error("Automatic Configuration failed. No files were able to be parsed."); - } - - // Create a registry of rule configs - registry = new autoconfig.Registry(); - registry.populateFromCoreRules(); - - // Lint all files with each rule config in the registry - 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 })}`); - - // Create a list of recommended rules, because we don't want to disable them - 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(ruleId => { - - // If the rule is recommended, set it to error, otherwise disable it - disabledConfigs[ruleId] = (recRules.indexOf(ruleId) !== -1) ? 2 : 0; - }); - - // Now that we know which rules to disable, strip out configs with errors - registry = registry.stripFailingConfigs(); - - /* - * If there is only one config that results in no errors for a rule, we should use it. - * createConfig will only add rules that have one configuration in the registry. - */ - const singleConfigs = registry.createConfig().rules; - - /* - * The "sweet spot" for number of options in a config seems to be two (severity plus one option). - * Very often, a third option (usually an object) is available to address - * edge cases, exceptions, or unique situations. We will prefer to use a config with - * specificity of two. - */ - const specTwoConfigs = registry.filterBySpecificity(2).createConfig().rules; - - // Maybe a specific combination using all three options works - const specThreeConfigs = registry.filterBySpecificity(3).createConfig().rules; - - // If all else fails, try to use the default (severity only) - const defaultConfigs = registry.filterBySpecificity(1).createConfig().rules; - - // Combine configs in reverse priority order (later take precedence) - newConfig.rules = Object.assign({}, disabledConfigs, defaultConfigs, specThreeConfigs, specTwoConfigs, singleConfigs); - - // Make sure progress bar has finished (floating point rounding) - bar.update(BAR_TOTAL); - - // 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(ruleId => (newConfig.rules[ruleId] !== 0)).length; - const resultMessage = [ - `\nEnabled ${enabledRules} out of ${totalRules}`, - `rules based on ${fileQty}`, - `file${(fileQty === 1) ? "." : "s."}` - ].join(" "); - - log.info(resultMessage); - - ConfigOps.normalizeToStrings(newConfig); - return newConfig; -} - -/** - * process user's answers and create config object - * @param {Object} answers answers received from inquirer - * @returns {Object} config object - */ -function processAnswers(answers) { - let config = { - rules: {}, - env: {}, - parserOptions: {}, - extends: [] - }; - - // set the latest ECMAScript version - config.parserOptions.ecmaVersion = DEFAULT_ECMA_VERSION; - config.env.es6 = true; - config.globals = { - Atomics: "readonly", - SharedArrayBuffer: "readonly" - }; - - // set the module type - if (answers.moduleType === "esm") { - config.parserOptions.sourceType = "module"; - } else if (answers.moduleType === "commonjs") { - config.env.commonjs = true; - } - - // add in browser and node environments if necessary - answers.env.forEach(env => { - config.env[env] = true; - }); - - // add in library information - if (answers.framework === "react") { - config.parserOptions.ecmaFeatures = { - jsx: true - }; - config.plugins = ["react"]; - } else if (answers.framework === "vue") { - config.plugins = ["vue"]; - config.extends.push("plugin:vue/essential"); - } - - // setup rules based on problems/style enforcement preferences - if (answers.purpose === "problems") { - config.extends.unshift("eslint:recommended"); - } else if (answers.purpose === "style") { - if (answers.source === "prompt") { - config.extends.unshift("eslint:recommended"); - config.rules.indent = ["error", answers.indent]; - config.rules.quotes = ["error", answers.quotes]; - config.rules["linebreak-style"] = ["error", answers.linebreak]; - config.rules.semi = ["error", answers.semi ? "always" : "never"]; - } else if (answers.source === "auto") { - config = configureRules(answers, config); - config = autoconfig.extendFromRecommended(config); - } - } - - // normalize extends - if (config.extends.length === 0) { - delete config.extends; - } else if (config.extends.length === 1) { - config.extends = config.extends[0]; - } - - ConfigOps.normalizeToStrings(config); - return config; -} - -/** - * process user's style guide of choice and return an appropriate config object. - * @param {string} guide name of the chosen style guide - * @returns {Object} config object - */ -function getConfigForStyleGuide(guide) { - const guides = { - google: { extends: "google" }, - airbnb: { extends: "airbnb" }, - "airbnb-base": { extends: "airbnb-base" }, - standard: { extends: "standard" } - }; - - if (!guides[guide]) { - throw new Error("You referenced an unsupported guide."); - } - - return guides[guide]; -} - -/** - * Get the version of the local ESLint. - * @returns {string|null} The version. If the local ESLint was not found, returns null. - */ -function getLocalESLintVersion() { - try { - const resolver = new ModuleResolver(); - const eslintPath = resolver.resolve("eslint", process.cwd()); - const eslint = require(eslintPath); - - return eslint.linter.version || null; - } catch (_err) { - return null; - } -} - -/** - * Get the shareable config name of the chosen style guide. - * @param {Object} answers The answers object. - * @returns {string} The shareable config name. - */ -function getStyleGuideName(answers) { - if (answers.styleguide === "airbnb" && answers.framework !== "react") { - return "airbnb-base"; - } - return answers.styleguide; -} - -/** - * Check whether the local ESLint version conflicts with the required version of the chosen shareable config. - * @param {Object} answers The answers object. - * @returns {boolean} `true` if the local ESLint is found then it conflicts with the required version of the chosen shareable config. - */ -function hasESLintVersionConflict(answers) { - - // Get the local ESLint version. - const localESLintVersion = getLocalESLintVersion(); - - if (!localESLintVersion) { - return false; - } - - // Get the required range of ESLint version. - const configName = getStyleGuideName(answers); - const moduleName = `eslint-config-${configName}@latest`; - const peerDependencies = getPeerDependencies(moduleName) || {}; - const requiredESLintVersionRange = peerDependencies.eslint; - - if (!requiredESLintVersionRange) { - return false; - } - - answers.localESLintVersion = localESLintVersion; - answers.requiredESLintVersionRange = requiredESLintVersionRange; - - // Check the version. - if (semver.satisfies(localESLintVersion, requiredESLintVersionRange)) { - answers.installESLint = false; - return false; - } - - return true; -} - -/** - * Install modules. - * @param {string[]} modules Modules to be installed. - * @returns {void} - */ -function installModules(modules) { - log.info(`Installing ${modules.join(", ")}`); - npmUtils.installSyncSaveDev(modules); -} - -/* istanbul ignore next: no need to test inquirer */ -/** - * Ask user to install modules. - * @param {string[]} modules Array of modules to be installed. - * @param {boolean} packageJsonExists Indicates if package.json is existed. - * @returns {Promise} Answer that indicates if user wants to install. - */ -function askInstallModules(modules, packageJsonExists) { - - // If no modules, do nothing. - if (modules.length === 0) { - return Promise.resolve(); - } - - log.info("The config that you've selected requires the following dependencies:\n"); - log.info(modules.join(" ")); - return inquirer.prompt([ - { - type: "confirm", - name: "executeInstallation", - message: "Would you like to install them now with npm?", - default: true, - when() { - return modules.length && packageJsonExists; - } - } - ]).then(({ executeInstallation }) => { - if (executeInstallation) { - installModules(modules); - } - }); -} - -/* istanbul ignore next: no need to test inquirer */ -/** - * Ask use a few questions on command prompt - * @returns {Promise} The promise with the result of the prompt - */ -function promptUser() { - - return inquirer.prompt([ - { - type: "list", - name: "purpose", - message: "How would you like to use ESLint?", - default: "problems", - choices: [ - { name: "To check syntax only", value: "syntax" }, - { name: "To check syntax and find problems", value: "problems" }, - { name: "To check syntax, find problems, and enforce code style", value: "style" } - ] - }, - { - type: "list", - name: "moduleType", - message: "What type of modules does your project use?", - default: "esm", - choices: [ - { name: "JavaScript modules (import/export)", value: "esm" }, - { name: "CommonJS (require/exports)", value: "commonjs" }, - { name: "None of these", value: "none" } - ] - }, - { - type: "list", - name: "framework", - message: "Which framework does your project use?", - default: "react", - choices: [ - { name: "React", value: "react" }, - { name: "Vue.js", value: "vue" }, - { name: "None of these", value: "none" } - ] - }, - { - type: "checkbox", - name: "env", - message: "Where does your code run?", - default: ["browser"], - choices: [ - { name: "Browser", value: "browser" }, - { name: "Node", value: "node" } - ] - }, - { - type: "list", - name: "source", - message: "How would you like to define a style for your project?", - default: "guide", - choices: [ - { name: "Use a popular style guide", value: "guide" }, - { name: "Answer questions about your style", value: "prompt" }, - { name: "Inspect your JavaScript file(s)", value: "auto" } - ], - when(answers) { - return answers.purpose === "style"; - } - }, - { - type: "list", - name: "styleguide", - message: "Which style guide do you want to follow?", - choices: [ - { name: "Airbnb (https://github.com/airbnb/javascript)", value: "airbnb" }, - { name: "Standard (https://github.com/standard/standard)", value: "standard" }, - { name: "Google (https://github.com/google/eslint-config-google)", value: "google" } - ], - when(answers) { - answers.packageJsonExists = npmUtils.checkPackageJson(); - return answers.source === "guide" && answers.packageJsonExists; - } - }, - { - type: "input", - name: "patterns", - message: "Which file(s), path(s), or glob(s) should be examined?", - when(answers) { - return (answers.source === "auto"); - }, - validate(input) { - if (input.trim().length === 0 && input.trim() !== ",") { - return "You must tell us what code to examine. Try again."; - } - return true; - } - }, - { - type: "list", - name: "format", - message: "What format do you want your config file to be in?", - default: "JavaScript", - choices: ["JavaScript", "YAML", "JSON"] - }, - { - type: "confirm", - name: "installESLint", - message(answers) { - const verb = semver.ltr(answers.localESLintVersion, answers.requiredESLintVersionRange) - ? "upgrade" - : "downgrade"; - - return `The style guide "${answers.styleguide}" requires eslint@${answers.requiredESLintVersionRange}. You are currently using eslint@${answers.localESLintVersion}.\n Do you want to ${verb}?`; - }, - default: true, - when(answers) { - return answers.source === "guide" && answers.packageJsonExists && hasESLintVersionConflict(answers); - } - } - ]).then(earlyAnswers => { - - // early exit if no style guide is necessary - if (earlyAnswers.purpose !== "style") { - const config = processAnswers(earlyAnswers); - const modules = getModulesList(config); - - return askInstallModules(modules, earlyAnswers.packageJsonExists) - .then(() => writeFile(config, earlyAnswers.format)); - } - - // early exit if you are using a style guide - if (earlyAnswers.source === "guide") { - if (!earlyAnswers.packageJsonExists) { - 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 void 0; - } - if (earlyAnswers.installESLint === false && !semver.satisfies(earlyAnswers.localESLintVersion, earlyAnswers.requiredESLintVersionRange)) { - log.info(`Note: it might not work since ESLint's version is mismatched with the ${earlyAnswers.styleguide} config.`); - } - if (earlyAnswers.styleguide === "airbnb" && earlyAnswers.framework !== "react") { - earlyAnswers.styleguide = "airbnb-base"; - } - - const config = ConfigOps.merge(processAnswers(earlyAnswers), getConfigForStyleGuide(earlyAnswers.styleguide)); - const modules = getModulesList(config); - - return askInstallModules(modules, earlyAnswers.packageJsonExists) - .then(() => writeFile(config, earlyAnswers.format)); - - } - - if (earlyAnswers.source === "auto") { - const combinedAnswers = Object.assign({}, earlyAnswers); - const config = processAnswers(combinedAnswers); - const modules = getModulesList(config); - - return askInstallModules(modules).then(() => writeFile(config, earlyAnswers.format)); - } - - // continue with the style questions otherwise... - return inquirer.prompt([ - { - type: "list", - name: "indent", - message: "What style of indentation do you use?", - default: "tab", - 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" }] - }, - { - type: "list", - name: "linebreak", - message: "What line endings do you use?", - default: "unix", - choices: [{ name: "Unix", value: "unix" }, { name: "Windows", value: "windows" }] - }, - { - type: "confirm", - name: "semi", - message: "Do you require semicolons?", - default: true - }, - { - type: "list", - name: "format", - message: "What format do you want your config file to be in?", - default: "JavaScript", - choices: ["JavaScript", "YAML", "JSON"] - } - ]).then(answers => { - const totalAnswers = Object.assign({}, earlyAnswers, answers); - - const config = processAnswers(totalAnswers); - const modules = getModulesList(config); - - return askInstallModules(modules).then(() => writeFile(config, answers.format)); - }); - }); -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -const init = { - getConfigForStyleGuide, - getModulesList, - hasESLintVersionConflict, - installModules, - processAnswers, - /* istanbul ignore next */initializeConfig() { - return promptUser(); - } -}; - -module.exports = init; diff --git a/tools/node_modules/eslint/lib/config/config-ops.js b/tools/node_modules/eslint/lib/config/config-ops.js deleted file mode 100644 index b38cdf7d7ca1f4..00000000000000 --- a/tools/node_modules/eslint/lib/config/config-ops.js +++ /dev/null @@ -1,404 +0,0 @@ -/** - * @fileoverview Config file operations. This file must be usable in the browser, - * so no Node-specific code can be here. - * @author Nicholas C. Zakas - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const minimatch = require("minimatch"), - path = require("path"); - -const debug = require("debug")("eslint:config-ops"); - -//------------------------------------------------------------------------------ -// Private -//------------------------------------------------------------------------------ - -const RULE_SEVERITY_STRINGS = ["off", "warn", "error"], - RULE_SEVERITY = RULE_SEVERITY_STRINGS.reduce((map, value, index) => { - map[value] = index; - return map; - }, {}), - VALID_SEVERITIES = [0, 1, 2, "off", "warn", "error"]; - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = { - - /** - * Creates an empty configuration object suitable for merging as a base. - * @returns {Object} A configuration object. - */ - createEmptyConfig() { - return { - globals: {}, - env: {}, - rules: {}, - parserOptions: {} - }; - }, - - /** - * Creates an environment config based on the specified environments. - * @param {Object} env The environment settings. - * @param {Environments} envContext The environment context. - * @returns {Object} A configuration object with the appropriate rules and globals - * set. - */ - createEnvironmentConfig(env, envContext) { - - const envConfig = this.createEmptyConfig(); - - if (env) { - - envConfig.env = env; - - Object.keys(env).filter(name => env[name]).forEach(name => { - const environment = envContext.get(name); - - if (environment) { - debug(`Creating config for environment ${name}`); - if (environment.globals) { - Object.assign(envConfig.globals, environment.globals); - } - - if (environment.parserOptions) { - Object.assign(envConfig.parserOptions, environment.parserOptions); - } - } - }); - } - - return envConfig; - }, - - /** - * Given a config with environment settings, applies the globals and - * ecmaFeatures to the configuration and returns the result. - * @param {Object} config The configuration information. - * @param {Environments} envContent env context. - * @returns {Object} The updated configuration information. - */ - applyEnvironments(config, envContent) { - if (config.env && typeof config.env === "object") { - debug("Apply environment settings to config"); - return this.merge(this.createEnvironmentConfig(config.env, envContent), config); - } - - return config; - }, - - /** - * Merges two config objects. This will not only add missing keys, but will also modify values to match. - * @param {Object} target config object - * @param {Object} src config object. Overrides in this config object will take priority over base. - * @param {boolean} [combine] Whether to combine arrays or not - * @param {boolean} [isRule] Whether its a rule - * @returns {Object} merged config object. - */ - merge: function deepmerge(target, src, combine, isRule) { - - /* - * The MIT License (MIT) - * - * Copyright (c) 2012 Nicholas Fisher - * - * 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. - */ - - /* - * This code is taken from deepmerge repo - * (https://github.com/KyleAMathews/deepmerge) - * and modified to meet our needs. - */ - const array = Array.isArray(src) || Array.isArray(target); - let dst = array && [] || {}; - - if (array) { - const resolvedTarget = target || []; - - // src could be a string, so check for array - if (isRule && Array.isArray(src) && src.length > 1) { - dst = dst.concat(src); - } else { - dst = dst.concat(resolvedTarget); - } - const resolvedSrc = typeof src === "object" ? src : [src]; - - Object.keys(resolvedSrc).forEach((_, i) => { - const e = resolvedSrc[i]; - - if (typeof dst[i] === "undefined") { - dst[i] = e; - } else if (typeof e === "object") { - if (isRule) { - dst[i] = e; - } else { - dst[i] = deepmerge(resolvedTarget[i], e, combine, isRule); - } - } else { - if (!combine) { - dst[i] = e; - } else { - if (dst.indexOf(e) === -1) { - dst.push(e); - } - } - } - }); - } else { - if (target && typeof target === "object") { - Object.keys(target).forEach(key => { - dst[key] = target[key]; - }); - } - Object.keys(src).forEach(key => { - if (key === "overrides") { - dst[key] = (target[key] || []).concat(src[key] || []); - } else if (Array.isArray(src[key]) || Array.isArray(target[key])) { - dst[key] = deepmerge(target[key], src[key], key === "plugins" || key === "extends", isRule); - } else if (typeof src[key] !== "object" || !src[key] || key === "exported" || key === "astGlobals") { - dst[key] = src[key]; - } else { - dst[key] = deepmerge(target[key] || {}, src[key], combine, key === "rules"); - } - }); - } - - return dst; - }, - - /** - * Normalizes the severity value of a rule's configuration to a number - * @param {(number|string|[number, ...*]|[string, ...*])} ruleConfig A rule's configuration value, generally - * received from the user. A valid config value is either 0, 1, 2, the string "off" (treated the same as 0), - * the string "warn" (treated the same as 1), the string "error" (treated the same as 2), or an array - * whose first element is one of the above values. Strings are matched case-insensitively. - * @returns {(0|1|2)} The numeric severity value if the config value was valid, otherwise 0. - */ - getRuleSeverity(ruleConfig) { - const severityValue = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig; - - if (severityValue === 0 || severityValue === 1 || severityValue === 2) { - return severityValue; - } - - if (typeof severityValue === "string") { - return RULE_SEVERITY[severityValue.toLowerCase()] || 0; - } - - return 0; - }, - - /** - * Converts old-style severity settings (0, 1, 2) into new-style - * severity settings (off, warn, error) for all rules. Assumption is that severity - * values have already been validated as correct. - * @param {Object} config The config object to normalize. - * @returns {void} - */ - normalizeToStrings(config) { - - if (config.rules) { - Object.keys(config.rules).forEach(ruleId => { - const ruleConfig = config.rules[ruleId]; - - if (typeof ruleConfig === "number") { - config.rules[ruleId] = RULE_SEVERITY_STRINGS[ruleConfig] || RULE_SEVERITY_STRINGS[0]; - } else if (Array.isArray(ruleConfig) && typeof ruleConfig[0] === "number") { - ruleConfig[0] = RULE_SEVERITY_STRINGS[ruleConfig[0]] || RULE_SEVERITY_STRINGS[0]; - } - }); - } - }, - - /** - * Determines if the severity for the given rule configuration represents an error. - * @param {int|string|Array} ruleConfig The configuration for an individual rule. - * @returns {boolean} True if the rule represents an error, false if not. - */ - isErrorSeverity(ruleConfig) { - return module.exports.getRuleSeverity(ruleConfig) === 2; - }, - - /** - * Checks whether a given config has valid severity or not. - * @param {number|string|Array} ruleConfig - The configuration for an individual rule. - * @returns {boolean} `true` if the configuration has valid severity. - */ - isValidSeverity(ruleConfig) { - let severity = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig; - - if (typeof severity === "string") { - severity = severity.toLowerCase(); - } - return VALID_SEVERITIES.indexOf(severity) !== -1; - }, - - /** - * Checks whether every rule of a given config has valid severity or not. - * @param {Object} config - The configuration for rules. - * @returns {boolean} `true` if the configuration has valid severity. - */ - isEverySeverityValid(config) { - return Object.keys(config).every(ruleId => this.isValidSeverity(config[ruleId])); - }, - - /** - * Merges all configurations in a given config vector. A vector is an array of objects, each containing a config - * file path and a list of subconfig indices that match the current file path. All config data is assumed to be - * cached. - * @param {Array} vector list of config files and their subconfig indices that match the current file path - * @param {Object} configCache the config cache - * @returns {Object} config object - */ - getConfigFromVector(vector, configCache) { - - const cachedConfig = configCache.getMergedVectorConfig(vector); - - if (cachedConfig) { - return cachedConfig; - } - - debug("Using config from partial cache"); - - const subvector = Array.from(vector); - let nearestCacheIndex = subvector.length - 1, - partialCachedConfig; - - while (nearestCacheIndex >= 0) { - partialCachedConfig = configCache.getMergedVectorConfig(subvector); - if (partialCachedConfig) { - break; - } - subvector.pop(); - nearestCacheIndex--; - } - - if (!partialCachedConfig) { - partialCachedConfig = {}; - } - - let finalConfig = partialCachedConfig; - - // Start from entry immediately following nearest cached config (first uncached entry) - for (let i = nearestCacheIndex + 1; i < vector.length; i++) { - finalConfig = this.mergeVectorEntry(finalConfig, vector[i], configCache); - configCache.setMergedVectorConfig(vector.slice(0, i + 1), finalConfig); - } - - return finalConfig; - }, - - /** - * Merges the config options from a single vector entry into the supplied config. - * @param {Object} config the base config to merge the vector entry's options into - * @param {Object} vectorEntry a single entry from a vector, consisting of a config file path and an array of - * matching override indices - * @param {Object} configCache the config cache - * @returns {Object} merged config object - */ - mergeVectorEntry(config, vectorEntry, configCache) { - const vectorEntryConfig = Object.assign({}, configCache.getConfig(vectorEntry.filePath)); - let mergedConfig = Object.assign({}, config), - overrides; - - if (vectorEntryConfig.overrides) { - overrides = vectorEntryConfig.overrides.filter( - (override, overrideIndex) => vectorEntry.matchingOverrides.indexOf(overrideIndex) !== -1 - ); - } else { - overrides = []; - } - - mergedConfig = this.merge(mergedConfig, vectorEntryConfig); - - delete mergedConfig.overrides; - - mergedConfig = overrides.reduce((lastConfig, override) => this.merge(lastConfig, override), mergedConfig); - - if (mergedConfig.filePath) { - delete mergedConfig.filePath; - delete mergedConfig.baseDirectory; - } else if (mergedConfig.files) { - delete mergedConfig.files; - } - - return mergedConfig; - }, - - /** - * Checks that the specified file path matches all of the supplied glob patterns. - * @param {string} filePath The file path to test patterns against - * @param {string|string[]} patterns One or more glob patterns, of which at least one should match the file path - * @param {string|string[]} [excludedPatterns] One or more glob patterns, of which none should match the file path - * @returns {boolean} True if all the supplied patterns match the file path, false otherwise - */ - pathMatchesGlobs(filePath, patterns, excludedPatterns) { - const patternList = [].concat(patterns); - const excludedPatternList = [].concat(excludedPatterns || []); - - patternList.concat(excludedPatternList).forEach(pattern => { - if (path.isAbsolute(pattern) || pattern.includes("..")) { - throw new Error(`Invalid override pattern (expected relative path not containing '..'): ${pattern}`); - } - }); - - const opts = { matchBase: true }; - - return patternList.some(pattern => minimatch(filePath, pattern, opts)) && - !excludedPatternList.some(excludedPattern => minimatch(filePath, excludedPattern, opts)); - }, - - /** - * Normalizes a value for a global in a config - * @param {(boolean|string|null)} configuredValue The value given for a global in configuration or in - * a global directive comment - * @returns {("readable"|"writeable"|"off")} The value normalized as a string - */ - normalizeConfigGlobal(configuredValue) { - switch (configuredValue) { - case "off": - return "off"; - - case true: - case "true": - case "writeable": - case "writable": - return "writeable"; - - case null: - case false: - case "false": - case "readable": - case "readonly": - return "readable"; - - // Fallback to minimize compatibility impact - default: - return "writeable"; - } - } -}; diff --git a/tools/node_modules/eslint/lib/config/config-rule.js b/tools/node_modules/eslint/lib/config/config-rule.js deleted file mode 100644 index 29aac0b9a1a518..00000000000000 --- a/tools/node_modules/eslint/lib/config/config-rule.js +++ /dev/null @@ -1,319 +0,0 @@ -/** - * @fileoverview Create configurations for a rule - * @author Ian VanSchooten - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const Rules = require("../rules"), - builtInRules = require("../built-in-rules-index"); - -const rules = new Rules(); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Wrap all of the elements of an array into arrays. - * @param {*[]} xs Any array. - * @returns {Array[]} An array of arrays. - */ -function explodeArray(xs) { - return xs.reduce((accumulator, x) => { - accumulator.push([x]); - return accumulator; - }, []); -} - -/** - * Mix two arrays such that each element of the second array is concatenated - * onto each element of the first array. - * - * For example: - * combineArrays([a, [b, c]], [x, y]); // -> [[a, x], [a, y], [b, c, x], [b, c, y]] - * - * @param {Array} arr1 The first array to combine. - * @param {Array} arr2 The second array to combine. - * @returns {Array} A mixture of the elements of the first and second arrays. - */ -function combineArrays(arr1, arr2) { - const res = []; - - if (arr1.length === 0) { - return explodeArray(arr2); - } - if (arr2.length === 0) { - return explodeArray(arr1); - } - arr1.forEach(x1 => { - arr2.forEach(x2 => { - res.push([].concat(x1, x2)); - }); - }); - return res; -} - -/** - * Group together valid rule configurations based on object properties - * - * e.g.: - * groupByProperty([ - * {before: true}, - * {before: false}, - * {after: true}, - * {after: false} - * ]); - * - * will return: - * [ - * [{before: true}, {before: false}], - * [{after: true}, {after: false}] - * ] - * - * @param {Object[]} objects Array of objects, each with one property/value pair - * @returns {Array[]} Array of arrays of objects grouped by property - */ -function groupByProperty(objects) { - 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(prop => groupedObj[prop]); -} - - -//------------------------------------------------------------------------------ -// Private -//------------------------------------------------------------------------------ - -/** - * Configuration settings for a rule. - * - * A configuration can be a single number (severity), or an array where the first - * element in the array is the severity, and is the only required element. - * Configs may also have one or more additional elements to specify rule - * configuration or options. - * - * @typedef {array|number} ruleConfig - * @param {number} 0 The rule's severity (0, 1, 2). - */ - -/** - * Object whose keys are rule names and values are arrays of valid ruleConfig items - * which should be linted against the target source code to determine error counts. - * (a ruleConfigSet.ruleConfigs). - * - * e.g. rulesConfig = { - * "comma-dangle": [2, [2, "always"], [2, "always-multiline"], [2, "never"]], - * "no-console": [2] - * } - * @typedef rulesConfig - */ - - -/** - * Create valid rule configurations by combining two arrays, - * with each array containing multiple objects each with a - * single property/value pair and matching properties. - * - * e.g.: - * combinePropertyObjects( - * [{before: true}, {before: false}], - * [{after: true}, {after: false}] - * ); - * - * will return: - * [ - * {before: true, after: true}, - * {before: true, after: false}, - * {before: false, after: true}, - * {before: false, after: false} - * ] - * - * @param {Object[]} objArr1 Single key/value objects, all with the same key - * @param {Object[]} objArr2 Single key/value objects, all with another key - * @returns {Object[]} Combined objects for each combination of input properties and values - */ -function combinePropertyObjects(objArr1, objArr2) { - const res = []; - - if (objArr1.length === 0) { - return objArr2; - } - if (objArr2.length === 0) { - return objArr1; - } - objArr1.forEach(obj1 => { - objArr2.forEach(obj2 => { - const combinedObj = {}; - const obj1Props = Object.keys(obj1); - const obj2Props = Object.keys(obj2); - - obj1Props.forEach(prop1 => { - combinedObj[prop1] = obj1[prop1]; - }); - obj2Props.forEach(prop2 => { - combinedObj[prop2] = obj2[prop2]; - }); - res.push(combinedObj); - }); - }); - return res; -} - -/** - * Creates a new instance of a rule configuration set - * - * A rule configuration set is an array of configurations that are valid for a - * given rule. For example, the configuration set for the "semi" rule could be: - * - * ruleConfigSet.ruleConfigs // -> [[2], [2, "always"], [2, "never"]] - * - * Rule configuration set class - */ -class RuleConfigSet { - - /** - * @param {ruleConfig[]} configs Valid rule configurations - */ - constructor(configs) { - - /** - * Stored valid rule configurations for this instance - * @type {array} - */ - this.ruleConfigs = configs || []; - } - - /** - * Add a severity level to the front of all configs in the instance. - * This should only be called after all configs have been added to the instance. - * - * @returns {void} - */ - addErrorSeverity() { - const severity = 2; - - this.ruleConfigs = this.ruleConfigs.map(config => { - config.unshift(severity); - return config; - }); - - // Add a single config at the beginning consisting of only the severity - this.ruleConfigs.unshift(severity); - } - - /** - * Add rule configs from an array of strings (schema enums) - * @param {string[]} enums Array of valid rule options (e.g. ["always", "never"]) - * @returns {void} - */ - addEnums(enums) { - this.ruleConfigs = this.ruleConfigs.concat(combineArrays(this.ruleConfigs, enums)); - } - - /** - * Add rule configurations from a schema object - * @param {Object} obj Schema item with type === "object" - * @returns {boolean} true if at least one schema for the object could be generated, false otherwise - */ - addObject(obj) { - const objectConfigSet = { - objectConfigs: [], - add(property, values) { - for (let idx = 0; idx < values.length; idx++) { - const optionObj = {}; - - optionObj[property] = values[idx]; - this.objectConfigs.push(optionObj); - } - }, - - combine() { - this.objectConfigs = groupByProperty(this.objectConfigs).reduce((accumulator, objArr) => combinePropertyObjects(accumulator, objArr), []); - } - }; - - /* - * 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(prop => { - if (obj.properties[prop].enum) { - objectConfigSet.add(prop, obj.properties[prop].enum); - } - if (obj.properties[prop].type && obj.properties[prop].type === "boolean") { - objectConfigSet.add(prop, [true, false]); - } - }); - objectConfigSet.combine(); - - if (objectConfigSet.objectConfigs.length > 0) { - this.ruleConfigs = this.ruleConfigs.concat(combineArrays(this.ruleConfigs, objectConfigSet.objectConfigs)); - return true; - } - - return false; - } -} - -/** - * Generate valid rule configurations based on a schema object - * @param {Object} schema A rule's schema object - * @returns {Array[]} Valid rule configurations - */ -function generateConfigsFromSchema(schema) { - const configSet = new RuleConfigSet(); - - if (Array.isArray(schema)) { - for (const opt of schema) { - if (opt.enum) { - configSet.addEnums(opt.enum); - } else if (opt.type && opt.type === "object") { - if (!configSet.addObject(opt)) { - break; - } - - // TODO (IanVS): support oneOf - } else { - - // If we don't know how to fill in this option, don't fill in any of the following options. - break; - } - } - } - configSet.addErrorSeverity(); - return configSet.ruleConfigs; -} - -/** - * Generate possible rule configurations for all of the core rules - * @returns {rulesConfig} Hash of rule names and arrays of possible configurations - */ -function createCoreRuleConfigs() { - return Object.keys(builtInRules).reduce((accumulator, id) => { - const rule = rules.get(id); - const schema = (typeof rule === "function") ? rule.schema : rule.meta.schema; - - accumulator[id] = generateConfigsFromSchema(schema); - return accumulator; - }, {}); -} - - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = { - generateConfigsFromSchema, - createCoreRuleConfigs -}; diff --git a/tools/node_modules/eslint/lib/config/config-validator.js b/tools/node_modules/eslint/lib/config/config-validator.js deleted file mode 100644 index 0c63b68f76c943..00000000000000 --- a/tools/node_modules/eslint/lib/config/config-validator.js +++ /dev/null @@ -1,279 +0,0 @@ -/** - * @fileoverview Validates configs. - * @author Brandon Mills - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const path = require("path"), - ajv = require("../util/ajv"), - lodash = require("lodash"), - configSchema = require("../../conf/config-schema.js"), - util = require("util"); - -const ruleValidators = new WeakMap(); - -//------------------------------------------------------------------------------ -// Private -//------------------------------------------------------------------------------ -let validateSchema; - -// Defitions for deprecation warnings. -const deprecationWarningMessages = { - ESLINT_LEGACY_ECMAFEATURES: "The 'ecmaFeatures' config file property is deprecated, and has no effect.", - ESLINT_LEGACY_OBJECT_REST_SPREAD: "The 'parserOptions.ecmaFeatures.experimentalObjectRestSpread' option is deprecated. Use 'parserOptions.ecmaVersion' instead." -}; -const severityMap = { - error: 2, - warn: 1, - off: 0 -}; - -/** - * Gets a complete options schema for a rule. - * @param {{create: Function, schema: (Array|null)}} rule A new-style rule object - * @returns {Object} JSON Schema for the rule's options. - */ -function getRuleOptionsSchema(rule) { - const schema = rule.schema || rule.meta && rule.meta.schema; - - // Given a tuple of schemas, insert warning level at the beginning - if (Array.isArray(schema)) { - if (schema.length) { - return { - type: "array", - items: schema, - minItems: 0, - maxItems: schema.length - }; - } - return { - type: "array", - minItems: 0, - maxItems: 0 - }; - - } - - // Given a full schema, leave it alone - return schema || null; -} - -/** - * 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; - const normSeverity = typeof severity === "string" ? severityMap[severity.toLowerCase()] : severity; - - if (normSeverity === 0 || normSeverity === 1 || normSeverity === 2) { - return normSeverity; - } - - 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`); - -} - -/** - * Validates the non-severity options passed to a rule, based on its schema. - * @param {{create: Function}} rule The rule to validate - * @param {Array} localOptions The options for the rule, excluding severity - * @returns {void} - */ -function validateRuleSchema(rule, localOptions) { - if (!ruleValidators.has(rule)) { - const schema = getRuleOptionsSchema(rule); - - if (schema) { - ruleValidators.set(rule, ajv.compile(schema)); - } - } - - const validateRule = ruleValidators.get(rule); - - if (validateRule) { - validateRule(localOptions); - if (validateRule.errors) { - throw new Error(validateRule.errors.map( - error => `\tValue ${JSON.stringify(error.data)} ${error.message}.\n` - ).join("")); - } - } -} - -/** - * Validates a rule's options against its schema. - * @param {{create: Function}|null} rule The rule that the config is being validated for - * @param {string} ruleId The rule's unique name. - * @param {Array|number} options The given options for the rule. - * @param {string|null} source The name of the configuration source to report in any errors. If null or undefined, - * no source is prepended to the message. - * @returns {void} - */ -function validateRuleOptions(rule, ruleId, options, source) { - if (!rule) { - return; - } - try { - const severity = validateRuleSeverity(options); - - if (severity !== 0) { - validateRuleSchema(rule, Array.isArray(options) ? options.slice(1) : []); - } - } catch (err) { - const enhancedMessage = `Configuration for rule "${ruleId}" is invalid:\n${err.message}`; - - if (typeof source === "string") { - throw new Error(`${source}:\n\t${enhancedMessage}`); - } else { - throw new Error(enhancedMessage); - } - } -} - -/** - * Validates an environment object - * @param {Object} environment The environment config object to validate. - * @param {string} source The name of the configuration source to report in any errors. - * @param {Environments} envContext Env context - * @returns {void} - */ -function validateEnvironment(environment, source, envContext) { - - // not having an environment is ok - if (!environment) { - return; - } - - Object.keys(environment).forEach(env => { - if (!envContext.get(env)) { - const message = `${source}:\n\tEnvironment key "${env}" is unknown\n`; - - throw new Error(message); - } - }); -} - -/** - * Validates a rules config object - * @param {Object} rulesConfig The rules config object to validate. - * @param {string} source The name of the configuration source to report in any errors. - * @param {function(string): {create: Function}} ruleMapper A mapper function from strings to loaded rules - * @returns {void} - */ -function validateRules(rulesConfig, source, ruleMapper) { - if (!rulesConfig) { - return; - } - - Object.keys(rulesConfig).forEach(id => { - validateRuleOptions(ruleMapper(id), id, rulesConfig[id], source); - }); -} - -/** - * Formats an array of schema validation errors. - * @param {Array} errors An array of error messages to format. - * @returns {string} Formatted error message - */ -function formatErrors(errors) { - return errors.map(error => { - if (error.keyword === "additionalProperties") { - const formattedPropertyPath = error.dataPath.length ? `${error.dataPath.slice(1)}.${error.params.additionalProperty}` : error.params.additionalProperty; - - return `Unexpected top-level property "${formattedPropertyPath}"`; - } - if (error.keyword === "type") { - const formattedField = error.dataPath.slice(1); - const formattedExpectedType = Array.isArray(error.schema) ? error.schema.join("/") : error.schema; - const formattedValue = JSON.stringify(error.data); - - return `Property "${formattedField}" is the wrong type (expected ${formattedExpectedType} but got \`${formattedValue}\`)`; - } - - const field = error.dataPath[0] === "." ? error.dataPath.slice(1) : error.dataPath; - - return `"${field}" ${error.message}. Value: ${JSON.stringify(error.data)}`; - }).map(message => `\t- ${message}.\n`).join(""); -} - -/** - * Emits a deprecation warning containing a given filepath. A new deprecation warning is emitted - * for each unique file path, but repeated invocations with the same file path have no effect. - * No warnings are emitted if the `--no-deprecation` or `--no-warnings` Node runtime flags are active. - * @param {string} source The name of the configuration source to report the warning for. - * @param {string} errorCode The warning message to show. - * @returns {void} - */ -const emitDeprecationWarning = lodash.memoize((source, errorCode) => { - const rel = path.relative(process.cwd(), source); - const message = deprecationWarningMessages[errorCode]; - - process.emitWarning( - `${message} (found in "${rel}")`, - "DeprecationWarning", - errorCode - ); -}); - -/** - * Validates the top level properties of the config object. - * @param {Object} config The config object to validate. - * @param {string} source The name of the configuration source to report in any errors. - * @returns {void} - */ -function validateConfigSchema(config, source) { - validateSchema = validateSchema || ajv.compile(configSchema); - - if (!validateSchema(config)) { - throw new Error(`ESLint configuration in ${source} is invalid:\n${formatErrors(validateSchema.errors)}`); - } - - if (Object.hasOwnProperty.call(config, "ecmaFeatures")) { - emitDeprecationWarning(source, "ESLINT_LEGACY_ECMAFEATURES"); - } - - if ( - (config.parser || "espree") === "espree" && - config.parserOptions && - config.parserOptions.ecmaFeatures && - config.parserOptions.ecmaFeatures.experimentalObjectRestSpread - ) { - emitDeprecationWarning(source, "ESLINT_LEGACY_OBJECT_REST_SPREAD"); - } -} - -/** - * Validates an entire config object. - * @param {Object} config The config object to validate. - * @param {string} source The name of the configuration source to report in any errors. - * @param {function(string): {create: Function}} ruleMapper A mapper function from rule IDs to defined rules - * @param {Environments} envContext The env context - * @returns {void} - */ -function validate(config, source, ruleMapper, envContext) { - validateConfigSchema(config, source); - validateRules(config.rules, source, ruleMapper); - validateEnvironment(config.env, source, envContext); - - for (const override of config.overrides || []) { - validateRules(override.rules, source, ruleMapper); - validateEnvironment(override.env, source, envContext); - } -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = { - getRuleOptionsSchema, - validate, - validateRuleOptions -}; diff --git a/tools/node_modules/eslint/lib/config/environments.js b/tools/node_modules/eslint/lib/config/environments.js deleted file mode 100644 index 1ec9438af5de2a..00000000000000 --- a/tools/node_modules/eslint/lib/config/environments.js +++ /dev/null @@ -1,84 +0,0 @@ -/** - * @fileoverview Environments manager - * @author Nicholas C. Zakas - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const envs = require("../../conf/environments"); - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -class Environments { - - /** - * create env context - */ - constructor() { - this._environments = new Map(); - - this.load(); - } - - /** - * Loads the default environments. - * @returns {void} - * @private - */ - load() { - Object.keys(envs).forEach(envName => { - this._environments.set(envName, envs[envName]); - }); - } - - /** - * Gets the environment with the given name. - * @param {string} name The name of the environment to retrieve. - * @returns {Object?} The environment object or null if not found. - */ - get(name) { - return this._environments.get(name) || null; - } - - /** - * Gets all the environment present - * @returns {Object} The environment object for each env name - */ - getAll() { - return Array.from(this._environments).reduce((coll, env) => { - coll[env[0]] = env[1]; - return coll; - }, {}); - } - - /** - * Defines an environment. - * @param {string} name The name of the environment. - * @param {Object} env The environment settings. - * @returns {void} - */ - define(name, env) { - this._environments.set(name, env); - } - - /** - * Imports all environments from a plugin. - * @param {Object} plugin The plugin object. - * @param {string} pluginName The name of the plugin. - * @returns {void} - */ - importPlugin(plugin, pluginName) { - if (plugin.environments) { - Object.keys(plugin.environments).forEach(envName => { - this.define(`${pluginName}/${envName}`, plugin.environments[envName]); - }); - } - } -} - -module.exports = Environments; diff --git a/tools/node_modules/eslint/lib/config/plugins.js b/tools/node_modules/eslint/lib/config/plugins.js deleted file mode 100644 index f32cc26c33f8fa..00000000000000 --- a/tools/node_modules/eslint/lib/config/plugins.js +++ /dev/null @@ -1,169 +0,0 @@ -/** - * @fileoverview Plugins manager - * @author Nicholas C. Zakas - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const debug = require("debug")("eslint:plugins"); -const naming = require("../util/naming"); -const path = require("path"); - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -/** - * Plugin class - */ -class Plugins { - - /** - * Creates the plugins context - * @param {Environments} envContext - env context - * @param {function(string, Rule): void} defineRule - Callback for when a plugin is defined which introduces rules - */ - constructor(envContext, defineRule) { - this._plugins = Object.create(null); - this._environments = envContext; - this._defineRule = defineRule; - } - - /** - * Defines a plugin with a given name rather than loading from disk. - * @param {string} pluginName The name of the plugin to load. - * @param {Object} plugin The plugin object. - * @returns {void} - */ - define(pluginName, plugin) { - const longName = naming.normalizePackageName(pluginName, "eslint-plugin"); - const shortName = naming.getShorthandName(longName, "eslint-plugin"); - - // load up environments and rules - this._plugins[shortName] = plugin; - this._environments.importPlugin(plugin, shortName); - - if (plugin.rules) { - Object.keys(plugin.rules).forEach(ruleId => { - const qualifiedRuleId = `${shortName}/${ruleId}`, - rule = plugin.rules[ruleId]; - - this._defineRule(qualifiedRuleId, rule); - }); - } - } - - /** - * Gets a plugin with the given name. - * @param {string} pluginName The name of the plugin to retrieve. - * @returns {Object} The plugin or null if not loaded. - */ - get(pluginName) { - return this._plugins[pluginName] || null; - } - - /** - * Returns all plugins that are loaded. - * @returns {Object} The plugins cache. - */ - getAll() { - return this._plugins; - } - - /** - * Loads a plugin with the given name. - * @param {string} pluginName The name of the plugin to load. - * @returns {void} - * @throws {Error} If the plugin cannot be loaded. - */ - load(pluginName) { - const longName = naming.normalizePackageName(pluginName, "eslint-plugin"); - const shortName = naming.getShorthandName(longName, "eslint-plugin"); - let plugin = null; - - if (pluginName.match(/\s+/)) { - const whitespaceError = new Error(`Whitespace found in plugin name '${pluginName}'`); - - whitespaceError.messageTemplate = "whitespace-found"; - whitespaceError.messageData = { - pluginName: longName - }; - throw whitespaceError; - } - - if (!this._plugins[shortName]) { - try { - plugin = require(longName); - } catch (pluginLoadErr) { - try { - - // Check whether the plugin exists - require.resolve(longName); - } catch (missingPluginErr) { - - // If the plugin can't be resolved, display the missing plugin error (usually a config or install error) - debug(`Failed to load plugin ${longName}.`); - missingPluginErr.message = `Failed to load plugin ${pluginName}: ${missingPluginErr.message}`; - missingPluginErr.messageTemplate = "plugin-missing"; - missingPluginErr.messageData = { - pluginName: longName, - eslintPath: path.resolve(__dirname, "../..") - }; - throw missingPluginErr; - } - - // Otherwise, the plugin exists and is throwing on module load for some reason, so print the stack trace. - throw pluginLoadErr; - } - - // This step is costly, so skip if debug is disabled - if (debug.enabled) { - const resolvedPath = require.resolve(longName); - - let version = null; - - try { - version = require(`${longName}/package.json`).version; - } catch (e) { - - // Do nothing - } - - const loadedPluginAndVersion = version - ? `${longName}@${version}` - : `${longName}, version unknown`; - - debug(`Loaded plugin ${pluginName} (${loadedPluginAndVersion}) (from ${resolvedPath})`); - } - - this.define(pluginName, plugin); - } - } - - /** - * Loads all plugins from an array. - * @param {string[]} pluginNames An array of plugins names. - * @returns {void} - * @throws {Error} If a plugin cannot be loaded. - * @throws {Error} If "plugins" in config is not an array - */ - loadAll(pluginNames) { - - // if "plugins" in config is not an array, throw an error so user can fix their config. - if (!Array.isArray(pluginNames)) { - const pluginNotArrayMessage = "ESLint configuration error: \"plugins\" value must be an array"; - - debug(`${pluginNotArrayMessage}: ${JSON.stringify(pluginNames)}`); - - throw new Error(pluginNotArrayMessage); - } - - // load each plugin by name - pluginNames.forEach(this.load, this); - } -} - -module.exports = Plugins; diff --git a/tools/node_modules/eslint/lib/formatters/checkstyle.js b/tools/node_modules/eslint/lib/formatters/checkstyle.js deleted file mode 100644 index c807871930bdec..00000000000000 --- a/tools/node_modules/eslint/lib/formatters/checkstyle.js +++ /dev/null @@ -1,60 +0,0 @@ -/** - * @fileoverview CheckStyle XML reporter - * @author Ian Christian Myers - */ -"use strict"; - -const xmlEscape = require("../util/xml-escape"); - -//------------------------------------------------------------------------------ -// Helper Functions -//------------------------------------------------------------------------------ - -/** - * Returns the severity of warning or error - * @param {Object} message message object to examine - * @returns {string} severity level - * @private - */ -function getMessageType(message) { - if (message.fatal || message.severity === 2) { - return "error"; - } - return "warning"; - -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = function(results) { - - let output = ""; - - output += ""; - output += ""; - - results.forEach(result => { - const messages = result.messages; - - output += ``; - - messages.forEach(message => { - output += [ - `` - ].join(" "); - }); - - output += ""; - - }); - - output += ""; - - return output; -}; diff --git a/tools/node_modules/eslint/lib/formatters/codeframe.js b/tools/node_modules/eslint/lib/formatters/codeframe.js deleted file mode 100644 index a42872c5a1deb2..00000000000000 --- a/tools/node_modules/eslint/lib/formatters/codeframe.js +++ /dev/null @@ -1,138 +0,0 @@ -/** - * @fileoverview Codeframe reporter - * @author Vitor Balocco - */ -"use strict"; - -const chalk = require("chalk"); -const { codeFrameColumns } = require("@babel/code-frame"); -const path = require("path"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Given a word and a count, append an s if count is not one. - * @param {string} word A word in its singular form. - * @param {number} count A number controlling whether word should be pluralized. - * @returns {string} The original word with an s on the end if count is not one. - */ -function pluralize(word, count) { - return (count === 1 ? word : `${word}s`); -} - -/** - * Gets a formatted relative file path from an absolute path and a line/column in the file. - * @param {string} filePath The absolute file path to format. - * @param {number} line The line from the file to use for formatting. - * @param {number} column The column from the file to use for formatting. - * @returns {string} The formatted file path. - */ -function formatFilePath(filePath, line, column) { - let relPath = path.relative(process.cwd(), filePath); - - if (line && column) { - relPath += `:${line}:${column}`; - } - - return chalk.green(relPath); -} - -/** - * Gets the formatted output for a given message. - * @param {Object} message The object that represents this message. - * @param {Object} parentResult The result object that this message belongs to. - * @returns {string} The formatted output. - */ -function formatMessage(message, parentResult) { - const type = (message.fatal || message.severity === 2) ? chalk.red("error") : chalk.yellow("warning"); - const msg = `${chalk.bold(message.message.replace(/([^ ])\.$/, "$1"))}`; - const ruleId = message.fatal ? "" : chalk.dim(`(${message.ruleId})`); - const filePath = formatFilePath(parentResult.filePath, message.line, message.column); - const sourceCode = parentResult.output ? parentResult.output : parentResult.source; - - const firstLine = [ - `${type}:`, - `${msg}`, - ruleId ? `${ruleId}` : "", - sourceCode ? `at ${filePath}:` : `at ${filePath}` - ].filter(String).join(" "); - - const result = [firstLine]; - - if (sourceCode) { - result.push( - codeFrameColumns(sourceCode, { start: { line: message.line, column: message.column } }, { highlightCode: false }) - ); - } - - return result.join("\n"); -} - -/** - * Gets the formatted output summary for a given number of errors and warnings. - * @param {number} errors The number of errors. - * @param {number} warnings The number of warnings. - * @param {number} fixableErrors The number of fixable errors. - * @param {number} fixableWarnings The number of fixable warnings. - * @returns {string} The formatted output summary. - */ -function formatSummary(errors, warnings, fixableErrors, fixableWarnings) { - const summaryColor = errors > 0 ? "red" : "yellow"; - const summary = []; - const fixablesSummary = []; - - if (errors > 0) { - summary.push(`${errors} ${pluralize("error", errors)}`); - } - - if (warnings > 0) { - summary.push(`${warnings} ${pluralize("warning", warnings)}`); - } - - if (fixableErrors > 0) { - fixablesSummary.push(`${fixableErrors} ${pluralize("error", fixableErrors)}`); - } - - if (fixableWarnings > 0) { - fixablesSummary.push(`${fixableWarnings} ${pluralize("warning", fixableWarnings)}`); - } - - let output = chalk[summaryColor].bold(`${summary.join(" and ")} found.`); - - if (fixableErrors || fixableWarnings) { - output += chalk[summaryColor].bold(`\n${fixablesSummary.join(" and ")} potentially fixable with the \`--fix\` option.`); - } - - return output; -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = function(results) { - let errors = 0; - let warnings = 0; - let fixableErrors = 0; - let fixableWarnings = 0; - - const resultsWithMessages = results.filter(result => result.messages.length > 0); - - let output = resultsWithMessages.reduce((resultsOutput, result) => { - const messages = result.messages.map(message => `${formatMessage(message, result)}\n\n`); - - errors += result.errorCount; - warnings += result.warningCount; - fixableErrors += result.fixableErrorCount; - fixableWarnings += result.fixableWarningCount; - - return resultsOutput.concat(messages); - }, []).join("\n"); - - output += "\n"; - output += formatSummary(errors, warnings, fixableErrors, fixableWarnings); - - return (errors + warnings) > 0 ? output : ""; -}; diff --git a/tools/node_modules/eslint/lib/formatters/compact.js b/tools/node_modules/eslint/lib/formatters/compact.js deleted file mode 100644 index 2b540bde2361c1..00000000000000 --- a/tools/node_modules/eslint/lib/formatters/compact.js +++ /dev/null @@ -1,60 +0,0 @@ -/** - * @fileoverview Compact reporter - * @author Nicholas C. Zakas - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Helper Functions -//------------------------------------------------------------------------------ - -/** - * Returns the severity of warning or error - * @param {Object} message message object to examine - * @returns {string} severity level - * @private - */ -function getMessageType(message) { - if (message.fatal || message.severity === 2) { - return "Error"; - } - return "Warning"; - -} - - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = function(results) { - - let output = "", - total = 0; - - results.forEach(result => { - - const messages = result.messages; - - total += messages.length; - - messages.forEach(message => { - - output += `${result.filePath}: `; - output += `line ${message.line || 0}`; - output += `, col ${message.column || 0}`; - output += `, ${getMessageType(message)}`; - output += ` - ${message.message}`; - output += message.ruleId ? ` (${message.ruleId})` : ""; - output += "\n"; - - }); - - }); - - if (total > 0) { - output += `\n${total} problem${total !== 1 ? "s" : ""}`; - } - - return output; -}; diff --git a/tools/node_modules/eslint/lib/formatters/html-template-message.html b/tools/node_modules/eslint/lib/formatters/html-template-message.html deleted file mode 100644 index bc353502050d0c..00000000000000 --- a/tools/node_modules/eslint/lib/formatters/html-template-message.html +++ /dev/null @@ -1,8 +0,0 @@ - - <%= lineNumber %>:<%= columnNumber %> - <%= severityName %> - <%- message %> - - <%= ruleId %> - - diff --git a/tools/node_modules/eslint/lib/formatters/html-template-page.html b/tools/node_modules/eslint/lib/formatters/html-template-page.html deleted file mode 100644 index 4016576fa06713..00000000000000 --- a/tools/node_modules/eslint/lib/formatters/html-template-page.html +++ /dev/null @@ -1,115 +0,0 @@ - - - - - ESLint Report - - - -
-

ESLint Report

-
- <%= reportSummary %> - Generated on <%= date %> -
-
- - - <%= results %> - -
- - - diff --git a/tools/node_modules/eslint/lib/formatters/html-template-result.html b/tools/node_modules/eslint/lib/formatters/html-template-result.html deleted file mode 100644 index f4a55933c2047e..00000000000000 --- a/tools/node_modules/eslint/lib/formatters/html-template-result.html +++ /dev/null @@ -1,6 +0,0 @@ - - - [+] <%- filePath %> - <%- summary %> - - diff --git a/tools/node_modules/eslint/lib/formatters/html.js b/tools/node_modules/eslint/lib/formatters/html.js deleted file mode 100644 index d450f9dee24f57..00000000000000 --- a/tools/node_modules/eslint/lib/formatters/html.js +++ /dev/null @@ -1,127 +0,0 @@ -/** - * @fileoverview HTML reporter - * @author Julian Laval - */ -"use strict"; - -const lodash = require("lodash"); -const fs = require("fs"); -const path = require("path"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const pageTemplate = lodash.template(fs.readFileSync(path.join(__dirname, "html-template-page.html"), "utf-8")); -const messageTemplate = lodash.template(fs.readFileSync(path.join(__dirname, "html-template-message.html"), "utf-8")); -const resultTemplate = lodash.template(fs.readFileSync(path.join(__dirname, "html-template-result.html"), "utf-8")); - -/** - * Given a word and a count, append an s if count is not one. - * @param {string} word A word in its singular form. - * @param {int} count A number controlling whether word should be pluralized. - * @returns {string} The original word with an s on the end if count is not one. - */ -function pluralize(word, count) { - return (count === 1 ? word : `${word}s`); -} - -/** - * Renders text along the template of x problems (x errors, x warnings) - * @param {string} totalErrors Total errors - * @param {string} totalWarnings Total warnings - * @returns {string} The formatted string, pluralized where necessary - */ -function renderSummary(totalErrors, totalWarnings) { - const totalProblems = totalErrors + totalWarnings; - let renderedText = `${totalProblems} ${pluralize("problem", totalProblems)}`; - - if (totalProblems !== 0) { - renderedText += ` (${totalErrors} ${pluralize("error", totalErrors)}, ${totalWarnings} ${pluralize("warning", totalWarnings)})`; - } - return renderedText; -} - -/** - * Get the color based on whether there are errors/warnings... - * @param {string} totalErrors Total errors - * @param {string} totalWarnings Total warnings - * @returns {int} The color code (0 = green, 1 = yellow, 2 = red) - */ -function renderColor(totalErrors, totalWarnings) { - if (totalErrors !== 0) { - return 2; - } - if (totalWarnings !== 0) { - return 1; - } - return 0; -} - -/** - * Get HTML (table rows) describing the messages. - * @param {Array} messages Messages. - * @param {int} parentIndex Index of the parent HTML row. - * @returns {string} HTML (table rows) describing the messages. - */ -function renderMessages(messages, parentIndex) { - - /** - * Get HTML (table row) describing a message. - * @param {Object} message Message. - * @returns {string} HTML (table row) describing a message. - */ - return lodash.map(messages, message => { - const lineNumber = message.line || 0; - const columnNumber = message.column || 0; - - return messageTemplate({ - parentIndex, - lineNumber, - columnNumber, - severityNumber: message.severity, - severityName: message.severity === 1 ? "Warning" : "Error", - message: message.message, - ruleId: message.ruleId - }); - }).join("\n"); -} - -/** - * @param {Array} results Test results. - * @returns {string} HTML string describing the results. - */ -function renderResults(results) { - 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"); -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = function(results) { - let totalErrors, - totalWarnings; - - totalErrors = 0; - totalWarnings = 0; - - // Iterate over results to get totals - results.forEach(result => { - totalErrors += result.errorCount; - totalWarnings += result.warningCount; - }); - - return pageTemplate({ - date: new Date(), - reportColor: renderColor(totalErrors, totalWarnings), - reportSummary: renderSummary(totalErrors, totalWarnings), - results: renderResults(results) - }); -}; diff --git a/tools/node_modules/eslint/lib/formatters/jslint-xml.js b/tools/node_modules/eslint/lib/formatters/jslint-xml.js deleted file mode 100644 index 14743430d8ff94..00000000000000 --- a/tools/node_modules/eslint/lib/formatters/jslint-xml.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * @fileoverview JSLint XML reporter - * @author Ian Christian Myers - */ -"use strict"; - -const xmlEscape = require("../util/xml-escape"); - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = function(results) { - - let output = ""; - - output += ""; - output += ""; - - results.forEach(result => { - const messages = result.messages; - - output += ``; - - messages.forEach(message => { - output += [ - `` - ].join(" "); - }); - - output += ""; - - }); - - output += ""; - - return output; -}; diff --git a/tools/node_modules/eslint/lib/formatters/json.js b/tools/node_modules/eslint/lib/formatters/json.js deleted file mode 100644 index 82138af1874855..00000000000000 --- a/tools/node_modules/eslint/lib/formatters/json.js +++ /dev/null @@ -1,13 +0,0 @@ -/** - * @fileoverview JSON reporter - * @author Burak Yigit Kaya aka BYK - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = function(results) { - return JSON.stringify(results); -}; diff --git a/tools/node_modules/eslint/lib/formatters/junit.js b/tools/node_modules/eslint/lib/formatters/junit.js deleted file mode 100644 index 77d548f380e2b6..00000000000000 --- a/tools/node_modules/eslint/lib/formatters/junit.js +++ /dev/null @@ -1,70 +0,0 @@ -/** - * @fileoverview jUnit Reporter - * @author Jamund Ferguson - */ -"use strict"; - -const xmlEscape = require("../util/xml-escape"); - -//------------------------------------------------------------------------------ -// Helper Functions -//------------------------------------------------------------------------------ - -/** - * Returns the severity of warning or error - * @param {Object} message message object to examine - * @returns {string} severity level - * @private - */ -function getMessageType(message) { - if (message.fatal || message.severity === 2) { - return "Error"; - } - return "Warning"; - -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = function(results) { - - let output = ""; - - output += "\n"; - output += "\n"; - - results.forEach(result => { - - const messages = result.messages; - - if (messages.length > 0) { - output += `\n`; - messages.forEach(message => { - const type = message.fatal ? "error" : "failure"; - - output += ``; - output += `<${type} message="${xmlEscape(message.message || "")}">`; - output += ""; - output += ``; - output += "\n"; - }); - output += "\n"; - } else { - output += `\n`; - output += `\n`; - output += "\n"; - } - - }); - - output += "\n"; - - return output; -}; diff --git a/tools/node_modules/eslint/lib/formatters/stylish.js b/tools/node_modules/eslint/lib/formatters/stylish.js deleted file mode 100644 index 48d70ecb3d2fad..00000000000000 --- a/tools/node_modules/eslint/lib/formatters/stylish.js +++ /dev/null @@ -1,100 +0,0 @@ -/** - * @fileoverview Stylish reporter - * @author Sindre Sorhus - */ -"use strict"; - -const chalk = require("chalk"), - stripAnsi = require("strip-ansi"), - table = require("text-table"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Given a word and a count, append an s if count is not one. - * @param {string} word A word in its singular form. - * @param {int} count A number controlling whether word should be pluralized. - * @returns {string} The original word with an s on the end if count is not one. - */ -function pluralize(word, count) { - return (count === 1 ? word : `${word}s`); -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = function(results) { - - let output = "\n", - errorCount = 0, - warningCount = 0, - fixableErrorCount = 0, - fixableWarningCount = 0, - summaryColor = "yellow"; - - results.forEach(result => { - const messages = result.messages; - - if (messages.length === 0) { - return; - } - - errorCount += result.errorCount; - warningCount += result.warningCount; - fixableErrorCount += result.fixableErrorCount; - fixableWarningCount += result.fixableWarningCount; - - output += `${chalk.underline(result.filePath)}\n`; - - output += `${table( - messages.map(message => { - let messageType; - - if (message.fatal || message.severity === 2) { - messageType = chalk.red("error"); - summaryColor = "red"; - } else { - messageType = chalk.yellow("warning"); - } - - return [ - "", - message.line || 0, - message.column || 0, - messageType, - message.message.replace(/([^ ])\.$/, "$1"), - chalk.dim(message.ruleId || "") - ]; - }), - { - align: ["", "r", "l"], - stringLength(str) { - return stripAnsi(str).length; - } - } - ).split("\n").map(el => el.replace(/(\d+)\s+(\d+)/, (m, p1, p2) => chalk.dim(`${p1}:${p2}`))).join("\n")}\n\n`; - }); - - const total = errorCount + warningCount; - - if (total > 0) { - output += chalk[summaryColor].bold([ - "\u2716 ", total, pluralize(" problem", total), - " (", errorCount, pluralize(" error", errorCount), ", ", - warningCount, pluralize(" warning", warningCount), ")\n" - ].join("")); - - if (fixableErrorCount > 0 || fixableWarningCount > 0) { - output += chalk[summaryColor].bold([ - " ", fixableErrorCount, pluralize(" error", fixableErrorCount), " and ", - fixableWarningCount, pluralize(" warning", fixableWarningCount), - " potentially fixable with the `--fix` option.\n" - ].join("")); - } - } - - return total > 0 ? output : ""; -}; diff --git a/tools/node_modules/eslint/lib/formatters/table.js b/tools/node_modules/eslint/lib/formatters/table.js deleted file mode 100644 index a74cce0d516ecc..00000000000000 --- a/tools/node_modules/eslint/lib/formatters/table.js +++ /dev/null @@ -1,159 +0,0 @@ -/** - * @fileoverview "table reporter. - * @author Gajus Kuizinas - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const chalk = require("chalk"), - table = require("table").table; - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Given a word and a count, append an "s" if count is not one. - * @param {string} word A word. - * @param {number} count Quantity. - * @returns {string} The original word with an s on the end if count is not one. - */ -function pluralize(word, count) { - return (count === 1 ? word : `${word}s`); -} - -/** - * Draws text table. - * @param {Array} messages Error messages relating to a specific file. - * @returns {string} A text table. - */ -function drawTable(messages) { - const rows = []; - - if (messages.length === 0) { - return ""; - } - - rows.push([ - chalk.bold("Line"), - chalk.bold("Column"), - chalk.bold("Type"), - chalk.bold("Message"), - chalk.bold("Rule ID") - ]); - - messages.forEach(message => { - let messageType; - - if (message.fatal || message.severity === 2) { - messageType = chalk.red("error"); - } else { - messageType = chalk.yellow("warning"); - } - - rows.push([ - message.line || 0, - message.column || 0, - messageType, - message.message, - message.ruleId || "" - ]); - }); - - return table(rows, { - columns: { - 0: { - width: 8, - wrapWord: true - }, - 1: { - width: 8, - wrapWord: true - }, - 2: { - width: 8, - wrapWord: true - }, - 3: { - paddingRight: 5, - width: 50, - wrapWord: true - }, - 4: { - width: 20, - wrapWord: true - } - }, - drawHorizontalLine(index) { - return index === 1; - } - }); -} - -/** - * Draws a report (multiple tables). - * @param {Array} results Report results for every file. - * @returns {string} A column of text tables. - */ -function drawReport(results) { - let files; - - files = results.map(result => { - if (!result.messages.length) { - return ""; - } - - return `\n${result.filePath}\n\n${drawTable(result.messages)}`; - }); - - files = files.filter(content => content.trim()); - - return files.join(""); -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = function(report) { - let result, - errorCount, - warningCount; - - result = ""; - errorCount = 0; - warningCount = 0; - - report.forEach(fileReport => { - errorCount += fileReport.errorCount; - warningCount += fileReport.warningCount; - }); - - if (errorCount || warningCount) { - result = drawReport(report); - } - - result += `\n${table([ - [ - chalk.red(pluralize(`${errorCount} Error`, errorCount)) - ], - [ - chalk.yellow(pluralize(`${warningCount} Warning`, warningCount)) - ] - ], { - columns: { - 0: { - width: 110, - wrapWord: true - } - }, - drawHorizontalLine() { - return true; - } - })}`; - - return result; -}; diff --git a/tools/node_modules/eslint/lib/formatters/tap.js b/tools/node_modules/eslint/lib/formatters/tap.js deleted file mode 100644 index 354872a0c92af3..00000000000000 --- a/tools/node_modules/eslint/lib/formatters/tap.js +++ /dev/null @@ -1,95 +0,0 @@ -/** - * @fileoverview TAP reporter - * @author Jonathan Kingston - */ -"use strict"; - -const yaml = require("js-yaml"); - -//------------------------------------------------------------------------------ -// Helper Functions -//------------------------------------------------------------------------------ - -/** - * Returns a canonical error level string based upon the error message passed in. - * @param {Object} message Individual error message provided by eslint - * @returns {string} Error level string - */ -function getMessageType(message) { - if (message.fatal || message.severity === 2) { - return "error"; - } - return "warning"; -} - -/** - * Takes in a JavaScript object and outputs a TAP diagnostics string - * @param {Object} diagnostic JavaScript object to be embedded as YAML into output. - * @returns {string} diagnostics string with YAML embedded - TAP version 13 compliant - */ -function outputDiagnostics(diagnostic) { - const prefix = " "; - let output = `${prefix}---\n`; - - output += prefix + yaml.safeDump(diagnostic).split("\n").join(`\n${prefix}`); - output += "...\n"; - return output; -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = function(results) { - let output = `TAP version 13\n1..${results.length}\n`; - - results.forEach((result, id) => { - const messages = result.messages; - let testResult = "ok"; - let diagnostics = {}; - - if (messages.length > 0) { - messages.forEach(message => { - const severity = getMessageType(message); - const diagnostic = { - message: message.message, - severity, - data: { - line: message.line || 0, - column: message.column || 0, - ruleId: message.ruleId || "" - } - }; - - // This ensures a warning message is not flagged as error - if (severity === "error") { - testResult = "not ok"; - } - - /* - * If we have multiple messages place them under a messages key - * The first error will be logged as message key - * This is to adhere to TAP 13 loosely defined specification of having a message key - */ - if ("message" in diagnostics) { - if (typeof diagnostics.messages === "undefined") { - diagnostics.messages = []; - } - diagnostics.messages.push(diagnostic); - } else { - diagnostics = diagnostic; - } - }); - } - - output += `${testResult} ${id + 1} - ${result.filePath}\n`; - - // If we have an error include diagnostics - if (messages.length > 0) { - output += outputDiagnostics(diagnostics); - } - - }); - - return output; -}; diff --git a/tools/node_modules/eslint/lib/formatters/unix.js b/tools/node_modules/eslint/lib/formatters/unix.js deleted file mode 100644 index c6c4ebbdb9f4cc..00000000000000 --- a/tools/node_modules/eslint/lib/formatters/unix.js +++ /dev/null @@ -1,58 +0,0 @@ -/** - * @fileoverview unix-style formatter. - * @author oshi-shinobu - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Helper Functions -//------------------------------------------------------------------------------ - -/** - * Returns a canonical error level string based upon the error message passed in. - * @param {Object} message Individual error message provided by eslint - * @returns {string} Error level string - */ -function getMessageType(message) { - if (message.fatal || message.severity === 2) { - return "Error"; - } - return "Warning"; - -} - - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = function(results) { - - let output = "", - total = 0; - - results.forEach(result => { - - const messages = result.messages; - - total += messages.length; - - messages.forEach(message => { - - output += `${result.filePath}:`; - output += `${message.line || 0}:`; - output += `${message.column || 0}:`; - output += ` ${message.message} `; - output += `[${getMessageType(message)}${message.ruleId ? `/${message.ruleId}` : ""}]`; - output += "\n"; - - }); - - }); - - if (total > 0) { - output += `\n${total} problem${total !== 1 ? "s" : ""}`; - } - - return output; -}; diff --git a/tools/node_modules/eslint/lib/formatters/visualstudio.js b/tools/node_modules/eslint/lib/formatters/visualstudio.js deleted file mode 100644 index 0d49431db87926..00000000000000 --- a/tools/node_modules/eslint/lib/formatters/visualstudio.js +++ /dev/null @@ -1,63 +0,0 @@ -/** - * @fileoverview Visual Studio compatible formatter - * @author Ronald Pijnacker - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Helper Functions -//------------------------------------------------------------------------------ - -/** - * Returns the severity of warning or error - * @param {Object} message message object to examine - * @returns {string} severity level - * @private - */ -function getMessageType(message) { - if (message.fatal || message.severity === 2) { - return "error"; - } - return "warning"; - -} - - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = function(results) { - - let output = "", - total = 0; - - results.forEach(result => { - - const messages = result.messages; - - total += messages.length; - - messages.forEach(message => { - - output += result.filePath; - output += `(${message.line || 0}`; - output += message.column ? `,${message.column}` : ""; - output += `): ${getMessageType(message)}`; - output += message.ruleId ? ` ${message.ruleId}` : ""; - output += ` : ${message.message}`; - output += "\n"; - - }); - - }); - - if (total === 0) { - output += "no problems"; - } else { - output += `\n${total} problem${total !== 1 ? "s" : ""}`; - } - - return output; -}; diff --git a/tools/node_modules/eslint/lib/linter.js b/tools/node_modules/eslint/lib/linter.js deleted file mode 100644 index 29505e9ac02242..00000000000000 --- a/tools/node_modules/eslint/lib/linter.js +++ /dev/null @@ -1,1070 +0,0 @@ -/** - * @fileoverview Main Linter Class - * @author Gyandeep Singh - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const eslintScope = require("eslint-scope"), - evk = require("eslint-visitor-keys"), - lodash = require("lodash"), - CodePathAnalyzer = require("./code-path-analysis/code-path-analyzer"), - ConfigOps = require("./config/config-ops"), - validator = require("./config/config-validator"), - Environments = require("./config/environments"), - applyDisableDirectives = require("./util/apply-disable-directives"), - createEmitter = require("./util/safe-emitter"), - NodeEventGenerator = require("./util/node-event-generator"), - SourceCode = require("./util/source-code"), - Traverser = require("./util/traverser"), - createReportTranslator = require("./util/report-translator"), - Rules = require("./rules"), - timing = require("./util/timing"), - ConfigCommentParser = require("./util/config-comment-parser"), - astUtils = require("./util/ast-utils"), - pkg = require("../package.json"), - SourceCodeFixer = require("./util/source-code-fixer"); - -const debug = require("debug")("eslint:linter"); -const MAX_AUTOFIX_PASSES = 10; -const DEFAULT_PARSER_NAME = "espree"; -const commentParser = new ConfigCommentParser(); - -//------------------------------------------------------------------------------ -// 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. - * @property {ScopeManager|null} scopeManager The scope manager object of this AST. - * @property {Object|null} visitorKeys The visitor keys to traverse this AST. - */ - -/** - * @typedef {Object} DisableDirective - * @property {("disable"|"enable"|"disable-line"|"disable-next-line")} type - * @property {number} line - * @property {number} column - * @property {(string|null)} ruleId - */ - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Ensures that variables representing built-in properties of the Global Object, - * and any globals declared by special block comments, are present in the global - * scope. - * @param {Scope} globalScope The global scope. - * @param {Object} configGlobals The globals declared in configuration - * @param {{exportedVariables: Object, enabledGlobals: Object}} commentDirectives Directives from comment configuration - * @returns {void} - */ -function addDeclaredGlobals(globalScope, configGlobals, commentDirectives) { - const mergedGlobalsInfo = Object.assign( - {}, - lodash.mapValues(configGlobals, value => ({ sourceComment: null, value: ConfigOps.normalizeConfigGlobal(value) })), - lodash.mapValues(commentDirectives.enabledGlobals, ({ comment, value }) => ({ sourceComment: comment, value: ConfigOps.normalizeConfigGlobal(value) })) - ); - - Object.keys(mergedGlobalsInfo) - .filter(name => mergedGlobalsInfo[name].value !== "off") - .forEach(name => { - let variable = globalScope.set.get(name); - - if (!variable) { - variable = new eslintScope.Variable(name, globalScope); - if (mergedGlobalsInfo[name].sourceComment === null) { - variable.eslintExplicitGlobal = false; - } else { - variable.eslintExplicitGlobal = true; - variable.eslintExplicitGlobalComment = mergedGlobalsInfo[name].sourceComment; - } - globalScope.variables.push(variable); - globalScope.set.set(name, variable); - } - variable.writeable = (mergedGlobalsInfo[name].value === "writeable"); - }); - - // mark all exported variables as such - Object.keys(commentDirectives.exportedVariables).forEach(name => { - const variable = globalScope.set.get(name); - - if (variable) { - variable.eslintUsed = true; - } - }); - - /* - * "through" contains all references which definitions cannot be found. - * 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(reference => { - const name = reference.identifier.name; - const variable = globalScope.set.get(name); - - if (variable) { - - /* - * Links the variable and the reference. - * And this reference is removed from `Scope#through`. - */ - reference.resolved = variable; - variable.references.push(reference); - - return false; - } - - return true; - }); -} - -/** - * Creates a collection of disable directives from a comment - * @param {("disable"|"enable"|"disable-line"|"disable-next-line")} type The type of directive comment - * @param {{line: number, column: number}} loc The 0-based location of the comment token - * @param {string} value The value after the directive in the comment - * comment specified no specific rules, so it applies to all rules (e.g. `eslint-disable`) - * @returns {DisableDirective[]} Directives from the comment - */ -function createDisableDirectives(type, loc, value) { - const ruleIds = Object.keys(commentParser.parseListConfig(value)); - const directiveRules = ruleIds.length ? ruleIds : [null]; - - return directiveRules.map(ruleId => ({ type, line: loc.line, column: loc.column + 1, ruleId })); -} - -/** - * Parses comments in file to extract file-specific config of rules, globals - * and environments and merges them with global config; also code blocks - * where reporting is disabled or enabled and merges them with reporting config. - * @param {string} filename The file being checked. - * @param {ASTNode} ast The top node of the AST. - * @param {function(string): {create: Function}} ruleMapper A map from rule IDs to defined rules - * @returns {{configuredRules: Object, enabledGlobals: Object, exportedVariables: Object, problems: Problem[], disableDirectives: DisableDirective[]}} - * A collection of the directive comments that were found, along with any problems that occurred when parsing - */ -function getDirectiveComments(filename, ast, ruleMapper) { - const configuredRules = {}; - const enabledGlobals = {}; - const exportedVariables = {}; - const problems = []; - const disableDirectives = []; - - ast.comments.filter(token => token.type !== "Shebang").forEach(comment => { - const trimmedCommentText = comment.value.trim(); - const match = /^(eslint(-\w+){0,3}|exported|globals?)(\s|$)/.exec(trimmedCommentText); - - if (!match) { - return; - } - - const directiveValue = trimmedCommentText.slice(match.index + match[1].length); - - if (/^eslint-disable-(next-)?line$/.test(match[1])) { - if (comment.loc.start.line === comment.loc.end.line) { - const directiveType = match[1].slice("eslint-".length); - - disableDirectives.push(...createDisableDirectives(directiveType, comment.loc.start, directiveValue)); - } else { - problems.push({ - ruleId: null, - severity: 2, - message: `${match[1]} comment should not span multiple lines.`, - line: comment.loc.start.line, - column: comment.loc.start.column + 1, - endLine: comment.loc.end.line, - endColumn: comment.loc.end.column + 1, - nodeType: null - }); - } - } else if (comment.type === "Block") { - switch (match[1]) { - case "exported": - Object.assign(exportedVariables, commentParser.parseStringConfig(directiveValue, comment)); - break; - - case "globals": - case "global": - Object.assign(enabledGlobals, commentParser.parseStringConfig(directiveValue, comment)); - break; - - case "eslint-disable": - disableDirectives.push(...createDisableDirectives("disable", comment.loc.start, directiveValue)); - break; - - case "eslint-enable": - disableDirectives.push(...createDisableDirectives("enable", comment.loc.start, directiveValue)); - break; - - case "eslint": { - const parseResult = commentParser.parseJsonConfig(directiveValue, comment.loc); - - if (parseResult.success) { - Object.keys(parseResult.config).forEach(name => { - const ruleValue = parseResult.config[name]; - - try { - validator.validateRuleOptions(ruleMapper(name), name, ruleValue); - } catch (err) { - problems.push({ - ruleId: name, - severity: 2, - message: err.message, - line: comment.loc.start.line, - column: comment.loc.start.column + 1, - endLine: comment.loc.end.line, - endColumn: comment.loc.end.column + 1, - nodeType: null - }); - } - configuredRules[name] = ruleValue; - }); - } else { - problems.push(parseResult.error); - } - - break; - } - - // no default - } - } - }); - - return { - configuredRules, - enabledGlobals, - exportedVariables, - problems, - disableDirectives - }; -} - -/** - * Normalize ECMAScript version from the initial config - * @param {number} ecmaVersion ECMAScript version from the initial config - * @param {boolean} isModule Whether the source type is module or not - * @returns {number} normalized ECMAScript version - */ -function normalizeEcmaVersion(ecmaVersion, isModule) { - - // Need at least ES6 for modules - if (isModule && (!ecmaVersion || ecmaVersion < 6)) { - return 6; - } - - /* - * Calculate ECMAScript edition number from official year version starting with - * ES2015, which corresponds with ES6 (or a difference of 2009). - */ - if (ecmaVersion >= 2015) { - return ecmaVersion - 2009; - } - - return ecmaVersion; -} - -const eslintEnvPattern = /\/\*\s*eslint-env\s(.+?)\*\//g; - -/** - * Checks whether or not there is a comment which has "eslint-env *" in a given text. - * @param {string} text - A source code text to check. - * @returns {Object|null} A result of parseListConfig() with "eslint-env *" comment. - */ -function findEslintEnv(text) { - let match, retv; - - eslintEnvPattern.lastIndex = 0; - - while ((match = eslintEnvPattern.exec(text))) { - retv = Object.assign(retv || {}, commentParser.parseListConfig(match[1])); - } - - return retv; -} - -/** - * Normalizes the possible options for `linter.verify` and `linter.verifyAndFix` to a - * consistent shape. - * @param {(string|{reportUnusedDisableDirectives: boolean, filename: string, allowInlineConfig: boolean})} providedOptions Options - * @returns {{reportUnusedDisableDirectives: boolean, filename: string, allowInlineConfig: boolean}} Normalized options - */ -function normalizeVerifyOptions(providedOptions) { - const isObjectOptions = typeof providedOptions === "object"; - const providedFilename = isObjectOptions ? providedOptions.filename : providedOptions; - - return { - filename: typeof providedFilename === "string" ? providedFilename : "", - allowInlineConfig: !isObjectOptions || providedOptions.allowInlineConfig !== false, - reportUnusedDisableDirectives: isObjectOptions && !!providedOptions.reportUnusedDisableDirectives - }; -} - -/** - * Combines the provided parserOptions with the options from environments - * @param {string} parserName The parser name which uses this options. - * @param {Object} providedOptions The provided 'parserOptions' key in a config - * @param {Environment[]} enabledEnvironments The environments enabled in configuration and with inline comments - * @returns {Object} Resulting parser options after merge - */ -function resolveParserOptions(parserName, providedOptions, enabledEnvironments) { - const parserOptionsFromEnv = enabledEnvironments - .filter(env => env.parserOptions) - .reduce((parserOptions, env) => ConfigOps.merge(parserOptions, env.parserOptions), {}); - - const mergedParserOptions = ConfigOps.merge(parserOptionsFromEnv, providedOptions || {}); - - const isModule = mergedParserOptions.sourceType === "module"; - - if (isModule) { - - // can't have global return inside of modules - mergedParserOptions.ecmaFeatures = Object.assign({}, mergedParserOptions.ecmaFeatures, { globalReturn: false }); - } - - mergedParserOptions.ecmaVersion = normalizeEcmaVersion(mergedParserOptions.ecmaVersion, isModule); - - // TODO: For backward compatibility. Will remove on v6.0.0. - if ( - parserName === DEFAULT_PARSER_NAME && - mergedParserOptions.ecmaFeatures && - mergedParserOptions.ecmaFeatures.experimentalObjectRestSpread && - (!mergedParserOptions.ecmaVersion || mergedParserOptions.ecmaVersion < 9) - ) { - mergedParserOptions.ecmaVersion = 9; - } - - return mergedParserOptions; -} - -/** - * Combines the provided globals object with the globals from environments - * @param {Object} providedGlobals The 'globals' key in a config - * @param {Environments[]} enabledEnvironments The environments enabled in configuration and with inline comments - * @returns {Object} The resolved globals object - */ -function resolveGlobals(providedGlobals, enabledEnvironments) { - return Object.assign( - {}, - ...enabledEnvironments.filter(env => env.globals).map(env => env.globals), - providedGlobals - ); -} - -/** - * Strips Unicode BOM from a given text. - * - * @param {string} text - A text to strip. - * @returns {string} The stripped text. - */ -function stripUnicodeBOM(text) { - - /* - * Check Unicode BOM. - * In JavaScript, string data is stored as UTF-16, so BOM is 0xFEFF. - * http://www.ecma-international.org/ecma-262/6.0/#sec-unicode-format-control-characters - */ - if (text.charCodeAt(0) === 0xFEFF) { - return text.slice(1); - } - return text; -} - -/** - * Get the options for a rule (not including severity), if any - * @param {Array|number} ruleConfig rule configuration - * @returns {Array} of rule options, empty Array if none - */ -function getRuleOptions(ruleConfig) { - if (Array.isArray(ruleConfig)) { - return ruleConfig.slice(1); - } - return []; - -} - -/** - * Analyze scope of the given AST. - * @param {ASTNode} ast The `Program` node to analyze. - * @param {Object} parserOptions The parser options. - * @param {Object} visitorKeys The visitor keys. - * @returns {ScopeManager} The analysis result. - */ -function analyzeScope(ast, parserOptions, visitorKeys) { - const ecmaFeatures = parserOptions.ecmaFeatures || {}; - const ecmaVersion = parserOptions.ecmaVersion || 5; - - return eslintScope.analyze(ast, { - ignoreEval: true, - nodejsScope: ecmaFeatures.globalReturn, - impliedStrict: ecmaFeatures.impliedStrict, - ecmaVersion, - sourceType: parserOptions.sourceType || "script", - childVisitorKeys: visitorKeys || evk.KEYS, - fallback: Traverser.getKeys - }); -} - -/** - * Parses text into an AST. Moved out here because the try-catch prevents - * optimization of functions, so it's best to keep the try-catch as isolated - * as possible - * @param {string} text The text to parse. - * @param {Object} providedParserOptions Options to pass to the parser - * @param {string} parserName The name of the parser - * @param {Map} parserMap A map from names to loaded parsers - * @param {string} filePath The path to the file being parsed. - * @returns {{success: false, error: Problem}|{success: true, sourceCode: SourceCode}} - * An object containing the AST and parser services if parsing was successful, or the error if parsing failed - * @private - */ -function parse(text, providedParserOptions, parserName, parserMap, filePath) { - - - const textToParse = stripUnicodeBOM(text).replace(astUtils.SHEBANG_MATCHER, (match, captured) => `//${captured}`); - const parserOptions = Object.assign({}, providedParserOptions, { - loc: true, - range: true, - raw: true, - tokens: true, - comment: true, - eslintVisitorKeys: true, - eslintScopeManager: true, - filePath - }); - - let parser; - - try { - parser = parserMap.get(parserName) || require(parserName); - } catch (ex) { - return { - success: false, - error: { - ruleId: null, - fatal: true, - severity: 2, - message: ex.message, - line: 0, - column: 0 - } - }; - } - - /* - * Check for parsing errors first. If there's a parsing error, nothing - * else can happen. However, a parsing error does not throw an error - * from this method - it's just considered a fatal error message, a - * problem that ESLint identified just like any other. - */ - try { - const parseResult = (typeof parser.parseForESLint === "function") - ? parser.parseForESLint(textToParse, parserOptions) - : { ast: parser.parse(textToParse, parserOptions) }; - const ast = parseResult.ast; - const parserServices = parseResult.services || {}; - const visitorKeys = parseResult.visitorKeys || evk.KEYS; - const scopeManager = parseResult.scopeManager || analyzeScope(ast, parserOptions, visitorKeys); - - return { - success: true, - - /* - * Save all values that `parseForESLint()` returned. - * If a `SourceCode` object is given as the first parameter instead of source code text, - * linter skips the parsing process and reuses the source code object. - * In that case, linter needs all the values that `parseForESLint()` returned. - */ - sourceCode: new SourceCode({ - text, - ast, - parserServices, - scopeManager, - visitorKeys - }) - }; - } catch (ex) { - - // If the message includes a leading line number, strip it: - const message = `Parsing error: ${ex.message.replace(/^line \d+:/i, "").trim()}`; - - return { - success: false, - error: { - ruleId: null, - fatal: true, - severity: 2, - message, - line: ex.lineNumber, - column: ex.column - } - }; - } -} - -/** - * Gets the scope for the current node - * @param {ScopeManager} scopeManager The scope manager for this AST - * @param {ASTNode} currentNode The node to get the scope of - * @returns {eslint-scope.Scope} The scope information for this node - */ -function getScope(scopeManager, currentNode) { - - // On Program node, get the outermost scope to avoid return Node.js special function scope or ES modules scope. - const inner = currentNode.type !== "Program"; - - for (let node = currentNode; node; node = node.parent) { - const scope = scopeManager.acquire(node, inner); - - if (scope) { - if (scope.type === "function-expression-name") { - return scope.childScopes[0]; - } - return scope; - } - } - - return scopeManager.scopes[0]; -} - -/** - * Marks a variable as used in the current scope - * @param {ScopeManager} scopeManager The scope manager for this AST. The scope may be mutated by this function. - * @param {ASTNode} currentNode The node currently being traversed - * @param {Object} parserOptions The options used to parse this text - * @param {string} name The name of the variable that should be marked as used. - * @returns {boolean} True if the variable was found and marked as used, false if not. - */ -function markVariableAsUsed(scopeManager, currentNode, parserOptions, name) { - const hasGlobalReturn = parserOptions.ecmaFeatures && parserOptions.ecmaFeatures.globalReturn; - const specialScope = hasGlobalReturn || parserOptions.sourceType === "module"; - const currentScope = getScope(scopeManager, currentNode); - - // Special Node.js scope means we need to start one level deeper - const initialScope = currentScope.type === "global" && specialScope ? currentScope.childScopes[0] : currentScope; - - for (let scope = initialScope; scope; scope = scope.upper) { - const variable = scope.variables.find(scopeVar => scopeVar.name === name); - - if (variable) { - variable.eslintUsed = true; - return true; - } - } - - return false; -} - -/** - * Runs a rule, and gets its listeners - * @param {Rule} rule A normalized rule with a `create` method - * @param {Context} ruleContext The context that should be passed to the rule - * @returns {Object} A map of selector listeners provided by the rule - */ -function createRuleListeners(rule, ruleContext) { - try { - return rule.create(ruleContext); - } catch (ex) { - ex.message = `Error while loading rule '${ruleContext.id}': ${ex.message}`; - throw ex; - } -} - -/** - * Gets all the ancestors of a given node - * @param {ASTNode} node The node - * @returns {ASTNode[]} All the ancestor nodes in the AST, not including the provided node, starting - * from the root node and going inwards to the parent node. - */ -function getAncestors(node) { - const ancestorsStartingAtParent = []; - - for (let ancestor = node.parent; ancestor; ancestor = ancestor.parent) { - ancestorsStartingAtParent.push(ancestor); - } - - return ancestorsStartingAtParent.reverse(); -} - -// methods that exist on SourceCode object -const DEPRECATED_SOURCECODE_PASSTHROUGHS = { - getSource: "getText", - getSourceLines: "getLines", - getAllComments: "getAllComments", - getNodeByRangeIndex: "getNodeByRangeIndex", - getComments: "getComments", - getCommentsBefore: "getCommentsBefore", - getCommentsAfter: "getCommentsAfter", - getCommentsInside: "getCommentsInside", - getJSDocComment: "getJSDocComment", - getFirstToken: "getFirstToken", - getFirstTokens: "getFirstTokens", - getLastToken: "getLastToken", - getLastTokens: "getLastTokens", - getTokenAfter: "getTokenAfter", - getTokenBefore: "getTokenBefore", - getTokenByRangeStart: "getTokenByRangeStart", - getTokens: "getTokens", - getTokensAfter: "getTokensAfter", - getTokensBefore: "getTokensBefore", - getTokensBetween: "getTokensBetween" -}; - -const BASE_TRAVERSAL_CONTEXT = Object.freeze( - Object.keys(DEPRECATED_SOURCECODE_PASSTHROUGHS).reduce( - (contextInfo, methodName) => - Object.assign(contextInfo, { - [methodName](...args) { - return this.getSourceCode()[DEPRECATED_SOURCECODE_PASSTHROUGHS[methodName]](...args); - } - }), - {} - ) -); - -/** - * Runs the given rules on the given SourceCode object - * @param {SourceCode} sourceCode A SourceCode object for the given text - * @param {Object} configuredRules The rules configuration - * @param {function(string): Rule} ruleMapper A mapper function from rule names to rules - * @param {Object} parserOptions The options that were passed to the parser - * @param {string} parserName The name of the parser in the config - * @param {Object} settings The settings that were enabled in the config - * @param {string} filename The reported filename of the code - * @returns {Problem[]} An array of reported problems - */ -function runRules(sourceCode, configuredRules, ruleMapper, parserOptions, parserName, settings, filename) { - const emitter = createEmitter(); - const nodeQueue = []; - let currentNode = sourceCode.ast; - - Traverser.traverse(sourceCode.ast, { - enter(node, parent) { - node.parent = parent; - nodeQueue.push({ isEntering: true, node }); - }, - leave(node) { - nodeQueue.push({ isEntering: false, node }); - }, - visitorKeys: sourceCode.visitorKeys - }); - - /* - * Create a frozen object with the ruleContext properties and methods that are shared by all rules. - * All rule contexts will inherit from this object. This avoids the performance penalty of copying all the - * properties once for each rule. - */ - const sharedTraversalContext = Object.freeze( - Object.assign( - Object.create(BASE_TRAVERSAL_CONTEXT), - { - getAncestors: () => getAncestors(currentNode), - getDeclaredVariables: sourceCode.scopeManager.getDeclaredVariables.bind(sourceCode.scopeManager), - getFilename: () => filename, - getScope: () => getScope(sourceCode.scopeManager, currentNode), - getSourceCode: () => sourceCode, - markVariableAsUsed: name => markVariableAsUsed(sourceCode.scopeManager, currentNode, parserOptions, name), - parserOptions, - parserPath: parserName, - parserServices: sourceCode.parserServices, - settings - } - ) - ); - - - const lintingProblems = []; - - Object.keys(configuredRules).forEach(ruleId => { - const severity = ConfigOps.getRuleSeverity(configuredRules[ruleId]); - - if (severity === 0) { - return; - } - - const rule = ruleMapper(ruleId); - const messageIds = rule.meta && rule.meta.messages; - let reportTranslator = null; - const ruleContext = Object.freeze( - Object.assign( - Object.create(sharedTraversalContext), - { - id: ruleId, - options: getRuleOptions(configuredRules[ruleId]), - report(...args) { - - /* - * Create a report translator lazily. - * In a vast majority of cases, any given rule reports zero errors on a given - * piece of code. Creating a translator lazily avoids the performance cost of - * creating a new translator function for each rule that usually doesn't get - * called. - * - * Using lazy report translators improves end-to-end performance by about 3% - * with Node 8.4.0. - */ - if (reportTranslator === null) { - reportTranslator = createReportTranslator({ ruleId, severity, sourceCode, messageIds }); - } - const problem = reportTranslator(...args); - - if (problem.fix && rule.meta && !rule.meta.fixable) { - throw new Error("Fixable rules should export a `meta.fixable` property."); - } - lintingProblems.push(problem); - } - } - ) - ); - - const ruleListeners = createRuleListeners(rule, ruleContext); - - // add all the selectors from the rule as listeners - Object.keys(ruleListeners).forEach(selector => { - emitter.on( - selector, - timing.enabled - ? timing.time(ruleId, ruleListeners[selector]) - : ruleListeners[selector] - ); - }); - }); - - const eventGenerator = new CodePathAnalyzer(new NodeEventGenerator(emitter)); - - nodeQueue.forEach(traversalInfo => { - currentNode = traversalInfo.node; - - if (traversalInfo.isEntering) { - eventGenerator.enterNode(currentNode); - } else { - eventGenerator.leaveNode(currentNode); - } - }); - - return lintingProblems; -} - -const lastSourceCodes = new WeakMap(); -const loadedParserMaps = new WeakMap(); -const ruleMaps = new WeakMap(); - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -/** - * Object that is responsible for verifying JavaScript text - * @name eslint - */ -module.exports = class Linter { - - constructor() { - lastSourceCodes.set(this, null); - loadedParserMaps.set(this, new Map()); - ruleMaps.set(this, new Rules()); - this.version = pkg.version; - this.environments = new Environments(); - } - - /** - * Getter for package version. - * @static - * @returns {string} The version from package.json. - */ - static get version() { - return pkg.version; - } - - /** - * Configuration object for the `verify` API. A JS representation of the eslintrc files. - * @typedef {Object} ESLintConfig - * @property {Object} rules The rule configuration to verify against. - * @property {string} [parser] Parser to use when generatig the AST. - * @property {Object} [parserOptions] Options for the parsed used. - * @property {Object} [settings] Global settings passed to each rule. - * @property {Object} [env] The environment to verify in. - * @property {Object} [globals] Available globals to the code. - */ - - /** - * Same as linter.verify, except without support for processors. - * @param {string|SourceCode} textOrSourceCode The text to parse or a SourceCode object. - * @param {ESLintConfig} providedConfig An ESLintConfig instance to configure everything. - * @param {(string|Object)} [filenameOrOptions] The optional filename of the file being checked. - * If this is not set, the filename will default to '' in the rule context. If - * an object, then it has "filename", "saveState", and "allowInlineConfig" properties. - * @param {boolean} [filenameOrOptions.allowInlineConfig=true] Allow/disallow inline comments' ability to change config once it is set. Defaults to true if not supplied. - * Useful if you want to validate JS without comments overriding rules. - * @param {boolean} [filenameOrOptions.reportUnusedDisableDirectives=false] Adds reported errors for unused - * eslint-disable directives - * @returns {Object[]} The results as an array of messages or an empty array if no messages. - */ - _verifyWithoutProcessors(textOrSourceCode, providedConfig, filenameOrOptions) { - const config = providedConfig || {}; - const options = normalizeVerifyOptions(filenameOrOptions); - let text; - - // evaluate arguments - if (typeof textOrSourceCode === "string") { - lastSourceCodes.set(this, null); - text = textOrSourceCode; - } else { - lastSourceCodes.set(this, textOrSourceCode); - text = textOrSourceCode.text; - } - - // search and apply "eslint-env *". - const envInFile = findEslintEnv(text); - const resolvedEnvConfig = Object.assign({ builtin: true }, config.env, envInFile); - const enabledEnvs = Object.keys(resolvedEnvConfig) - .filter(envName => resolvedEnvConfig[envName]) - .map(envName => this.environments.get(envName)) - .filter(env => env); - - const parserName = config.parser || DEFAULT_PARSER_NAME; - const parserOptions = resolveParserOptions(parserName, config.parserOptions || {}, enabledEnvs); - const configuredGlobals = resolveGlobals(config.globals || {}, enabledEnvs); - const settings = config.settings || {}; - - if (!lastSourceCodes.get(this)) { - const parseResult = parse( - text, - parserOptions, - parserName, - loadedParserMaps.get(this), - options.filename - ); - - if (!parseResult.success) { - return [parseResult.error]; - } - - lastSourceCodes.set(this, parseResult.sourceCode); - } else { - - /* - * If the given source code object as the first argument does not have scopeManager, analyze the scope. - * This is for backward compatibility (SourceCode is frozen so it cannot rebind). - */ - const lastSourceCode = lastSourceCodes.get(this); - - if (!lastSourceCode.scopeManager) { - lastSourceCodes.set(this, new SourceCode({ - text: lastSourceCode.text, - ast: lastSourceCode.ast, - parserServices: lastSourceCode.parserServices, - visitorKeys: lastSourceCode.visitorKeys, - scopeManager: analyzeScope(lastSourceCode.ast, parserOptions) - })); - } - } - - const sourceCode = lastSourceCodes.get(this); - const commentDirectives = options.allowInlineConfig - ? getDirectiveComments(options.filename, sourceCode.ast, ruleId => ruleMaps.get(this).get(ruleId)) - : { configuredRules: {}, enabledGlobals: {}, exportedVariables: {}, problems: [], disableDirectives: [] }; - - // augment global scope with declared global variables - addDeclaredGlobals( - sourceCode.scopeManager.scopes[0], - configuredGlobals, - { exportedVariables: commentDirectives.exportedVariables, enabledGlobals: commentDirectives.enabledGlobals } - ); - - const configuredRules = Object.assign({}, config.rules, commentDirectives.configuredRules); - - let lintingProblems; - - try { - lintingProblems = runRules( - sourceCode, - configuredRules, - ruleId => ruleMaps.get(this).get(ruleId), - parserOptions, - parserName, - settings, - options.filename - ); - } catch (err) { - debug("An error occurred while traversing"); - debug("Filename:", options.filename); - debug("Parser Options:", parserOptions); - debug("Parser Path:", parserName); - debug("Settings:", settings); - throw err; - } - - return applyDisableDirectives({ - directives: commentDirectives.disableDirectives, - problems: lintingProblems - .concat(commentDirectives.problems) - .sort((problemA, problemB) => problemA.line - problemB.line || problemA.column - problemB.column), - reportUnusedDisableDirectives: options.reportUnusedDisableDirectives - }); - } - - /** - * Verifies the text against the rules specified by the second argument. - * @param {string|SourceCode} textOrSourceCode The text to parse or a SourceCode object. - * @param {ESLintConfig} config An ESLintConfig instance to configure everything. - * @param {(string|Object)} [filenameOrOptions] The optional filename of the file being checked. - * If this is not set, the filename will default to '' in the rule context. If - * an object, then it has "filename", "saveState", and "allowInlineConfig" properties. - * @param {boolean} [filenameOrOptions.allowInlineConfig] Allow/disallow inline comments' ability to change config once it is set. Defaults to true if not supplied. - * Useful if you want to validate JS without comments overriding rules. - * @param {function(string): string[]} [filenameOrOptions.preprocess] preprocessor for source text. If provided, - * this should accept a string of source text, and return an array of code blocks to lint. - * @param {function(Array): Object[]} [filenameOrOptions.postprocess] postprocessor for report messages. If provided, - * this should accept an array of the message lists for each code block returned from the preprocessor, - * apply a mapping to the messages as appropriate, and return a one-dimensional array of messages - * @returns {Object[]} The results as an array of messages or an empty array if no messages. - */ - verify(textOrSourceCode, config, filenameOrOptions) { - const preprocess = filenameOrOptions && filenameOrOptions.preprocess || (rawText => [rawText]); - const postprocess = filenameOrOptions && filenameOrOptions.postprocess || lodash.flatten; - - return postprocess( - preprocess(textOrSourceCode).map( - textBlock => this._verifyWithoutProcessors(textBlock, config, filenameOrOptions) - ) - ); - } - - /** - * Gets the SourceCode object representing the parsed source. - * @returns {SourceCode} The SourceCode object. - */ - getSourceCode() { - return lastSourceCodes.get(this); - } - - /** - * Defines a new linting rule. - * @param {string} ruleId A unique rule identifier - * @param {Function} ruleModule Function from context to object mapping AST node types to event handlers - * @returns {void} - */ - defineRule(ruleId, ruleModule) { - ruleMaps.get(this).define(ruleId, ruleModule); - } - - /** - * Defines many new linting rules. - * @param {Object} rulesToDefine map from unique rule identifier to rule - * @returns {void} - */ - defineRules(rulesToDefine) { - Object.getOwnPropertyNames(rulesToDefine).forEach(ruleId => { - this.defineRule(ruleId, rulesToDefine[ruleId]); - }); - } - - /** - * Gets an object with all loaded rules. - * @returns {Map} All loaded rules - */ - getRules() { - return ruleMaps.get(this).getAllLoadedRules(); - } - - /** - * Define a new parser module - * @param {any} parserId Name of the parser - * @param {any} parserModule The parser object - * @returns {void} - */ - defineParser(parserId, parserModule) { - loadedParserMaps.get(this).set(parserId, parserModule); - } - - /** - * Performs multiple autofix passes over the text until as many fixes as possible - * have been applied. - * @param {string} text The source text to apply fixes to. - * @param {Object} config The ESLint config object to use. - * @param {Object} options The ESLint options object to use. - * @param {string} options.filename The filename from which the text was read. - * @param {boolean} options.allowInlineConfig Flag indicating if inline comments - * should be allowed. - * @param {boolean|Function} options.fix Determines whether fixes should be applied - * @param {Function} options.preprocess preprocessor for source text. If provided, this should - * accept a string of source text, and return an array of code blocks to lint. - * @param {Function} options.postprocess postprocessor for report messages. If provided, - * this should accept an array of the message lists for each code block returned from the preprocessor, - * apply a mapping to the messages as appropriate, and return a one-dimensional array of messages - * @returns {Object} The result of the fix operation as returned from the - * SourceCodeFixer. - */ - verifyAndFix(text, config, options) { - let messages = [], - fixedResult, - fixed = false, - passNumber = 0, - currentText = text; - const debugTextDescription = options && options.filename || `${text.slice(0, 10)}...`; - const shouldFix = options && typeof options.fix !== "undefined" ? options.fix : true; - - /** - * This loop continues until one of the following is true: - * - * 1. No more fixes have been applied. - * 2. Ten passes have been made. - * - * That means anytime a fix is successfully applied, there will be another pass. - * Essentially, guaranteeing a minimum of two passes. - */ - do { - passNumber++; - - debug(`Linting code for ${debugTextDescription} (pass ${passNumber})`); - messages = this.verify(currentText, config, options); - - debug(`Generating fixed text for ${debugTextDescription} (pass ${passNumber})`); - fixedResult = SourceCodeFixer.applyFixes(currentText, messages, shouldFix); - - /* - * stop if there are any syntax errors. - * 'fixedResult.output' is a empty string. - */ - if (messages.length === 1 && messages[0].fatal) { - break; - } - - // keep track if any fixes were ever applied - important for return value - fixed = fixed || fixedResult.fixed; - - // update to use the fixed output instead of the original text - currentText = fixedResult.output; - - } while ( - fixedResult.fixed && - passNumber < MAX_AUTOFIX_PASSES - ); - - /* - * If the last result had fixes, we need to lint again to be sure we have - * the most up-to-date information. - */ - if (fixedResult.fixed) { - fixedResult.messages = this.verify(currentText, config, options); - } - - // ensure the last result properly reflects if fixes were done - fixedResult.fixed = fixed; - fixedResult.output = currentText; - - return fixedResult; - } -}; diff --git a/tools/node_modules/eslint/lib/load-rules.js b/tools/node_modules/eslint/lib/load-rules.js deleted file mode 100644 index a7383624651c33..00000000000000 --- a/tools/node_modules/eslint/lib/load-rules.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * @fileoverview Module for loading rules from files and directories. - * @author Michael Ficarra - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const fs = require("fs"), - path = require("path"); - -const rulesDirCache = {}; - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -/** - * Load all rule modules from specified directory. - * @param {string} relativeRulesDir Path to rules directory, may be relative. - * @param {string} cwd Current working directory - * @returns {Object} Loaded rule modules by rule ids (file names). - */ -module.exports = function(relativeRulesDir, cwd) { - const rulesDir = path.resolve(cwd, relativeRulesDir); - - // cache will help performance as IO operation are expensive - if (rulesDirCache[rulesDir]) { - return rulesDirCache[rulesDir]; - } - - const rules = Object.create(null); - - fs.readdirSync(rulesDir).forEach(file => { - if (path.extname(file) !== ".js") { - return; - } - rules[file.slice(0, -3)] = path.join(rulesDir, file); - }); - rulesDirCache[rulesDir] = rules; - - return rules; -}; diff --git a/tools/node_modules/eslint/lib/options.js b/tools/node_modules/eslint/lib/options.js deleted file mode 100644 index ee7357a296aa05..00000000000000 --- a/tools/node_modules/eslint/lib/options.js +++ /dev/null @@ -1,246 +0,0 @@ -/** - * @fileoverview Options configuration for optionator. - * @author George Zahariev - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const optionator = require("optionator"); - -//------------------------------------------------------------------------------ -// Initialization and Public Interface -//------------------------------------------------------------------------------ - -// exports "parse(args)", "generateHelp()", and "generateHelpForOption(optionName)" -module.exports = optionator({ - prepend: "eslint [options] file.js [file.js] [dir]", - defaults: { - concatRepeatedArrays: true, - mergeRepeatedObjects: true - }, - options: [ - { - heading: "Basic configuration" - }, - { - option: "eslintrc", - type: "Boolean", - default: "true", - description: "Disable use of configuration from .eslintrc.*" - }, - { - option: "config", - alias: "c", - type: "path::String", - description: "Use this configuration, overriding .eslintrc.* config options if present" - }, - { - option: "env", - type: "[String]", - description: "Specify environments" - }, - { - option: "ext", - type: "[String]", - default: ".js", - description: "Specify JavaScript file extensions" - }, - { - option: "global", - type: "[String]", - description: "Define global variables" - }, - { - option: "parser", - type: "String", - description: "Specify the parser to be used" - }, - { - option: "parser-options", - type: "Object", - description: "Specify parser options" - }, - { - heading: "Specifying rules and plugins" - }, - { - option: "rulesdir", - type: "[path::String]", - description: "Use additional rules from this directory" - }, - { - option: "plugin", - type: "[String]", - description: "Specify plugins" - }, - { - option: "rule", - type: "Object", - description: "Specify rules" - }, - { - heading: "Fixing problems" - }, - { - option: "fix", - type: "Boolean", - default: false, - description: "Automatically fix problems" - }, - { - option: "fix-dry-run", - type: "Boolean", - default: false, - description: "Automatically fix problems without saving the changes to the file system" - }, - { - option: "fix-type", - type: "Array", - description: "Specify the types of fixes to apply (problem, suggestion, layout)" - }, - { - heading: "Ignoring files" - }, - { - option: "ignore-path", - type: "path::String", - description: "Specify path of ignore file" - }, - { - option: "ignore", - type: "Boolean", - default: "true", - description: "Disable use of ignore files and patterns" - }, - { - option: "ignore-pattern", - type: "[String]", - description: "Pattern of files to ignore (in addition to those in .eslintignore)", - concatRepeatedArrays: [true, { - oneValuePerFlag: true - }] - }, - { - heading: "Using stdin" - }, - { - option: "stdin", - type: "Boolean", - default: "false", - description: "Lint code provided on " - }, - { - option: "stdin-filename", - type: "String", - description: "Specify filename to process STDIN as" - }, - { - heading: "Handling warnings" - }, - { - option: "quiet", - type: "Boolean", - default: "false", - description: "Report errors only" - }, - { - option: "max-warnings", - type: "Int", - default: "-1", - description: "Number of warnings to trigger nonzero exit code" - }, - { - heading: "Output" - }, - { - option: "output-file", - alias: "o", - type: "path::String", - description: "Specify file to write report to" - }, - { - option: "format", - alias: "f", - type: "String", - default: "stylish", - description: "Use a specific output format" - }, - { - option: "color", - type: "Boolean", - alias: "no-color", - description: "Force enabling/disabling of color" - }, - { - heading: "Inline configuration comments" - }, - { - option: "inline-config", - type: "Boolean", - default: "true", - description: "Prevent comments from changing config or rules" - }, - { - option: "report-unused-disable-directives", - type: "Boolean", - default: false, - description: "Adds reported errors for unused eslint-disable directives" - }, - { - heading: "Caching" - }, - { - option: "cache", - type: "Boolean", - default: "false", - description: "Only check changed files" - }, - { - option: "cache-file", - type: "path::String", - default: ".eslintcache", - description: "Path to the cache file. Deprecated: use --cache-location" - }, - { - option: "cache-location", - type: "path::String", - description: "Path to the cache file or directory" - }, - { - heading: "Miscellaneous" - }, - { - option: "init", - type: "Boolean", - default: "false", - description: "Run config initialization wizard" - }, - { - option: "debug", - type: "Boolean", - default: false, - description: "Output debugging information" - }, - { - option: "help", - alias: "h", - type: "Boolean", - description: "Show help" - }, - { - option: "version", - alias: "v", - type: "Boolean", - description: "Output the version number" - }, - { - option: "print-config", - type: "path::String", - description: "Print the configuration for the given file" - } - ] -}); diff --git a/tools/node_modules/eslint/lib/rules.js b/tools/node_modules/eslint/lib/rules.js deleted file mode 100644 index d0f909514164eb..00000000000000 --- a/tools/node_modules/eslint/lib/rules.js +++ /dev/null @@ -1,110 +0,0 @@ -/** - * @fileoverview Defines a storage for rules. - * @author Nicholas C. Zakas - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const lodash = require("lodash"); -const ruleReplacements = require("../conf/replacements").rules; -const builtInRules = require("./built-in-rules-index"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Creates a stub rule that gets used when a rule with a given ID is not found. - * @param {string} ruleId The ID of the missing rule - * @returns {{create: function(RuleContext): Object}} A rule that reports an error at the first location - * in the program. The report has the message `Definition for rule '${ruleId}' was not found` if the rule is unknown, - * or `Rule '${ruleId}' was removed and replaced by: ${replacements.join(", ")}` if the rule is known to have been - * replaced. - */ -const createMissingRule = lodash.memoize(ruleId => { - const message = Object.prototype.hasOwnProperty.call(ruleReplacements, ruleId) - ? `Rule '${ruleId}' was removed and replaced by: ${ruleReplacements[ruleId].join(", ")}` - : `Definition for rule '${ruleId}' was not found`; - - return { - create: context => ({ - Program() { - context.report({ - loc: { line: 1, column: 0 }, - message - }); - } - }) - }; -}); - -/** - * Normalizes a rule module to the new-style API - * @param {(Function|{create: Function})} rule A rule object, which can either be a function - * ("old-style") or an object with a `create` method ("new-style") - * @returns {{create: Function}} A new-style rule. - */ -function normalizeRule(rule) { - return typeof rule === "function" ? Object.assign({ create: rule }, rule) : rule; -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -class Rules { - constructor() { - this._rules = Object.create(null); - Object.keys(builtInRules).forEach(ruleId => { - this.define(ruleId, builtInRules[ruleId]); - }); - } - - /** - * Registers a rule module for rule id in storage. - * @param {string} ruleId Rule id (file name). - * @param {Function} ruleModule Rule handler. - * @returns {void} - */ - define(ruleId, ruleModule) { - this._rules[ruleId] = normalizeRule(ruleModule); - } - - /** - * Access rule handler by id (file name). - * @param {string} ruleId Rule id (file name). - * @returns {{create: Function, schema: JsonSchema[]}} - * A rule. This is normalized to always have the new-style shape with a `create` method. - */ - get(ruleId) { - if (!Object.prototype.hasOwnProperty.call(this._rules, ruleId)) { - return createMissingRule(ruleId); - } - if (typeof this._rules[ruleId] === "string") { - return normalizeRule(require(this._rules[ruleId])); - } - return this._rules[ruleId]; - - } - - /** - * Get an object with all currently loaded rules - * @returns {Map} All loaded rules - */ - getAllLoadedRules() { - const allRules = new Map(); - - Object.keys(this._rules).forEach(name => { - const rule = this.get(name); - - allRules.set(name, rule); - }); - return allRules; - } -} - -module.exports = Rules; diff --git a/tools/node_modules/eslint/lib/rules/accessor-pairs.js b/tools/node_modules/eslint/lib/rules/accessor-pairs.js deleted file mode 100644 index aca231848633ad..00000000000000 --- a/tools/node_modules/eslint/lib/rules/accessor-pairs.js +++ /dev/null @@ -1,167 +0,0 @@ -/** - * @fileoverview Rule to flag wrapping non-iife in parens - * @author Gyandeep Singh - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks whether or not a given node is an `Identifier` node which was named a given name. - * @param {ASTNode} node - A node to check. - * @param {string} name - An expected name of the node. - * @returns {boolean} `true` if the node is an `Identifier` node which was named as expected. - */ -function isIdentifier(node, name) { - return node.type === "Identifier" && node.name === name; -} - -/** - * Checks whether or not a given node is an argument of a specified method call. - * @param {ASTNode} node - A node to check. - * @param {number} index - An expected index of the node in arguments. - * @param {string} object - An expected name of the object of the method. - * @param {string} property - An expected name of the method. - * @returns {boolean} `true` if the node is an argument of the specified method call. - */ -function isArgumentOfMethodCall(node, index, object, property) { - const parent = node.parent; - - return ( - parent.type === "CallExpression" && - parent.callee.type === "MemberExpression" && - parent.callee.computed === false && - isIdentifier(parent.callee.object, object) && - isIdentifier(parent.callee.property, property) && - parent.arguments[index] === node - ); -} - -/** - * Checks whether or not a given node is a property descriptor. - * @param {ASTNode} node - A node to check. - * @returns {boolean} `true` if the node is a property descriptor. - */ -function isPropertyDescriptor(node) { - - // Object.defineProperty(obj, "foo", {set: ...}) - if (isArgumentOfMethodCall(node, 2, "Object", "defineProperty") || - isArgumentOfMethodCall(node, 2, "Reflect", "defineProperty") - ) { - return true; - } - - /* - * Object.defineProperties(obj, {foo: {set: ...}}) - * Object.create(proto, {foo: {set: ...}}) - */ - const grandparent = node.parent.parent; - - return grandparent.type === "ObjectExpression" && ( - isArgumentOfMethodCall(grandparent, 1, "Object", "create") || - isArgumentOfMethodCall(grandparent, 1, "Object", "defineProperties") - ); -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce getter and setter pairs in objects", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/accessor-pairs" - }, - - schema: [{ - type: "object", - properties: { - getWithoutSet: { - type: "boolean", - default: false - }, - setWithoutGet: { - type: "boolean", - default: true - } - }, - additionalProperties: false - }], - - messages: { - getter: "Getter is not present.", - setter: "Setter is not present." - } - }, - create(context) { - const config = context.options[0] || {}; - const checkGetWithoutSet = config.getWithoutSet === true; - const checkSetWithoutGet = config.setWithoutGet !== false; - - /** - * Checks a object expression to see if it has setter and getter both present or none. - * @param {ASTNode} node The node to check. - * @returns {void} - * @private - */ - function checkLonelySetGet(node) { - let isSetPresent = false; - let isGetPresent = false; - const isDescriptor = isPropertyDescriptor(node); - - for (let i = 0, end = node.properties.length; i < end; i++) { - const property = node.properties[i]; - - let propToCheck = ""; - - if (property.kind === "init") { - if (isDescriptor && !property.computed) { - propToCheck = property.key.name; - } - } else { - propToCheck = property.kind; - } - - switch (propToCheck) { - case "set": - isSetPresent = true; - break; - - case "get": - isGetPresent = true; - break; - - default: - - // Do nothing - } - - if (isSetPresent && isGetPresent) { - break; - } - } - - if (checkSetWithoutGet && isSetPresent && !isGetPresent) { - context.report({ node, messageId: "getter" }); - } else if (checkGetWithoutSet && isGetPresent && !isSetPresent) { - context.report({ node, messageId: "setter" }); - } - } - - return { - ObjectExpression(node) { - if (checkSetWithoutGet || checkGetWithoutSet) { - checkLonelySetGet(node); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/array-bracket-newline.js b/tools/node_modules/eslint/lib/rules/array-bracket-newline.js deleted file mode 100644 index b98fa9d27ca1b6..00000000000000 --- a/tools/node_modules/eslint/lib/rules/array-bracket-newline.js +++ /dev/null @@ -1,263 +0,0 @@ -/** - * @fileoverview Rule to enforce linebreaks after open and before close array brackets - * @author Jan Peer Stöcklmair - */ - -"use strict"; - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce linebreaks after opening and before closing array brackets", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/array-bracket-newline" - }, - - fixable: "whitespace", - - schema: [ - { - oneOf: [ - { - enum: ["always", "never", "consistent"] - }, - { - type: "object", - properties: { - multiline: { - type: "boolean", - default: true - }, - minItems: { - type: ["integer", "null"], - minimum: 0, - default: null - } - }, - additionalProperties: false - } - ] - } - ], - - messages: { - unexpectedOpeningLinebreak: "There should be no linebreak after '['.", - unexpectedClosingLinebreak: "There should be no linebreak before ']'.", - missingOpeningLinebreak: "A linebreak is required after '['.", - missingClosingLinebreak: "A linebreak is required before ']'." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - - //---------------------------------------------------------------------- - // Helpers - //---------------------------------------------------------------------- - - /** - * Normalizes a given option value. - * - * @param {string|Object|undefined} option - An option value to parse. - * @returns {{multiline: boolean, minItems: number}} Normalized option object. - */ - function normalizeOptionValue(option) { - let consistent = false; - let multiline = false; - let minItems = 0; - - if (option) { - if (option === "consistent") { - consistent = true; - minItems = Number.POSITIVE_INFINITY; - } else if (option === "always" || option.minItems === 0) { - minItems = 0; - } else if (option === "never") { - minItems = Number.POSITIVE_INFINITY; - } else { - multiline = Boolean(option.multiline); - minItems = option.minItems || Number.POSITIVE_INFINITY; - } - } else { - consistent = false; - multiline = true; - minItems = Number.POSITIVE_INFINITY; - } - - return { consistent, multiline, minItems }; - } - - /** - * Normalizes a given option value. - * - * @param {string|Object|undefined} options - An option value to parse. - * @returns {{ArrayExpression: {multiline: boolean, minItems: number}, ArrayPattern: {multiline: boolean, minItems: number}}} Normalized option object. - */ - function normalizeOptions(options) { - const value = normalizeOptionValue(options); - - return { ArrayExpression: value, ArrayPattern: value }; - } - - /** - * Reports that there shouldn't be a linebreak after the first token - * @param {ASTNode} node - The node to report in the event of an error. - * @param {Token} token - The token to use for the report. - * @returns {void} - */ - function reportNoBeginningLinebreak(node, token) { - context.report({ - node, - loc: token.loc, - messageId: "unexpectedOpeningLinebreak", - fix(fixer) { - const nextToken = sourceCode.getTokenAfter(token, { includeComments: true }); - - if (astUtils.isCommentToken(nextToken)) { - return null; - } - - return fixer.removeRange([token.range[1], nextToken.range[0]]); - } - }); - } - - /** - * Reports that there shouldn't be a linebreak before the last token - * @param {ASTNode} node - The node to report in the event of an error. - * @param {Token} token - The token to use for the report. - * @returns {void} - */ - function reportNoEndingLinebreak(node, token) { - context.report({ - node, - loc: token.loc, - messageId: "unexpectedClosingLinebreak", - fix(fixer) { - const previousToken = sourceCode.getTokenBefore(token, { includeComments: true }); - - if (astUtils.isCommentToken(previousToken)) { - return null; - } - - return fixer.removeRange([previousToken.range[1], token.range[0]]); - } - }); - } - - /** - * Reports that there should be a linebreak after the first token - * @param {ASTNode} node - The node to report in the event of an error. - * @param {Token} token - The token to use for the report. - * @returns {void} - */ - function reportRequiredBeginningLinebreak(node, token) { - context.report({ - node, - loc: token.loc, - messageId: "missingOpeningLinebreak", - fix(fixer) { - return fixer.insertTextAfter(token, "\n"); - } - }); - } - - /** - * Reports that there should be a linebreak before the last token - * @param {ASTNode} node - The node to report in the event of an error. - * @param {Token} token - The token to use for the report. - * @returns {void} - */ - function reportRequiredEndingLinebreak(node, token) { - context.report({ - node, - loc: token.loc, - messageId: "missingClosingLinebreak", - fix(fixer) { - return fixer.insertTextBefore(token, "\n"); - } - }); - } - - /** - * Reports a given node if it violated this rule. - * - * @param {ASTNode} node - A node to check. This is an ArrayExpression node or an ArrayPattern node. - * @returns {void} - */ - function check(node) { - const elements = node.elements; - const normalizedOptions = normalizeOptions(context.options[0]); - const options = normalizedOptions[node.type]; - const openBracket = sourceCode.getFirstToken(node); - const closeBracket = sourceCode.getLastToken(node); - const firstIncComment = sourceCode.getTokenAfter(openBracket, { includeComments: true }); - const lastIncComment = sourceCode.getTokenBefore(closeBracket, { includeComments: true }); - const first = sourceCode.getTokenAfter(openBracket); - const last = sourceCode.getTokenBefore(closeBracket); - - const needsLinebreaks = ( - elements.length >= options.minItems || - ( - options.multiline && - elements.length > 0 && - firstIncComment.loc.start.line !== lastIncComment.loc.end.line - ) || - ( - elements.length === 0 && - firstIncComment.type === "Block" && - firstIncComment.loc.start.line !== lastIncComment.loc.end.line && - firstIncComment === lastIncComment - ) || - ( - options.consistent && - firstIncComment.loc.start.line !== openBracket.loc.end.line - ) - ); - - /* - * Use tokens or comments to check multiline or not. - * But use only tokens to check whether linebreaks are needed. - * This allows: - * var arr = [ // eslint-disable-line foo - * 'a' - * ] - */ - - if (needsLinebreaks) { - if (astUtils.isTokenOnSameLine(openBracket, first)) { - reportRequiredBeginningLinebreak(node, openBracket); - } - if (astUtils.isTokenOnSameLine(last, closeBracket)) { - reportRequiredEndingLinebreak(node, closeBracket); - } - } else { - if (!astUtils.isTokenOnSameLine(openBracket, first)) { - reportNoBeginningLinebreak(node, openBracket); - } - if (!astUtils.isTokenOnSameLine(last, closeBracket)) { - reportNoEndingLinebreak(node, closeBracket); - } - } - } - - //---------------------------------------------------------------------- - // Public - //---------------------------------------------------------------------- - - return { - ArrayPattern: check, - ArrayExpression: check - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/array-bracket-spacing.js b/tools/node_modules/eslint/lib/rules/array-bracket-spacing.js deleted file mode 100644 index 4bead37a12f51e..00000000000000 --- a/tools/node_modules/eslint/lib/rules/array-bracket-spacing.js +++ /dev/null @@ -1,241 +0,0 @@ -/** - * @fileoverview Disallows or enforces spaces inside of array brackets. - * @author Jamund Ferguson - */ -"use strict"; - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce consistent spacing inside array brackets", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/array-bracket-spacing" - }, - - fixable: "whitespace", - - schema: [ - { - enum: ["always", "never"] - }, - { - type: "object", - properties: { - singleValue: { - type: "boolean" - }, - objectsInArrays: { - type: "boolean" - }, - arraysInArrays: { - type: "boolean" - } - }, - additionalProperties: false - } - ], - - messages: { - unexpectedSpaceAfter: "There should be no space after '{{tokenValue}}'.", - unexpectedSpaceBefore: "There should be no space before '{{tokenValue}}'.", - missingSpaceAfter: "A space is required after '{{tokenValue}}'.", - missingSpaceBefore: "A space is required before '{{tokenValue}}'." - } - }, - create(context) { - const spaced = context.options[0] === "always", - sourceCode = context.getSourceCode(); - - /** - * Determines whether an option is set, relative to the spacing option. - * If spaced is "always", then check whether option is set to false. - * If spaced is "never", then check whether option is set to true. - * @param {Object} option - The option to exclude. - * @returns {boolean} Whether or not the property is excluded. - */ - function isOptionSet(option) { - return context.options[1] ? context.options[1][option] === !spaced : false; - } - - const options = { - spaced, - singleElementException: isOptionSet("singleValue"), - objectsInArraysException: isOptionSet("objectsInArrays"), - arraysInArraysException: isOptionSet("arraysInArrays") - }; - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Reports that there shouldn't be a space after the first token - * @param {ASTNode} node - The node to report in the event of an error. - * @param {Token} token - The token to use for the report. - * @returns {void} - */ - function reportNoBeginningSpace(node, token) { - context.report({ - node, - loc: token.loc.start, - messageId: "unexpectedSpaceAfter", - data: { - tokenValue: token.value - }, - fix(fixer) { - const nextToken = sourceCode.getTokenAfter(token); - - return fixer.removeRange([token.range[1], nextToken.range[0]]); - } - }); - } - - /** - * Reports that there shouldn't be a space before the last token - * @param {ASTNode} node - The node to report in the event of an error. - * @param {Token} token - The token to use for the report. - * @returns {void} - */ - function reportNoEndingSpace(node, token) { - context.report({ - node, - loc: token.loc.start, - messageId: "unexpectedSpaceBefore", - data: { - tokenValue: token.value - }, - fix(fixer) { - const previousToken = sourceCode.getTokenBefore(token); - - return fixer.removeRange([previousToken.range[1], token.range[0]]); - } - }); - } - - /** - * Reports that there should be a space after the first token - * @param {ASTNode} node - The node to report in the event of an error. - * @param {Token} token - The token to use for the report. - * @returns {void} - */ - function reportRequiredBeginningSpace(node, token) { - context.report({ - node, - loc: token.loc.start, - messageId: "missingSpaceAfter", - data: { - tokenValue: token.value - }, - fix(fixer) { - return fixer.insertTextAfter(token, " "); - } - }); - } - - /** - * Reports that there should be a space before the last token - * @param {ASTNode} node - The node to report in the event of an error. - * @param {Token} token - The token to use for the report. - * @returns {void} - */ - function reportRequiredEndingSpace(node, token) { - context.report({ - node, - loc: token.loc.start, - messageId: "missingSpaceBefore", - data: { - tokenValue: token.value - }, - fix(fixer) { - return fixer.insertTextBefore(token, " "); - } - }); - } - - /** - * Determines if a node is an object type - * @param {ASTNode} node - The node to check. - * @returns {boolean} Whether or not the node is an object type. - */ - function isObjectType(node) { - return node && (node.type === "ObjectExpression" || node.type === "ObjectPattern"); - } - - /** - * Determines if a node is an array type - * @param {ASTNode} node - The node to check. - * @returns {boolean} Whether or not the node is an array type. - */ - function isArrayType(node) { - return node && (node.type === "ArrayExpression" || node.type === "ArrayPattern"); - } - - /** - * Validates the spacing around array brackets - * @param {ASTNode} node - The node we're checking for spacing - * @returns {void} - */ - function validateArraySpacing(node) { - if (options.spaced && node.elements.length === 0) { - return; - } - - const first = sourceCode.getFirstToken(node), - second = sourceCode.getFirstToken(node, 1), - 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]; - - const openingBracketMustBeSpaced = - options.objectsInArraysException && isObjectType(firstElement) || - options.arraysInArraysException && isArrayType(firstElement) || - options.singleElementException && node.elements.length === 1 - ? !options.spaced : options.spaced; - - const closingBracketMustBeSpaced = - options.objectsInArraysException && isObjectType(lastElement) || - options.arraysInArraysException && isArrayType(lastElement) || - options.singleElementException && node.elements.length === 1 - ? !options.spaced : options.spaced; - - if (astUtils.isTokenOnSameLine(first, second)) { - if (openingBracketMustBeSpaced && !sourceCode.isSpaceBetweenTokens(first, second)) { - reportRequiredBeginningSpace(node, first); - } - if (!openingBracketMustBeSpaced && sourceCode.isSpaceBetweenTokens(first, second)) { - reportNoBeginningSpace(node, first); - } - } - - if (first !== penultimate && astUtils.isTokenOnSameLine(penultimate, last)) { - if (closingBracketMustBeSpaced && !sourceCode.isSpaceBetweenTokens(penultimate, last)) { - reportRequiredEndingSpace(node, last); - } - if (!closingBracketMustBeSpaced && sourceCode.isSpaceBetweenTokens(penultimate, last)) { - reportNoEndingSpace(node, last); - } - } - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - ArrayPattern: validateArraySpacing, - ArrayExpression: validateArraySpacing - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/array-callback-return.js b/tools/node_modules/eslint/lib/rules/array-callback-return.js deleted file mode 100644 index f88f4b8bfaeddd..00000000000000 --- a/tools/node_modules/eslint/lib/rules/array-callback-return.js +++ /dev/null @@ -1,258 +0,0 @@ -/** - * @fileoverview Rule to enforce return statements in callbacks of array's methods - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const lodash = require("lodash"); - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const TARGET_NODE_TYPE = /^(?:Arrow)?FunctionExpression$/; -const TARGET_METHODS = /^(?:every|filter|find(?:Index)?|map|reduce(?:Right)?|some|sort)$/; - -/** - * Checks a given code path segment is reachable. - * - * @param {CodePathSegment} segment - A segment to check. - * @returns {boolean} `true` if the segment is reachable. - */ -function isReachable(segment) { - return segment.reachable; -} - -/** - * Gets a readable location. - * - * - FunctionExpression -> the function name or `function` keyword. - * - ArrowFunctionExpression -> `=>` token. - * - * @param {ASTNode} node - A function node to get. - * @param {SourceCode} sourceCode - A source code to get tokens. - * @returns {ASTNode|Token} The node or the token of a location. - */ -function getLocation(node, sourceCode) { - if (node.type === "ArrowFunctionExpression") { - return sourceCode.getTokenBefore(node.body); - } - return node.id || node; -} - -/** - * Checks a given node is a MemberExpression node which has the specified name's - * property. - * - * @param {ASTNode} node - A node to check. - * @returns {boolean} `true` if the node is a MemberExpression node which has - * the specified name's property - */ -function isTargetMethod(node) { - return ( - node.type === "MemberExpression" && - TARGET_METHODS.test(astUtils.getStaticPropertyName(node) || "") - ); -} - -/** - * Checks whether or not a given node is a function expression which is the - * callback of an array method. - * - * @param {ASTNode} node - A node to check. This is one of - * FunctionExpression or ArrowFunctionExpression. - * @returns {boolean} `true` if the node is the callback of an array method. - */ -function isCallbackOfArrayMethod(node) { - let currentNode = node; - - while (currentNode) { - const parent = currentNode.parent; - - switch (parent.type) { - - /* - * Looks up the destination. e.g., - * foo.every(nativeFoo || function foo() { ... }); - */ - case "LogicalExpression": - case "ConditionalExpression": - currentNode = parent; - break; - - /* - * If the upper function is IIFE, checks the destination of the return value. - * e.g. - * foo.every((function() { - * // setup... - * return function callback() { ... }; - * })()); - */ - case "ReturnStatement": { - const func = astUtils.getUpperFunction(parent); - - if (func === null || !astUtils.isCallee(func)) { - return false; - } - currentNode = func.parent; - break; - } - - /* - * e.g. - * Array.from([], function() {}); - * list.every(function() {}); - */ - case "CallExpression": - if (astUtils.isArrayFromMethod(parent.callee)) { - return ( - parent.arguments.length >= 2 && - parent.arguments[1] === currentNode - ); - } - if (isTargetMethod(parent.callee)) { - return ( - parent.arguments.length >= 1 && - parent.arguments[0] === currentNode - ); - } - return false; - - // Otherwise this node is not target. - default: - return false; - } - } - - /* istanbul ignore next: unreachable */ - return false; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "enforce `return` statements in callbacks of array methods", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/array-callback-return" - }, - - schema: [ - { - type: "object", - properties: { - allowImplicit: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - - messages: { - expectedAtEnd: "Expected to return a value at the end of {{name}}.", - expectedInside: "Expected to return a value in {{name}}.", - expectedReturnValue: "{{name}} expected a return value." - } - }, - - create(context) { - - const options = context.options[0] || { allowImplicit: false }; - - let funcInfo = { - upper: null, - codePath: null, - hasReturn: false, - shouldCheck: false, - node: null - }; - - /** - * Checks whether or not the last code path segment is reachable. - * Then reports this function if the segment is reachable. - * - * If the last code path segment is reachable, there are paths which are not - * returned or thrown. - * - * @param {ASTNode} node - A node to check. - * @returns {void} - */ - function checkLastSegment(node) { - if (funcInfo.shouldCheck && - funcInfo.codePath.currentSegments.some(isReachable) - ) { - context.report({ - node, - loc: getLocation(node, context.getSourceCode()).loc.start, - messageId: funcInfo.hasReturn - ? "expectedAtEnd" - : "expectedInside", - data: { - name: astUtils.getFunctionNameWithKind(funcInfo.node) - } - }); - } - } - - return { - - // Stacks this function's information. - onCodePathStart(codePath, node) { - funcInfo = { - upper: funcInfo, - codePath, - hasReturn: false, - shouldCheck: - TARGET_NODE_TYPE.test(node.type) && - node.body.type === "BlockStatement" && - isCallbackOfArrayMethod(node) && - !node.async && - !node.generator, - node - }; - }, - - // Pops this function's information. - onCodePathEnd() { - funcInfo = funcInfo.upper; - }, - - // Checks the return statement is valid. - ReturnStatement(node) { - if (funcInfo.shouldCheck) { - funcInfo.hasReturn = true; - - // if allowImplicit: false, should also check node.argument - if (!options.allowImplicit && !node.argument) { - context.report({ - node, - messageId: "expectedReturnValue", - data: { - name: lodash.upperFirst(astUtils.getFunctionNameWithKind(funcInfo.node)) - } - }); - } - } - }, - - // Reports a given function if the last path is reachable. - "FunctionExpression:exit": checkLastSegment, - "ArrowFunctionExpression:exit": checkLastSegment - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/array-element-newline.js b/tools/node_modules/eslint/lib/rules/array-element-newline.js deleted file mode 100644 index 0efceedd27e691..00000000000000 --- a/tools/node_modules/eslint/lib/rules/array-element-newline.js +++ /dev/null @@ -1,264 +0,0 @@ -/** - * @fileoverview Rule to enforce line breaks after each array element - * @author Jan Peer Stöcklmair - */ - -"use strict"; - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce line breaks after each array element", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/array-element-newline" - }, - - fixable: "whitespace", - - schema: [ - { - oneOf: [ - { - enum: ["always", "never", "consistent"] - }, - { - type: "object", - properties: { - multiline: { - type: "boolean", - default: false - }, - minItems: { - type: ["integer", "null"], - minimum: 0, - default: null - } - }, - additionalProperties: false - } - ] - } - ], - - messages: { - unexpectedLineBreak: "There should be no linebreak here.", - missingLineBreak: "There should be a linebreak after this element." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - //---------------------------------------------------------------------- - // Helpers - //---------------------------------------------------------------------- - - /** - * Normalizes a given option value. - * - * @param {string|Object|undefined} providedOption - An option value to parse. - * @returns {{multiline: boolean, minItems: number}} Normalized option object. - */ - function normalizeOptionValue(providedOption) { - let consistent = false; - let multiline = false; - let minItems; - - const option = providedOption || "always"; - - if (!option || option === "always" || option.minItems === 0) { - minItems = 0; - } else if (option === "never") { - minItems = Number.POSITIVE_INFINITY; - } else if (option === "consistent") { - consistent = true; - minItems = Number.POSITIVE_INFINITY; - } else { - multiline = Boolean(option.multiline); - minItems = option.minItems || Number.POSITIVE_INFINITY; - } - - return { consistent, multiline, minItems }; - } - - /** - * Normalizes a given option value. - * - * @param {string|Object|undefined} options - An option value to parse. - * @returns {{ArrayExpression: {multiline: boolean, minItems: number}, ArrayPattern: {multiline: boolean, minItems: number}}} Normalized option object. - */ - function normalizeOptions(options) { - const value = normalizeOptionValue(options); - - return { ArrayExpression: value, ArrayPattern: value }; - } - - /** - * Reports that there shouldn't be a line break after the first token - * @param {Token} token - The token to use for the report. - * @returns {void} - */ - function reportNoLineBreak(token) { - const tokenBefore = sourceCode.getTokenBefore(token, { includeComments: true }); - - context.report({ - loc: { - start: tokenBefore.loc.end, - end: token.loc.start - }, - messageId: "unexpectedLineBreak", - fix(fixer) { - if (astUtils.isCommentToken(tokenBefore)) { - return null; - } - - if (!astUtils.isTokenOnSameLine(tokenBefore, token)) { - return fixer.replaceTextRange([tokenBefore.range[1], token.range[0]], " "); - } - - /* - * This will check if the comma is on the same line as the next element - * Following array: - * [ - * 1 - * , 2 - * , 3 - * ] - * - * will be fixed to: - * [ - * 1, 2, 3 - * ] - */ - const twoTokensBefore = sourceCode.getTokenBefore(tokenBefore, { includeComments: true }); - - if (astUtils.isCommentToken(twoTokensBefore)) { - return null; - } - - return fixer.replaceTextRange([twoTokensBefore.range[1], tokenBefore.range[0]], ""); - - } - }); - } - - /** - * Reports that there should be a line break after the first token - * @param {Token} token - The token to use for the report. - * @returns {void} - */ - function reportRequiredLineBreak(token) { - const tokenBefore = sourceCode.getTokenBefore(token, { includeComments: true }); - - context.report({ - loc: { - start: tokenBefore.loc.end, - end: token.loc.start - }, - messageId: "missingLineBreak", - fix(fixer) { - return fixer.replaceTextRange([tokenBefore.range[1], token.range[0]], "\n"); - } - }); - } - - /** - * Reports a given node if it violated this rule. - * - * @param {ASTNode} node - A node to check. This is an ObjectExpression node or an ObjectPattern node. - * @returns {void} - */ - function check(node) { - const elements = node.elements; - const normalizedOptions = normalizeOptions(context.options[0]); - const options = normalizedOptions[node.type]; - - let elementBreak = false; - - /* - * MULTILINE: true - * loop through every element and check - * if at least one element has linebreaks inside - * this ensures that following is not valid (due to elements are on the same line): - * - * [ - * 1, - * 2, - * 3 - * ] - */ - if (options.multiline) { - elementBreak = elements - .filter(element => element !== null) - .some(element => element.loc.start.line !== element.loc.end.line); - } - - const linebreaksCount = node.elements.map((element, i) => { - const previousElement = elements[i - 1]; - - if (i === 0 || element === null || previousElement === null) { - return false; - } - - const commaToken = sourceCode.getFirstTokenBetween(previousElement, element, astUtils.isCommaToken); - const lastTokenOfPreviousElement = sourceCode.getTokenBefore(commaToken); - const firstTokenOfCurrentElement = sourceCode.getTokenAfter(commaToken); - - return !astUtils.isTokenOnSameLine(lastTokenOfPreviousElement, firstTokenOfCurrentElement); - }).filter(isBreak => isBreak === true).length; - - const needsLinebreaks = ( - elements.length >= options.minItems || - ( - options.multiline && - elementBreak - ) || - ( - options.consistent && - linebreaksCount > 0 && - linebreaksCount < node.elements.length - ) - ); - - elements.forEach((element, i) => { - const previousElement = elements[i - 1]; - - if (i === 0 || element === null || previousElement === null) { - return; - } - - const commaToken = sourceCode.getFirstTokenBetween(previousElement, element, astUtils.isCommaToken); - const lastTokenOfPreviousElement = sourceCode.getTokenBefore(commaToken); - const firstTokenOfCurrentElement = sourceCode.getTokenAfter(commaToken); - - if (needsLinebreaks) { - if (astUtils.isTokenOnSameLine(lastTokenOfPreviousElement, firstTokenOfCurrentElement)) { - reportRequiredLineBreak(firstTokenOfCurrentElement); - } - } else { - if (!astUtils.isTokenOnSameLine(lastTokenOfPreviousElement, firstTokenOfCurrentElement)) { - reportNoLineBreak(firstTokenOfCurrentElement); - } - } - }); - } - - //---------------------------------------------------------------------- - // Public - //---------------------------------------------------------------------- - - return { - ArrayPattern: check, - ArrayExpression: check - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/arrow-body-style.js b/tools/node_modules/eslint/lib/rules/arrow-body-style.js deleted file mode 100644 index 83fc28aba06fab..00000000000000 --- a/tools/node_modules/eslint/lib/rules/arrow-body-style.js +++ /dev/null @@ -1,240 +0,0 @@ -/** - * @fileoverview Rule to require braces in arrow function body. - * @author Alberto Rodríguez - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require braces around arrow function bodies", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/arrow-body-style" - }, - - schema: { - anyOf: [ - { - type: "array", - items: [ - { - enum: ["always", "never"] - } - ], - minItems: 0, - maxItems: 1 - }, - { - type: "array", - items: [ - { - enum: ["as-needed"] - }, - { - type: "object", - properties: { - requireReturnForObjectLiteral: { type: "boolean", default: false } - }, - additionalProperties: false - } - ], - minItems: 0, - maxItems: 2 - } - ] - }, - - fixable: "code", - - messages: { - unexpectedOtherBlock: "Unexpected block statement surrounding arrow body.", - unexpectedEmptyBlock: "Unexpected block statement surrounding arrow body; put a value of `undefined` immediately after the `=>`.", - unexpectedObjectBlock: "Unexpected block statement surrounding arrow body; parenthesize the returned value and move it immediately after the `=>`.", - unexpectedSingleBlock: "Unexpected block statement surrounding arrow body; move the returned value immediately after the `=>`.", - expectedBlock: "Expected block statement surrounding arrow body." - } - }, - - create(context) { - const options = context.options; - const always = options[0] === "always"; - const asNeeded = !options[0] || options[0] === "as-needed"; - const never = options[0] === "never"; - const requireReturnForObjectLiteral = options[1] && options[1].requireReturnForObjectLiteral; - const sourceCode = context.getSourceCode(); - - /** - * Checks whether the given node has ASI problem or not. - * @param {Token} token The token to check. - * @returns {boolean} `true` if it changes semantics if `;` or `}` followed by the token are removed. - */ - function hasASIProblem(token) { - return token && token.type === "Punctuator" && /^[([/`+-]/.test(token.value); - } - - /** - * Gets the closing parenthesis which is the pair of the given opening parenthesis. - * @param {Token} token The opening parenthesis token to get. - * @returns {Token} The found closing parenthesis token. - */ - function findClosingParen(token) { - let node = sourceCode.getNodeByRangeIndex(token.range[1]); - - while (!astUtils.isParenthesised(sourceCode, node)) { - node = node.parent; - } - return sourceCode.getTokenAfter(node); - } - - /** - * Determines whether a arrow function body needs braces - * @param {ASTNode} node The arrow function node. - * @returns {void} - */ - function validate(node) { - const arrowBody = node.body; - - if (arrowBody.type === "BlockStatement") { - 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") { - let messageId; - - if (blockBody.length === 0) { - messageId = "unexpectedEmptyBlock"; - } else if (blockBody.length > 1) { - messageId = "unexpectedOtherBlock"; - } else if (blockBody[0].argument === null) { - messageId = "unexpectedSingleBlock"; - } else if (astUtils.isOpeningBraceToken(sourceCode.getFirstToken(blockBody[0], { skip: 1 }))) { - messageId = "unexpectedObjectBlock"; - } else { - messageId = "unexpectedSingleBlock"; - } - - context.report({ - node, - loc: arrowBody.loc.start, - messageId, - fix(fixer) { - const fixes = []; - - if (blockBody.length !== 1 || - blockBody[0].type !== "ReturnStatement" || - !blockBody[0].argument || - hasASIProblem(sourceCode.getTokenAfter(arrowBody)) - ) { - return fixes; - } - - const openingBrace = sourceCode.getFirstToken(arrowBody); - const closingBrace = sourceCode.getLastToken(arrowBody); - const firstValueToken = sourceCode.getFirstToken(blockBody[0], 1); - const lastValueToken = sourceCode.getLastToken(blockBody[0]); - const commentsExist = - sourceCode.commentsExistBetween(openingBrace, firstValueToken) || - sourceCode.commentsExistBetween(lastValueToken, closingBrace); - - /* - * Remove tokens around the return value. - * If comments don't exist, remove extra spaces as well. - */ - if (commentsExist) { - fixes.push( - fixer.remove(openingBrace), - fixer.remove(closingBrace), - fixer.remove(sourceCode.getTokenAfter(openingBrace)) // return keyword - ); - } else { - fixes.push( - fixer.removeRange([openingBrace.range[0], firstValueToken.range[0]]), - fixer.removeRange([lastValueToken.range[1], closingBrace.range[1]]) - ); - } - - /* - * If the first token of the reutrn value is `{`, - * enclose the return value by parentheses to avoid syntax error. - */ - if (astUtils.isOpeningBraceToken(firstValueToken)) { - fixes.push( - fixer.insertTextBefore(firstValueToken, "("), - fixer.insertTextAfter(lastValueToken, ")") - ); - } - - /* - * If the last token of the return statement is semicolon, remove it. - * Non-block arrow body is an expression, not a statement. - */ - if (astUtils.isSemicolonToken(lastValueToken)) { - fixes.push(fixer.remove(lastValueToken)); - } - - return fixes; - } - }); - } - } else { - if (always || (asNeeded && requireReturnForObjectLiteral && arrowBody.type === "ObjectExpression")) { - context.report({ - node, - loc: arrowBody.loc.start, - messageId: "expectedBlock", - fix(fixer) { - const fixes = []; - const arrowToken = sourceCode.getTokenBefore(arrowBody, astUtils.isArrowToken); - const firstBodyToken = sourceCode.getTokenAfter(arrowToken); - const lastBodyToken = sourceCode.getLastToken(node); - const isParenthesisedObjectLiteral = - astUtils.isOpeningParenToken(firstBodyToken) && - astUtils.isOpeningBraceToken(sourceCode.getTokenAfter(firstBodyToken)); - - // Wrap the value by a block and a return statement. - fixes.push( - fixer.insertTextBefore(firstBodyToken, "{return "), - fixer.insertTextAfter(lastBodyToken, "}") - ); - - // If the value is object literal, remove parentheses which were forced by syntax. - if (isParenthesisedObjectLiteral) { - fixes.push( - fixer.remove(firstBodyToken), - fixer.remove(findClosingParen(firstBodyToken)) - ); - } - - return fixes; - } - }); - } - } - } - - return { - "ArrowFunctionExpression:exit": validate - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/arrow-parens.js b/tools/node_modules/eslint/lib/rules/arrow-parens.js deleted file mode 100644 index 217a9b60e13cbb..00000000000000 --- a/tools/node_modules/eslint/lib/rules/arrow-parens.js +++ /dev/null @@ -1,164 +0,0 @@ -/** - * @fileoverview Rule to require parens in arrow function arguments. - * @author Jxck - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "require parentheses around arrow function arguments", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/arrow-parens" - }, - - fixable: "code", - - schema: [ - { - enum: ["always", "as-needed"] - }, - { - type: "object", - properties: { - requireForBlockBody: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - - messages: { - unexpectedParens: "Unexpected parentheses around single function argument.", - expectedParens: "Expected parentheses around arrow function argument.", - - unexpectedParensInline: "Unexpected parentheses around single function argument having a body with no curly braces.", - expectedParensBlock: "Expected parentheses around arrow function argument having a body with curly braces." - } - }, - - create(context) { - const asNeeded = context.options[0] === "as-needed"; - const requireForBlockBody = asNeeded && context.options[1] && context.options[1].requireForBlockBody === true; - - const sourceCode = context.getSourceCode(); - - /** - * Determines whether a arrow function argument end with `)` - * @param {ASTNode} node The arrow function node. - * @returns {void} - */ - function parens(node) { - const isAsync = node.async; - const firstTokenOfParam = sourceCode.getFirstToken(node, isAsync ? 1 : 0); - - /** - * Remove the parenthesis around a parameter - * @param {Fixer} fixer Fixer - * @returns {string} fixed parameter - */ - function fixParamsWithParenthesis(fixer) { - const paramToken = sourceCode.getTokenAfter(firstTokenOfParam); - - /* - * ES8 allows Trailing commas in function parameter lists and calls - * https://github.com/eslint/eslint/issues/8834 - */ - const closingParenToken = sourceCode.getTokenAfter(paramToken, astUtils.isClosingParenToken); - const asyncToken = isAsync ? sourceCode.getTokenBefore(firstTokenOfParam) : null; - const shouldAddSpaceForAsync = asyncToken && (asyncToken.range[1] === firstTokenOfParam.range[0]); - - return fixer.replaceTextRange([ - firstTokenOfParam.range[0], - closingParenToken.range[1] - ], `${shouldAddSpaceForAsync ? " " : ""}${paramToken.value}`); - } - - // "as-needed", { "requireForBlockBody": true }: x => x - if ( - requireForBlockBody && - node.params.length === 1 && - node.params[0].type === "Identifier" && - !node.params[0].typeAnnotation && - node.body.type !== "BlockStatement" && - !node.returnType - ) { - if (astUtils.isOpeningParenToken(firstTokenOfParam)) { - context.report({ - node, - messageId: "unexpectedParensInline", - fix: fixParamsWithParenthesis - }); - } - return; - } - - if ( - requireForBlockBody && - node.body.type === "BlockStatement" - ) { - if (!astUtils.isOpeningParenToken(firstTokenOfParam)) { - context.report({ - node, - messageId: "expectedParensBlock", - fix(fixer) { - return fixer.replaceText(firstTokenOfParam, `(${firstTokenOfParam.value})`); - } - }); - } - return; - } - - // "as-needed": x => x - if (asNeeded && - node.params.length === 1 && - node.params[0].type === "Identifier" && - !node.params[0].typeAnnotation && - !node.returnType - ) { - if (astUtils.isOpeningParenToken(firstTokenOfParam)) { - context.report({ - node, - messageId: "unexpectedParens", - fix: fixParamsWithParenthesis - }); - } - return; - } - - if (firstTokenOfParam.type === "Identifier") { - const after = sourceCode.getTokenAfter(firstTokenOfParam); - - // (x) => x - if (after.value !== ")") { - context.report({ - node, - messageId: "expectedParens", - fix(fixer) { - return fixer.replaceText(firstTokenOfParam, `(${firstTokenOfParam.value})`); - } - }); - } - } - } - - return { - ArrowFunctionExpression: parens - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/arrow-spacing.js b/tools/node_modules/eslint/lib/rules/arrow-spacing.js deleted file mode 100644 index 95acb78772584b..00000000000000 --- a/tools/node_modules/eslint/lib/rules/arrow-spacing.js +++ /dev/null @@ -1,161 +0,0 @@ -/** - * @fileoverview Rule to define spacing before/after arrow function's arrow. - * @author Jxck - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce consistent spacing before and after the arrow in arrow functions", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/arrow-spacing" - }, - - fixable: "whitespace", - - schema: [ - { - type: "object", - properties: { - before: { - type: "boolean", - default: true - }, - after: { - type: "boolean", - default: true - } - }, - additionalProperties: false - } - ], - - messages: { - expectedBefore: "Missing space before =>.", - unexpectedBefore: "Unexpected space before =>.", - - expectedAfter: "Missing space after =>.", - unexpectedAfter: "Unexpected space after =>." - } - }, - - create(context) { - - // merge rules with default - const rule = Object.assign({}, context.options[0]); - - rule.before = rule.before !== false; - rule.after = rule.after !== false; - - const sourceCode = context.getSourceCode(); - - /** - * Get tokens of arrow(`=>`) and before/after arrow. - * @param {ASTNode} node The arrow function node. - * @returns {Object} Tokens of arrow and before/after arrow. - */ - function getTokens(node) { - const arrow = sourceCode.getTokenBefore(node.body, astUtils.isArrowToken); - - return { - before: sourceCode.getTokenBefore(arrow), - arrow, - after: sourceCode.getTokenAfter(arrow) - }; - } - - /** - * Count spaces before/after arrow(`=>`) token. - * @param {Object} tokens Tokens before/after arrow. - * @returns {Object} count of space before/after arrow. - */ - function countSpaces(tokens) { - const before = tokens.arrow.range[0] - tokens.before.range[1]; - const after = tokens.after.range[0] - tokens.arrow.range[1]; - - return { before, after }; - } - - /** - * Determines whether space(s) before after arrow(`=>`) is satisfy rule. - * if before/after value is `true`, there should be space(s). - * if before/after value is `false`, there should be no space. - * @param {ASTNode} node The arrow function node. - * @returns {void} - */ - function spaces(node) { - const tokens = getTokens(node); - const countSpace = countSpaces(tokens); - - if (rule.before) { - - // should be space(s) before arrow - if (countSpace.before === 0) { - context.report({ - node: tokens.before, - messageId: "expectedBefore", - fix(fixer) { - return fixer.insertTextBefore(tokens.arrow, " "); - } - }); - } - } else { - - // should be no space before arrow - if (countSpace.before > 0) { - context.report({ - node: tokens.before, - messageId: "unexpectedBefore", - fix(fixer) { - return fixer.removeRange([tokens.before.range[1], tokens.arrow.range[0]]); - } - }); - } - } - - if (rule.after) { - - // should be space(s) after arrow - if (countSpace.after === 0) { - context.report({ - node: tokens.after, - messageId: "expectedAfter", - fix(fixer) { - return fixer.insertTextAfter(tokens.arrow, " "); - } - }); - } - } else { - - // should be no space after arrow - if (countSpace.after > 0) { - context.report({ - node: tokens.after, - messageId: "unexpectedAfter", - fix(fixer) { - return fixer.removeRange([tokens.arrow.range[1], tokens.after.range[0]]); - } - }); - } - } - } - - return { - ArrowFunctionExpression: spaces - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/block-scoped-var.js b/tools/node_modules/eslint/lib/rules/block-scoped-var.js deleted file mode 100644 index 053cfc334cd11a..00000000000000 --- a/tools/node_modules/eslint/lib/rules/block-scoped-var.js +++ /dev/null @@ -1,122 +0,0 @@ -/** - * @fileoverview Rule to check for "block scoped" variables by binding context - * @author Matt DuVall - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce the use of variables within the scope they are defined", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/block-scoped-var" - }, - - schema: [], - - messages: { - outOfScope: "'{{name}}' used outside of binding context." - } - }, - - create(context) { - let stack = []; - - /** - * Makes a block scope. - * @param {ASTNode} node - A node of a scope. - * @returns {void} - */ - function enterScope(node) { - stack.push(node.range); - } - - /** - * Pops the last block scope. - * @returns {void} - */ - function exitScope() { - stack.pop(); - } - - /** - * Reports a given reference. - * @param {eslint-scope.Reference} reference - A reference to report. - * @returns {void} - */ - function report(reference) { - const identifier = reference.identifier; - - context.report({ node: identifier, messageId: "outOfScope", data: { name: identifier.name } }); - } - - /** - * Finds and reports references which are outside of valid scopes. - * @param {ASTNode} node - A node to get variables. - * @returns {void} - */ - function checkForVariables(node) { - if (node.kind !== "var") { - return; - } - - // Defines a predicate to check whether or not a given reference is outside of valid scope. - const scopeRange = stack[stack.length - 1]; - - /** - * Check if a reference is out of scope - * @param {ASTNode} reference node to examine - * @returns {boolean} True is its outside the scope - * @private - */ - function isOutsideOfScope(reference) { - const idRange = reference.identifier.range; - - return idRange[0] < scopeRange[0] || idRange[1] > scopeRange[1]; - } - - // Gets declared variables, and checks its references. - const variables = context.getDeclaredVariables(node); - - for (let i = 0; i < variables.length; ++i) { - - // Reports. - variables[i] - .references - .filter(isOutsideOfScope) - .forEach(report); - } - } - - return { - Program(node) { - stack = [node.range]; - }, - - // Manages scopes. - BlockStatement: enterScope, - "BlockStatement:exit": exitScope, - ForStatement: enterScope, - "ForStatement:exit": exitScope, - ForInStatement: enterScope, - "ForInStatement:exit": exitScope, - ForOfStatement: enterScope, - "ForOfStatement:exit": exitScope, - SwitchStatement: enterScope, - "SwitchStatement:exit": exitScope, - CatchClause: enterScope, - "CatchClause:exit": exitScope, - - // Finds and reports references which are outside of valid scope. - VariableDeclaration: checkForVariables - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/block-spacing.js b/tools/node_modules/eslint/lib/rules/block-spacing.js deleted file mode 100644 index 864bfc0c5c09de..00000000000000 --- a/tools/node_modules/eslint/lib/rules/block-spacing.js +++ /dev/null @@ -1,147 +0,0 @@ -/** - * @fileoverview A rule to disallow or enforce spaces inside of single line blocks. - * @author Toru Nagashima - */ - -"use strict"; - -const util = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "disallow or enforce spaces inside of blocks after opening block and before closing block", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/block-spacing" - }, - - fixable: "whitespace", - - schema: [ - { enum: ["always", "never"] } - ], - - messages: { - missing: "Requires a space {{location}} '{{token}}'.", - extra: "Unexpected space(s) {{location}} '{{token}}'." - } - }, - - create(context) { - const always = (context.options[0] !== "never"), - messageId = always ? "missing" : "extra", - sourceCode = context.getSourceCode(); - - /** - * Gets the open brace token from a given node. - * @param {ASTNode} node - A BlockStatement/SwitchStatement node to get. - * @returns {Token} The token of the open brace. - */ - function getOpenBrace(node) { - if (node.type === "SwitchStatement") { - if (node.cases.length > 0) { - return sourceCode.getTokenBefore(node.cases[0]); - } - return sourceCode.getLastToken(node, 1); - } - return sourceCode.getFirstToken(node); - } - - /** - * Checks whether or not: - * - given tokens are on same line. - * - there is/isn't a space between given tokens. - * @param {Token} left - A token to check. - * @param {Token} right - The token which is next to `left`. - * @returns {boolean} - * When the option is `"always"`, `true` if there are one or more spaces between given tokens. - * When the option is `"never"`, `true` if there are not any spaces between given tokens. - * If given tokens are not on same line, it's always `true`. - */ - function isValid(left, right) { - return ( - !util.isTokenOnSameLine(left, right) || - sourceCode.isSpaceBetweenTokens(left, right) === always - ); - } - - /** - * Reports invalid spacing style inside braces. - * @param {ASTNode} node - A BlockStatement/SwitchStatement node to get. - * @returns {void} - */ - function checkSpacingInsideBraces(node) { - - // Gets braces and the first/last token of content. - const openBrace = getOpenBrace(node); - const closeBrace = sourceCode.getLastToken(node); - const firstToken = sourceCode.getTokenAfter(openBrace, { includeComments: true }); - const lastToken = sourceCode.getTokenBefore(closeBrace, { includeComments: true }); - - // Skip if the node is invalid or empty. - if (openBrace.type !== "Punctuator" || - openBrace.value !== "{" || - closeBrace.type !== "Punctuator" || - closeBrace.value !== "}" || - firstToken === closeBrace - ) { - return; - } - - // Skip line comments for option never - if (!always && firstToken.type === "Line") { - return; - } - - // Check. - if (!isValid(openBrace, firstToken)) { - context.report({ - node, - loc: openBrace.loc.start, - messageId, - data: { - location: "after", - token: openBrace.value - }, - fix(fixer) { - if (always) { - return fixer.insertTextBefore(firstToken, " "); - } - - return fixer.removeRange([openBrace.range[1], firstToken.range[0]]); - } - }); - } - if (!isValid(lastToken, closeBrace)) { - context.report({ - node, - loc: closeBrace.loc.start, - messageId, - data: { - location: "before", - token: closeBrace.value - }, - fix(fixer) { - if (always) { - return fixer.insertTextAfter(lastToken, " "); - } - - return fixer.removeRange([lastToken.range[1], closeBrace.range[0]]); - } - }); - } - } - - return { - BlockStatement: checkSpacingInsideBraces, - SwitchStatement: checkSpacingInsideBraces - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/brace-style.js b/tools/node_modules/eslint/lib/rules/brace-style.js deleted file mode 100644 index 17a5c7fdf9a37f..00000000000000 --- a/tools/node_modules/eslint/lib/rules/brace-style.js +++ /dev/null @@ -1,188 +0,0 @@ -/** - * @fileoverview Rule to flag block statements that do not use the one true brace style - * @author Ian Christian Myers - */ - -"use strict"; - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce consistent brace style for blocks", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/brace-style" - }, - - schema: [ - { - enum: ["1tbs", "stroustrup", "allman"] - }, - { - type: "object", - properties: { - allowSingleLine: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - - fixable: "whitespace", - - messages: { - nextLineOpen: "Opening curly brace does not appear on the same line as controlling statement.", - sameLineOpen: "Opening curly brace appears on the same line as controlling statement.", - blockSameLine: "Statement inside of curly braces should be on next line.", - nextLineClose: "Closing curly brace does not appear on the same line as the subsequent block.", - singleLineClose: "Closing curly brace should be on the same line as opening curly brace or on the line after the previous block.", - sameLineClose: "Closing curly brace appears on the same line as the subsequent block." - } - }, - - create(context) { - const style = context.options[0] || "1tbs", - params = context.options[1] || {}, - sourceCode = context.getSourceCode(); - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Fixes a place where a newline unexpectedly appears - * @param {Token} firstToken The token before the unexpected newline - * @param {Token} secondToken The token after the unexpected newline - * @returns {Function} A fixer function to remove the newlines between the tokens - */ - function removeNewlineBetween(firstToken, secondToken) { - const textRange = [firstToken.range[1], secondToken.range[0]]; - const textBetween = sourceCode.text.slice(textRange[0], textRange[1]); - - // Don't do a fix if there is a comment between the tokens - if (textBetween.trim()) { - return null; - } - return fixer => fixer.replaceTextRange(textRange, " "); - } - - /** - * Validates a pair of curly brackets based on the user's config - * @param {Token} openingCurly The opening curly bracket - * @param {Token} closingCurly The closing curly bracket - * @returns {void} - */ - function validateCurlyPair(openingCurly, closingCurly) { - const tokenBeforeOpeningCurly = sourceCode.getTokenBefore(openingCurly); - const tokenAfterOpeningCurly = sourceCode.getTokenAfter(openingCurly); - const tokenBeforeClosingCurly = sourceCode.getTokenBefore(closingCurly); - const singleLineException = params.allowSingleLine && astUtils.isTokenOnSameLine(openingCurly, closingCurly); - - if (style !== "allman" && !astUtils.isTokenOnSameLine(tokenBeforeOpeningCurly, openingCurly)) { - context.report({ - node: openingCurly, - messageId: "nextLineOpen", - fix: removeNewlineBetween(tokenBeforeOpeningCurly, openingCurly) - }); - } - - if (style === "allman" && astUtils.isTokenOnSameLine(tokenBeforeOpeningCurly, openingCurly) && !singleLineException) { - context.report({ - node: openingCurly, - messageId: "sameLineOpen", - fix: fixer => fixer.insertTextBefore(openingCurly, "\n") - }); - } - - if (astUtils.isTokenOnSameLine(openingCurly, tokenAfterOpeningCurly) && tokenAfterOpeningCurly !== closingCurly && !singleLineException) { - context.report({ - node: openingCurly, - messageId: "blockSameLine", - fix: fixer => fixer.insertTextAfter(openingCurly, "\n") - }); - } - - if (tokenBeforeClosingCurly !== openingCurly && !singleLineException && astUtils.isTokenOnSameLine(tokenBeforeClosingCurly, closingCurly)) { - context.report({ - node: closingCurly, - messageId: "singleLineClose", - fix: fixer => fixer.insertTextBefore(closingCurly, "\n") - }); - } - } - - /** - * Validates the location of a token that appears before a keyword (e.g. a newline before `else`) - * @param {Token} curlyToken The closing curly token. This is assumed to precede a keyword token (such as `else` or `finally`). - * @returns {void} - */ - function validateCurlyBeforeKeyword(curlyToken) { - const keywordToken = sourceCode.getTokenAfter(curlyToken); - - if (style === "1tbs" && !astUtils.isTokenOnSameLine(curlyToken, keywordToken)) { - context.report({ - node: curlyToken, - messageId: "nextLineClose", - fix: removeNewlineBetween(curlyToken, keywordToken) - }); - } - - if (style !== "1tbs" && astUtils.isTokenOnSameLine(curlyToken, keywordToken)) { - context.report({ - node: curlyToken, - messageId: "sameLineClose", - fix: fixer => fixer.insertTextAfter(curlyToken, "\n") - }); - } - } - - //-------------------------------------------------------------------------- - // Public API - //-------------------------------------------------------------------------- - - return { - BlockStatement(node) { - if (!astUtils.STATEMENT_LIST_PARENTS.has(node.parent.type)) { - validateCurlyPair(sourceCode.getFirstToken(node), sourceCode.getLastToken(node)); - } - }, - ClassBody(node) { - validateCurlyPair(sourceCode.getFirstToken(node), sourceCode.getLastToken(node)); - }, - SwitchStatement(node) { - const closingCurly = sourceCode.getLastToken(node); - const openingCurly = sourceCode.getTokenBefore(node.cases.length ? node.cases[0] : closingCurly); - - validateCurlyPair(openingCurly, closingCurly); - }, - IfStatement(node) { - if (node.consequent.type === "BlockStatement" && node.alternate) { - - // Handle the keyword after the `if` block (before `else`) - validateCurlyBeforeKeyword(sourceCode.getLastToken(node.consequent)); - } - }, - TryStatement(node) { - - // Handle the keyword after the `try` block (before `catch` or `finally`) - validateCurlyBeforeKeyword(sourceCode.getLastToken(node.block)); - - if (node.handler && node.finalizer) { - - // Handle the keyword after the `catch` block (before `finally`) - validateCurlyBeforeKeyword(sourceCode.getLastToken(node.handler.body)); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/callback-return.js b/tools/node_modules/eslint/lib/rules/callback-return.js deleted file mode 100644 index c5263cde46b752..00000000000000 --- a/tools/node_modules/eslint/lib/rules/callback-return.js +++ /dev/null @@ -1,182 +0,0 @@ -/** - * @fileoverview Enforce return after a callback. - * @author Jamund Ferguson - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require `return` statements after callbacks", - category: "Node.js and CommonJS", - recommended: false, - url: "https://eslint.org/docs/rules/callback-return" - }, - - schema: [{ - type: "array", - items: { type: "string" } - }], - - messages: { - missingReturn: "Expected return with your callback function." - } - }, - - create(context) { - - const callbacks = context.options[0] || ["callback", "cb", "next"], - sourceCode = context.getSourceCode(); - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Find the closest parent matching a list of types. - * @param {ASTNode} node The node whose parents we are searching - * @param {Array} types The node types to match - * @returns {ASTNode} The matched node or undefined. - */ - function findClosestParentOfType(node, types) { - if (!node.parent) { - return null; - } - if (types.indexOf(node.parent.type) === -1) { - return findClosestParentOfType(node.parent, types); - } - return node.parent; - } - - /** - * Check to see if a node contains only identifers - * @param {ASTNode} node The node to check - * @returns {boolean} Whether or not the node contains only identifers - */ - function containsOnlyIdentifiers(node) { - if (node.type === "Identifier") { - return true; - } - - if (node.type === "MemberExpression") { - if (node.object.type === "Identifier") { - return true; - } - if (node.object.type === "MemberExpression") { - return containsOnlyIdentifiers(node.object); - } - } - - return false; - } - - /** - * Check to see if a CallExpression is in our callback list. - * @param {ASTNode} node The node to check against our callback names list. - * @returns {boolean} Whether or not this function matches our callback name. - */ - function isCallback(node) { - return containsOnlyIdentifiers(node.callee) && callbacks.indexOf(sourceCode.getText(node.callee)) > -1; - } - - /** - * Determines whether or not the callback is part of a callback expression. - * @param {ASTNode} node The callback node - * @param {ASTNode} parentNode The expression node - * @returns {boolean} Whether or not this is part of a callback expression - */ - function isCallbackExpression(node, parentNode) { - - // ensure the parent node exists and is an expression - if (!parentNode || parentNode.type !== "ExpressionStatement") { - return false; - } - - // cb() - if (parentNode.expression === node) { - return true; - } - - // special case for cb && cb() and similar - if (parentNode.expression.type === "BinaryExpression" || parentNode.expression.type === "LogicalExpression") { - if (parentNode.expression.right === node) { - return true; - } - } - - return false; - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - CallExpression(node) { - - // if we're not a callback we can return - if (!isCallback(node)) { - return; - } - - // find the closest block, return or loop - const closestBlock = findClosestParentOfType(node, ["BlockStatement", "ReturnStatement", "ArrowFunctionExpression"]) || {}; - - // if our parent is a return we know we're ok - if (closestBlock.type === "ReturnStatement") { - return; - } - - // arrow functions don't always have blocks and implicitly return - if (closestBlock.type === "ArrowFunctionExpression") { - return; - } - - // block statements are part of functions and most if statements - if (closestBlock.type === "BlockStatement") { - - // find the last item in the block - const lastItem = closestBlock.body[closestBlock.body.length - 1]; - - // if the callback is the last thing in a block that might be ok - if (isCallbackExpression(node, lastItem)) { - - const parentType = closestBlock.parent.type; - - // but only if the block is part of a function - if (parentType === "FunctionExpression" || - parentType === "FunctionDeclaration" || - parentType === "ArrowFunctionExpression" - ) { - return; - } - - } - - // ending a block with a return is also ok - if (lastItem.type === "ReturnStatement") { - - // but only if the callback is immediately before - if (isCallbackExpression(node, closestBlock.body[closestBlock.body.length - 2])) { - return; - } - } - - } - - // 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, messageId: "missingReturn" }); - } - - } - - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/camelcase.js b/tools/node_modules/eslint/lib/rules/camelcase.js deleted file mode 100644 index 6dd3793f665ed2..00000000000000 --- a/tools/node_modules/eslint/lib/rules/camelcase.js +++ /dev/null @@ -1,228 +0,0 @@ -/** - * @fileoverview Rule to flag non-camelcased identifiers - * @author Nicholas C. Zakas - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce camelcase naming convention", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/camelcase" - }, - - schema: [ - { - type: "object", - properties: { - ignoreDestructuring: { - type: "boolean", - default: false - }, - properties: { - enum: ["always", "never"] - }, - allow: { - type: "array", - items: [ - { - type: "string" - } - ], - minItems: 0, - uniqueItems: true - } - }, - additionalProperties: false - } - ], - - messages: { - notCamelCase: "Identifier '{{name}}' is not in camel case." - } - }, - - create(context) { - - const options = context.options[0] || {}; - let properties = options.properties || ""; - const ignoreDestructuring = options.ignoreDestructuring; - const allow = options.allow || []; - - if (properties !== "always" && properties !== "never") { - properties = "always"; - } - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - // 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 - * @param {string} name The string to check. - * @returns {boolean} if the string is underscored - * @private - */ - function isUnderscored(name) { - - // if there's an underscore, it might be A_CONSTANT, which is okay - return name.indexOf("_") > -1 && name !== name.toUpperCase(); - } - - /** - * Checks if a string match the ignore list - * @param {string} name The string to check. - * @returns {boolean} if the string is ignored - * @private - */ - function isAllowed(name) { - return allow.findIndex( - entry => name === entry || name.match(new RegExp(entry)) - ) !== -1; - } - - /** - * Checks if a parent of a node is an ObjectPattern. - * @param {ASTNode} node The node to check. - * @returns {boolean} if the node is inside an ObjectPattern - * @private - */ - function isInsideObjectPattern(node) { - let current = node; - - while (current) { - const parent = current.parent; - - if (parent && parent.type === "Property" && parent.computed && parent.key === current) { - return false; - } - - if (current.type === "ObjectPattern") { - return true; - } - - current = parent; - } - - return false; - } - - /** - * Reports an AST node as a rule violation. - * @param {ASTNode} node The node to report. - * @returns {void} - * @private - */ - function report(node) { - if (reported.indexOf(node) < 0) { - reported.push(node); - context.report({ node, messageId: "notCamelCase", data: { name: node.name } }); - } - } - - return { - - Identifier(node) { - - /* - * Leading and trailing underscores are commonly used to flag - * private/protected identifiers, strip them before checking if underscored - */ - const name = node.name, - nameIsUnderscored = isUnderscored(name.replace(/^_+|_+$/g, "")), - effectiveParent = (node.parent.type === "MemberExpression") ? node.parent.parent : node.parent; - - // First, we ignore the node if it match the ignore list - if (isAllowed(name)) { - return; - } - - // MemberExpressions get special rules - if (node.parent.type === "MemberExpression") { - - // "never" check properties - if (properties === "never") { - return; - } - - // Always report underscored object names - if (node.parent.object.type === "Identifier" && node.parent.object.name === node.name && nameIsUnderscored) { - report(node); - - // Report AssignmentExpressions only if they are the left side of the assignment - } else if (effectiveParent.type === "AssignmentExpression" && nameIsUnderscored && (effectiveParent.right.type !== "MemberExpression" || effectiveParent.left.type === "MemberExpression" && effectiveParent.left.property.name === node.name)) { - report(node); - } - - /* - * Properties have their own rules, and - * AssignmentPattern nodes can be treated like Properties: - * e.g.: const { no_camelcased = false } = bar; - */ - } else if (node.parent.type === "Property" || node.parent.type === "AssignmentPattern") { - - if (node.parent.parent && node.parent.parent.type === "ObjectPattern") { - if (node.parent.shorthand && node.parent.value.left && nameIsUnderscored) { - report(node); - } - - const assignmentKeyEqualsValue = node.parent.key.name === node.parent.value.name; - - if (isUnderscored(name) && node.parent.computed) { - report(node); - } - - // prevent checking righthand side of destructured object - if (node.parent.key === node && node.parent.value !== node) { - return; - } - - const valueIsUnderscored = node.parent.value.name && nameIsUnderscored; - - // ignore destructuring if the option is set, unless a new identifier is created - if (valueIsUnderscored && !(assignmentKeyEqualsValue && ignoreDestructuring)) { - report(node); - } - } - - // "never" check properties or always ignore destructuring - if (properties === "never" || (ignoreDestructuring && isInsideObjectPattern(node))) { - return; - } - - // don't check right hand side of AssignmentExpression to prevent duplicate warnings - if (nameIsUnderscored && !ALLOWED_PARENT_TYPES.has(effectiveParent.type) && !(node.parent.right === node)) { - report(node); - } - - // Check if it's an import specifier - } else if (["ImportSpecifier", "ImportNamespaceSpecifier", "ImportDefaultSpecifier"].indexOf(node.parent.type) >= 0) { - - // Report only if the local imported identifier is underscored - if (node.parent.local && node.parent.local.name === node.name && nameIsUnderscored) { - report(node); - } - - // Report anything that is underscored that isn't a CallExpression - } else if (nameIsUnderscored && !ALLOWED_PARENT_TYPES.has(effectiveParent.type)) { - report(node); - } - } - - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/capitalized-comments.js b/tools/node_modules/eslint/lib/rules/capitalized-comments.js deleted file mode 100644 index 285f856379d487..00000000000000 --- a/tools/node_modules/eslint/lib/rules/capitalized-comments.js +++ /dev/null @@ -1,312 +0,0 @@ -/** - * @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"); -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const DEFAULT_IGNORE_PATTERN = astUtils.COMMENTS_IGNORE_PATTERN, - WHITESPACE = /\s/g, - MAYBE_URL = /^\s*[^:/?#\s]+:\/\/[^?#]/; // TODO: Combine w/ max-len pattern? - -/* - * 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", - default: "" - }, - ignoreInlineComments: { - type: "boolean", - default: false - }, - ignoreConsecutiveComments: { - type: "boolean", - default: false - } - }, - additionalProperties: false -}; -const DEFAULTS = Object.keys(SCHEMA_BODY.properties).reduce( - (obj, current) => { - obj[current] = SCHEMA_BODY.properties[current].default; - return obj; - }, - {} -); - -/** - * 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) { - 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: { - type: "suggestion", - - docs: { - description: "enforce or disallow capitalization of the first letter of a comment", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/capitalized-comments" - }, - - fixable: "code", - - schema: [ - { enum: ["always", "never"] }, - { - oneOf: [ - SCHEMA_BODY, - { - type: "object", - properties: { - line: SCHEMA_BODY, - block: SCHEMA_BODY - }, - additionalProperties: false - } - ] - } - ], - - messages: { - unexpectedLowercaseComment: "Comments should not begin with a lowercase character.", - unexpectedUppercaseComment: "Comments should not begin with an uppercase character." - } - }, - - 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.getTokenBefore(comment, { includeComments: true }), - nextToken = sourceCode.getTokenAfter(comment, { includeComments: true }); - - 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.getTokenBefore(comment, { includeComments: true }); - - 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; - } - 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 messageId = capitalize === "always" - ? "unexpectedLowercaseComment" - : "unexpectedUppercaseComment"; - - context.report({ - node: null, // Intentionally using loc instead - loc: comment.loc, - messageId, - 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.filter(token => token.type !== "Shebang").forEach(processComment); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/class-methods-use-this.js b/tools/node_modules/eslint/lib/rules/class-methods-use-this.js deleted file mode 100644 index 0eb1da87f4c227..00000000000000 --- a/tools/node_modules/eslint/lib/rules/class-methods-use-this.js +++ /dev/null @@ -1,118 +0,0 @@ -/** - * @fileoverview Rule to enforce that all class methods use 'this'. - * @author Patrick Williams - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce that class methods utilize `this`", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/class-methods-use-this" - }, - - schema: [{ - type: "object", - properties: { - exceptMethods: { - type: "array", - items: { - type: "string" - } - } - }, - additionalProperties: false - }], - - messages: { - missingThis: "Expected 'this' to be used by class method '{{name}}'." - } - }, - create(context) { - const config = Object.assign({}, context.options[0]); - const exceptMethods = new Set(config.exceptMethods || []); - - const stack = []; - - /** - * Initializes the current context to false and pushes it onto the stack. - * These booleans represent whether 'this' has been used in the context. - * @returns {void} - * @private - */ - function enterFunction() { - stack.push(false); - } - - /** - * Check if the node is an instance method - * @param {ASTNode} node - node to check - * @returns {boolean} True if its an instance method - * @private - */ - function isInstanceMethod(node) { - return !node.static && node.kind !== "constructor" && node.type === "MethodDefinition"; - } - - /** - * Check if the node is an instance method not excluded by config - * @param {ASTNode} node - node to check - * @returns {boolean} True if it is an instance method, and not excluded by config - * @private - */ - function isIncludedInstanceMethod(node) { - return isInstanceMethod(node) && !exceptMethods.has(node.key.name); - } - - /** - * Checks if we are leaving a function that is a method, and reports if 'this' has not been used. - * Static methods and the constructor are exempt. - * Then pops the context off the stack. - * @param {ASTNode} node - A function node that was entered. - * @returns {void} - * @private - */ - function exitFunction(node) { - const methodUsesThis = stack.pop(); - - if (isIncludedInstanceMethod(node.parent) && !methodUsesThis) { - context.report({ - node, - messageId: "missingThis", - data: { - name: node.parent.key.name - } - }); - } - } - - /** - * Mark the current context as having used 'this'. - * @returns {void} - * @private - */ - function markThisUsed() { - if (stack.length) { - stack[stack.length - 1] = true; - } - } - - return { - FunctionDeclaration: enterFunction, - "FunctionDeclaration:exit": exitFunction, - FunctionExpression: enterFunction, - "FunctionExpression:exit": exitFunction, - ThisExpression: markThisUsed, - Super: markThisUsed - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/comma-dangle.js b/tools/node_modules/eslint/lib/rules/comma-dangle.js deleted file mode 100644 index 96799b30796349..00000000000000 --- a/tools/node_modules/eslint/lib/rules/comma-dangle.js +++ /dev/null @@ -1,345 +0,0 @@ -/** - * @fileoverview Rule to forbid or enforce dangling commas. - * @author Ian Christian Myers - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const lodash = require("lodash"); -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const DEFAULT_OPTIONS = Object.freeze({ - arrays: "never", - objects: "never", - imports: "never", - exports: "never", - functions: "ignore" -}); - -/** - * Checks whether or not a trailing comma is allowed in a given node. - * If the `lastItem` is `RestElement` or `RestProperty`, it disallows trailing commas. - * - * @param {ASTNode} lastItem - The node of the last element in the given node. - * @returns {boolean} `true` if a trailing comma is allowed. - */ -function isTrailingCommaAllowed(lastItem) { - return !( - lastItem.type === "RestElement" || - lastItem.type === "RestProperty" || - lastItem.type === "ExperimentalRestProperty" - ); -} - -/** - * Normalize option value. - * - * @param {string|Object|undefined} optionValue - The 1st option value to normalize. - * @returns {Object} The normalized option value. - */ -function normalizeOptions(optionValue) { - if (typeof optionValue === "string") { - return { - arrays: optionValue, - objects: optionValue, - imports: optionValue, - exports: optionValue, - - // For backward compatibility, always ignore functions. - functions: "ignore" - }; - } - if (typeof optionValue === "object" && optionValue !== null) { - return { - arrays: optionValue.arrays || DEFAULT_OPTIONS.arrays, - objects: optionValue.objects || DEFAULT_OPTIONS.objects, - imports: optionValue.imports || DEFAULT_OPTIONS.imports, - exports: optionValue.exports || DEFAULT_OPTIONS.exports, - functions: optionValue.functions || DEFAULT_OPTIONS.functions - }; - } - - return DEFAULT_OPTIONS; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "require or disallow trailing commas", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/comma-dangle" - }, - - fixable: "code", - - schema: { - definitions: { - value: { - enum: [ - "always-multiline", - "always", - "never", - "only-multiline" - ] - }, - valueWithIgnore: { - enum: [ - "always-multiline", - "always", - "ignore", - "never", - "only-multiline" - ] - } - }, - type: "array", - items: [ - { - oneOf: [ - { - $ref: "#/definitions/value" - }, - { - type: "object", - properties: { - arrays: { $ref: "#/definitions/valueWithIgnore" }, - objects: { $ref: "#/definitions/valueWithIgnore" }, - imports: { $ref: "#/definitions/valueWithIgnore" }, - exports: { $ref: "#/definitions/valueWithIgnore" }, - functions: { $ref: "#/definitions/valueWithIgnore" } - }, - additionalProperties: false - } - ] - } - ] - }, - - messages: { - unexpected: "Unexpected trailing comma.", - missing: "Missing trailing comma." - } - }, - - create(context) { - const options = normalizeOptions(context.options[0]); - const sourceCode = context.getSourceCode(); - - /** - * Gets the last item of the given node. - * @param {ASTNode} node - The node to get. - * @returns {ASTNode|null} The last node or null. - */ - function getLastItem(node) { - switch (node.type) { - case "ObjectExpression": - case "ObjectPattern": - return lodash.last(node.properties); - case "ArrayExpression": - case "ArrayPattern": - return lodash.last(node.elements); - case "ImportDeclaration": - case "ExportNamedDeclaration": - return lodash.last(node.specifiers); - case "FunctionDeclaration": - case "FunctionExpression": - case "ArrowFunctionExpression": - return lodash.last(node.params); - case "CallExpression": - case "NewExpression": - return lodash.last(node.arguments); - default: - return null; - } - } - - /** - * Gets the trailing comma token of the given node. - * If the trailing comma does not exist, this returns the token which is - * the insertion point of the trailing comma token. - * - * @param {ASTNode} node - The node to get. - * @param {ASTNode} lastItem - The last item of the node. - * @returns {Token} The trailing comma token or the insertion point. - */ - function getTrailingToken(node, lastItem) { - switch (node.type) { - case "ObjectExpression": - case "ArrayExpression": - case "CallExpression": - case "NewExpression": - return sourceCode.getLastToken(node, 1); - default: { - const nextToken = sourceCode.getTokenAfter(lastItem); - - if (astUtils.isCommaToken(nextToken)) { - return nextToken; - } - return sourceCode.getLastToken(lastItem); - } - } - } - - /** - * Checks whether or not a given node is multiline. - * This rule handles a given node as multiline when the closing parenthesis - * and the last element are not on the same line. - * - * @param {ASTNode} node - A node to check. - * @returns {boolean} `true` if the node is multiline. - */ - function isMultiline(node) { - const lastItem = getLastItem(node); - - if (!lastItem) { - return false; - } - - const penultimateToken = getTrailingToken(node, lastItem); - const lastToken = sourceCode.getTokenAfter(penultimateToken); - - return lastToken.loc.end.line !== penultimateToken.loc.end.line; - } - - /** - * Reports a trailing comma if it exists. - * - * @param {ASTNode} node - A node to check. Its type is one of - * ObjectExpression, ObjectPattern, ArrayExpression, ArrayPattern, - * ImportDeclaration, and ExportNamedDeclaration. - * @returns {void} - */ - function forbidTrailingComma(node) { - const lastItem = getLastItem(node); - - if (!lastItem || (node.type === "ImportDeclaration" && lastItem.type !== "ImportSpecifier")) { - return; - } - - const trailingToken = getTrailingToken(node, lastItem); - - if (astUtils.isCommaToken(trailingToken)) { - context.report({ - node: lastItem, - loc: trailingToken.loc.start, - messageId: "unexpected", - fix(fixer) { - return fixer.remove(trailingToken); - } - }); - } - } - - /** - * Reports the last element of a given node if it does not have a trailing - * comma. - * - * If a given node is `ArrayPattern` which has `RestElement`, the trailing - * comma is disallowed, so report if it exists. - * - * @param {ASTNode} node - A node to check. Its type is one of - * ObjectExpression, ObjectPattern, ArrayExpression, ArrayPattern, - * ImportDeclaration, and ExportNamedDeclaration. - * @returns {void} - */ - function forceTrailingComma(node) { - const lastItem = getLastItem(node); - - if (!lastItem || (node.type === "ImportDeclaration" && lastItem.type !== "ImportSpecifier")) { - return; - } - if (!isTrailingCommaAllowed(lastItem)) { - forbidTrailingComma(node); - return; - } - - const trailingToken = getTrailingToken(node, lastItem); - - if (trailingToken.value !== ",") { - context.report({ - node: lastItem, - loc: trailingToken.loc.end, - messageId: "missing", - fix(fixer) { - return fixer.insertTextAfter(trailingToken, ","); - } - }); - } - } - - /** - * If a given node is multiline, reports the last element of a given node - * when it does not have a trailing comma. - * Otherwise, reports a trailing comma if it exists. - * - * @param {ASTNode} node - A node to check. Its type is one of - * ObjectExpression, ObjectPattern, ArrayExpression, ArrayPattern, - * ImportDeclaration, and ExportNamedDeclaration. - * @returns {void} - */ - function forceTrailingCommaIfMultiline(node) { - if (isMultiline(node)) { - forceTrailingComma(node); - } else { - forbidTrailingComma(node); - } - } - - /** - * Only if a given node is not multiline, reports the last element of a given node - * when it does not have a trailing comma. - * Otherwise, reports a trailing comma if it exists. - * - * @param {ASTNode} node - A node to check. Its type is one of - * ObjectExpression, ObjectPattern, ArrayExpression, ArrayPattern, - * ImportDeclaration, and ExportNamedDeclaration. - * @returns {void} - */ - function allowTrailingCommaIfMultiline(node) { - if (!isMultiline(node)) { - forbidTrailingComma(node); - } - } - - const predicate = { - always: forceTrailingComma, - "always-multiline": forceTrailingCommaIfMultiline, - "only-multiline": allowTrailingCommaIfMultiline, - never: forbidTrailingComma, - ignore: lodash.noop - }; - - return { - ObjectExpression: predicate[options.objects], - ObjectPattern: predicate[options.objects], - - ArrayExpression: predicate[options.arrays], - ArrayPattern: predicate[options.arrays], - - ImportDeclaration: predicate[options.imports], - - ExportNamedDeclaration: predicate[options.exports], - - FunctionDeclaration: predicate[options.functions], - FunctionExpression: predicate[options.functions], - ArrowFunctionExpression: predicate[options.functions], - CallExpression: predicate[options.functions], - NewExpression: predicate[options.functions] - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/comma-spacing.js b/tools/node_modules/eslint/lib/rules/comma-spacing.js deleted file mode 100644 index a9f89676a4a3cd..00000000000000 --- a/tools/node_modules/eslint/lib/rules/comma-spacing.js +++ /dev/null @@ -1,195 +0,0 @@ -/** - * @fileoverview Comma spacing - validates spacing before and after comma - * @author Vignesh Anand aka vegetableman. - */ -"use strict"; - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce consistent spacing before and after commas", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/comma-spacing" - }, - - fixable: "whitespace", - - schema: [ - { - type: "object", - properties: { - before: { - type: "boolean", - default: false - }, - after: { - type: "boolean", - default: true - } - }, - additionalProperties: false - } - ], - - messages: { - missing: "A space is required {{loc}} ','.", - unexpected: "There should be no space {{loc}} ','." - } - }, - - create(context) { - - const sourceCode = context.getSourceCode(); - const tokensAndComments = sourceCode.tokensAndComments; - - const options = { - before: context.options[0] ? context.options[0].before : false, - after: context.options[0] ? context.options[0].after : true - }; - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - // list of comma tokens to ignore for the check of leading whitespace - const commaTokensToIgnore = []; - - /** - * Reports a spacing error with an appropriate message. - * @param {ASTNode} node The binary expression node to report. - * @param {string} loc Is the error "before" or "after" the comma? - * @param {ASTNode} otherNode The node at the left or right of `node` - * @returns {void} - * @private - */ - function report(node, loc, otherNode) { - context.report({ - node, - fix(fixer) { - if (options[loc]) { - if (loc === "before") { - return fixer.insertTextBefore(node, " "); - } - return fixer.insertTextAfter(node, " "); - - } - let start, end; - const newText = ""; - - if (loc === "before") { - start = otherNode.range[1]; - end = node.range[0]; - } else { - start = node.range[1]; - end = otherNode.range[0]; - } - - return fixer.replaceTextRange([start, end], newText); - - }, - messageId: options[loc] ? "missing" : "unexpected", - data: { - loc - } - }); - } - - /** - * Validates the spacing around a comma token. - * @param {Object} tokens - The tokens to be validated. - * @param {Token} tokens.comma The token representing the comma. - * @param {Token} [tokens.left] The last token before the comma. - * @param {Token} [tokens.right] The first token after the comma. - * @param {Token|ASTNode} reportItem The item to use when reporting an error. - * @returns {void} - * @private - */ - function validateCommaItemSpacing(tokens, reportItem) { - if (tokens.left && astUtils.isTokenOnSameLine(tokens.left, tokens.comma) && - (options.before !== sourceCode.isSpaceBetweenTokens(tokens.left, tokens.comma)) - ) { - report(reportItem, "before", tokens.left); - } - - if (tokens.right && astUtils.isClosingParenToken(tokens.right)) { - return; - } - - if (tokens.right && !options.after && tokens.right.type === "Line") { - return; - } - - if (tokens.right && astUtils.isTokenOnSameLine(tokens.comma, tokens.right) && - (options.after !== sourceCode.isSpaceBetweenTokens(tokens.comma, tokens.right)) - ) { - report(reportItem, "after", tokens.right); - } - } - - /** - * Adds null elements of the given ArrayExpression or ArrayPattern node to the ignore list. - * @param {ASTNode} node An ArrayExpression or ArrayPattern node. - * @returns {void} - */ - function addNullElementsToIgnoreList(node) { - let previousToken = sourceCode.getFirstToken(node); - - node.elements.forEach(element => { - let token; - - if (element === null) { - token = sourceCode.getTokenAfter(previousToken); - - if (astUtils.isCommaToken(token)) { - commaTokensToIgnore.push(token); - } - } else { - token = sourceCode.getTokenAfter(element); - } - - previousToken = token; - }); - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - "Program:exit"() { - tokensAndComments.forEach((token, i) => { - - if (!astUtils.isCommaToken(token)) { - return; - } - - if (token && token.type === "JSXText") { - return; - } - - const previousToken = tokensAndComments[i - 1]; - const nextToken = tokensAndComments[i + 1]; - - validateCommaItemSpacing({ - comma: token, - left: astUtils.isCommaToken(previousToken) || commaTokensToIgnore.indexOf(token) > -1 ? null : previousToken, - right: astUtils.isCommaToken(nextToken) ? null : nextToken - }, token); - }); - }, - ArrayExpression: addNullElementsToIgnoreList, - ArrayPattern: addNullElementsToIgnoreList - - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/comma-style.js b/tools/node_modules/eslint/lib/rules/comma-style.js deleted file mode 100644 index 78438a858dbb12..00000000000000 --- a/tools/node_modules/eslint/lib/rules/comma-style.js +++ /dev/null @@ -1,315 +0,0 @@ -/** - * @fileoverview Comma style - enforces comma styles of two types: last and first - * @author Vignesh Anand aka vegetableman - */ - -"use strict"; - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce consistent comma style", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/comma-style" - }, - - fixable: "code", - - schema: [ - { - enum: ["first", "last"] - }, - { - type: "object", - properties: { - exceptions: { - type: "object", - additionalProperties: { - type: "boolean" - } - } - }, - additionalProperties: false - } - ], - - messages: { - unexpectedLineBeforeAndAfterComma: "Bad line breaking before and after ','.", - expectedCommaFirst: "',' should be placed first.", - expectedCommaLast: "',' should be placed last." - } - }, - - create(context) { - const style = context.options[0] || "last", - sourceCode = context.getSourceCode(); - const exceptions = { - ArrayPattern: true, - ArrowFunctionExpression: true, - CallExpression: true, - FunctionDeclaration: true, - FunctionExpression: true, - ImportDeclaration: true, - ObjectPattern: true, - NewExpression: true - }; - - if (context.options.length === 2 && Object.prototype.hasOwnProperty.call(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]]; - } - } - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Modified text based on the style - * @param {string} styleType Style type - * @param {string} text Source code text - * @returns {string} modified text - * @private - */ - function getReplacedText(styleType, text) { - switch (styleType) { - case "between": - return `,${text.replace(astUtils.LINEBREAK_MATCHER, "")}`; - - case "first": - return `${text},`; - - case "last": - return `,${text}`; - - default: - return ""; - } - } - - /** - * Determines the fixer function for a given style. - * @param {string} styleType comma style - * @param {ASTNode} previousItemToken The token to check. - * @param {ASTNode} commaToken The token to check. - * @param {ASTNode} currentItemToken The token to check. - * @returns {Function} Fixer function - * @private - */ - function getFixerFunction(styleType, previousItemToken, commaToken, currentItemToken) { - const text = - sourceCode.text.slice(previousItemToken.range[1], commaToken.range[0]) + - sourceCode.text.slice(commaToken.range[1], currentItemToken.range[0]); - const range = [previousItemToken.range[1], currentItemToken.range[0]]; - - return function(fixer) { - return fixer.replaceTextRange(range, getReplacedText(styleType, text)); - }; - } - - /** - * Validates the spacing around single items in lists. - * @param {Token} previousItemToken The last token from the previous item. - * @param {Token} commaToken The token representing the comma. - * @param {Token} currentItemToken The first token of the current item. - * @param {Token} reportItem The item to use when reporting an error. - * @returns {void} - * @private - */ - function validateCommaItemSpacing(previousItemToken, commaToken, currentItemToken, reportItem) { - - // if single line - if (astUtils.isTokenOnSameLine(commaToken, currentItemToken) && - astUtils.isTokenOnSameLine(previousItemToken, commaToken)) { - - // do nothing. - - } else if (!astUtils.isTokenOnSameLine(commaToken, currentItemToken) && - !astUtils.isTokenOnSameLine(previousItemToken, commaToken)) { - - const comment = sourceCode.getCommentsAfter(commaToken)[0]; - const styleType = comment && comment.type === "Block" && astUtils.isTokenOnSameLine(commaToken, comment) - ? style - : "between"; - - // lone comma - context.report({ - node: reportItem, - loc: { - line: commaToken.loc.end.line, - column: commaToken.loc.start.column - }, - messageId: "unexpectedLineBeforeAndAfterComma", - fix: getFixerFunction(styleType, previousItemToken, commaToken, currentItemToken) - }); - - } else if (style === "first" && !astUtils.isTokenOnSameLine(commaToken, currentItemToken)) { - - context.report({ - node: reportItem, - messageId: "expectedCommaFirst", - fix: getFixerFunction(style, previousItemToken, commaToken, currentItemToken) - }); - - } else if (style === "last" && astUtils.isTokenOnSameLine(commaToken, currentItemToken)) { - - context.report({ - node: reportItem, - loc: { - line: commaToken.loc.end.line, - column: commaToken.loc.end.column - }, - messageId: "expectedCommaLast", - fix: getFixerFunction(style, previousItemToken, commaToken, currentItemToken) - }); - } - } - - /** - * Checks the comma placement with regards to a declaration/property/element - * @param {ASTNode} node The binary expression node to check - * @param {string} property The property of the node containing child nodes. - * @private - * @returns {void} - */ - function validateComma(node, property) { - const items = node[property], - arrayLiteral = (node.type === "ArrayExpression" || node.type === "ArrayPattern"); - - if (items.length > 1 || arrayLiteral) { - - // seed as opening [ - let previousItemToken = sourceCode.getFirstToken(node); - - items.forEach(item => { - const commaToken = item ? sourceCode.getTokenBefore(item) : previousItemToken, - currentItemToken = item ? sourceCode.getFirstToken(item) : sourceCode.getTokenAfter(commaToken), - reportItem = item || currentItemToken; - - /* - * This works by comparing three token locations: - * - previousItemToken is the last token of the previous item - * - commaToken is the location of the comma before the current item - * - currentItemToken is the first token of the current item - * - * These values get switched around if item is undefined. - * previousItemToken will refer to the last token not belonging - * to the current item, which could be a comma or an opening - * square bracket. currentItemToken could be a comma. - * - * All comparisons are done based on these tokens directly, so - * they are always valid regardless of an undefined item. - */ - if (astUtils.isCommaToken(commaToken)) { - validateCommaItemSpacing(previousItemToken, commaToken, - currentItemToken, reportItem); - } - - if (item) { - const tokenAfterItem = sourceCode.getTokenAfter(item, astUtils.isNotClosingParenToken); - - previousItemToken = tokenAfterItem - ? sourceCode.getTokenBefore(tokenAfterItem) - : sourceCode.ast.tokens[sourceCode.ast.tokens.length - 1]; - } - }); - - /* - * Special case for array literals that have empty last items, such - * as [ 1, 2, ]. These arrays only have two items show up in the - * AST, so we need to look at the token to verify that there's no - * dangling comma. - */ - if (arrayLiteral) { - - const lastToken = sourceCode.getLastToken(node), - nextToLastToken = sourceCode.getTokenBefore(lastToken); - - if (astUtils.isCommaToken(nextToLastToken)) { - validateCommaItemSpacing( - sourceCode.getTokenBefore(nextToLastToken), - nextToLastToken, - lastToken, - lastToken - ); - } - } - } - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - const nodes = {}; - - if (!exceptions.VariableDeclaration) { - nodes.VariableDeclaration = function(node) { - validateComma(node, "declarations"); - }; - } - if (!exceptions.ObjectExpression) { - nodes.ObjectExpression = function(node) { - 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"); - }; - } - if (!exceptions.NewExpression) { - nodes.NewExpression = function(node) { - validateComma(node, "arguments"); - }; - } - - return nodes; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/complexity.js b/tools/node_modules/eslint/lib/rules/complexity.js deleted file mode 100644 index 9f791e6de7c49a..00000000000000 --- a/tools/node_modules/eslint/lib/rules/complexity.js +++ /dev/null @@ -1,159 +0,0 @@ -/** - * @fileoverview Counts the cyclomatic complexity of each function of the script. See http://en.wikipedia.org/wiki/Cyclomatic_complexity. - * Counts the number of if, conditional, for, whilte, try, switch/case, - * @author Patrick Brosset - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const lodash = require("lodash"); - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce a maximum cyclomatic complexity allowed in a program", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/complexity" - }, - - schema: [ - { - oneOf: [ - { - type: "integer", - minimum: 0 - }, - { - type: "object", - properties: { - maximum: { - type: "integer", - minimum: 0, - default: 20 - }, - max: { - type: "integer", - minimum: 0, - default: 20 - } - }, - additionalProperties: false - } - ] - } - ], - - messages: { - complex: "{{name}} has a complexity of {{complexity}}." - } - }, - - create(context) { - const option = context.options[0]; - let THRESHOLD = 20; - - if (typeof option === "object") { - THRESHOLD = option.maximum || option.max; - } else if (typeof option === "number") { - THRESHOLD = option; - } - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - // Using a stack to store complexity (handling nested functions) - const fns = []; - - /** - * When parsing a new function, store it in our function stack - * @returns {void} - * @private - */ - function startFunction() { - fns.push(1); - } - - /** - * Evaluate the node at the end of function - * @param {ASTNode} node node to evaluate - * @returns {void} - * @private - */ - function endFunction(node) { - const name = lodash.upperFirst(astUtils.getFunctionNameWithKind(node)); - const complexity = fns.pop(); - - if (complexity > THRESHOLD) { - context.report({ - node, - messageId: "complex", - data: { name, complexity } - }); - } - } - - /** - * Increase the complexity of the function in context - * @returns {void} - * @private - */ - function increaseComplexity() { - if (fns.length) { - fns[fns.length - 1]++; - } - } - - /** - * Increase the switch complexity in context - * @param {ASTNode} node node to evaluate - * @returns {void} - * @private - */ - function increaseSwitchComplexity(node) { - - // Avoiding `default` - if (node.test) { - increaseComplexity(); - } - } - - //-------------------------------------------------------------------------- - // Public API - //-------------------------------------------------------------------------- - - return { - FunctionDeclaration: startFunction, - FunctionExpression: startFunction, - ArrowFunctionExpression: startFunction, - "FunctionDeclaration:exit": endFunction, - "FunctionExpression:exit": endFunction, - "ArrowFunctionExpression:exit": endFunction, - - CatchClause: increaseComplexity, - ConditionalExpression: increaseComplexity, - LogicalExpression: increaseComplexity, - ForStatement: increaseComplexity, - ForInStatement: increaseComplexity, - ForOfStatement: increaseComplexity, - IfStatement: increaseComplexity, - SwitchCase: increaseSwitchComplexity, - WhileStatement: increaseComplexity, - DoWhileStatement: increaseComplexity - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/computed-property-spacing.js b/tools/node_modules/eslint/lib/rules/computed-property-spacing.js deleted file mode 100644 index 188d863d0d0f83..00000000000000 --- a/tools/node_modules/eslint/lib/rules/computed-property-spacing.js +++ /dev/null @@ -1,187 +0,0 @@ -/** - * @fileoverview Disallows or enforces spaces inside computed properties. - * @author Jamund Ferguson - */ -"use strict"; - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce consistent spacing inside computed property brackets", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/computed-property-spacing" - }, - - fixable: "whitespace", - - schema: [ - { - enum: ["always", "never"] - } - ], - - messages: { - unexpectedSpaceBefore: "There should be no space before '{{tokenValue}}'.", - unexpectedSpaceAfter: "There should be no space after '{{tokenValue}}'.", - - missingSpaceBefore: "A space is required before '{{tokenValue}}'.", - missingSpaceAfter: "A space is required after '{{tokenValue}}'." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - const propertyNameMustBeSpaced = context.options[0] === "always"; // default is "never" - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Reports that there shouldn't be a space after the first token - * @param {ASTNode} node - The node to report in the event of an error. - * @param {Token} token - The token to use for the report. - * @param {Token} tokenAfter - The token after `token`. - * @returns {void} - */ - function reportNoBeginningSpace(node, token, tokenAfter) { - context.report({ - node, - loc: token.loc.start, - messageId: "unexpectedSpaceAfter", - data: { - tokenValue: token.value - }, - fix(fixer) { - return fixer.removeRange([token.range[1], tokenAfter.range[0]]); - } - }); - } - - /** - * Reports that there shouldn't be a space before the last token - * @param {ASTNode} node - The node to report in the event of an error. - * @param {Token} token - The token to use for the report. - * @param {Token} tokenBefore - The token before `token`. - * @returns {void} - */ - function reportNoEndingSpace(node, token, tokenBefore) { - context.report({ - node, - loc: token.loc.start, - messageId: "unexpectedSpaceBefore", - data: { - tokenValue: token.value - }, - fix(fixer) { - return fixer.removeRange([tokenBefore.range[1], token.range[0]]); - } - }); - } - - /** - * Reports that there should be a space after the first token - * @param {ASTNode} node - The node to report in the event of an error. - * @param {Token} token - The token to use for the report. - * @returns {void} - */ - function reportRequiredBeginningSpace(node, token) { - context.report({ - node, - loc: token.loc.start, - messageId: "missingSpaceAfter", - data: { - tokenValue: token.value - }, - fix(fixer) { - return fixer.insertTextAfter(token, " "); - } - }); - } - - /** - * Reports that there should be a space before the last token - * @param {ASTNode} node - The node to report in the event of an error. - * @param {Token} token - The token to use for the report. - * @returns {void} - */ - function reportRequiredEndingSpace(node, token) { - context.report({ - node, - loc: token.loc.start, - messageId: "missingSpaceBefore", - data: { - tokenValue: token.value - }, - fix(fixer) { - return fixer.insertTextBefore(token, " "); - } - }); - } - - /** - * Returns a function that checks the spacing of a node on the property name - * that was passed in. - * @param {string} propertyName The property on the node to check for spacing - * @returns {Function} A function that will check spacing on a node - */ - function checkSpacing(propertyName) { - return function(node) { - if (!node.computed) { - return; - } - - const property = node[propertyName]; - - const before = sourceCode.getTokenBefore(property), - first = sourceCode.getFirstToken(property), - last = sourceCode.getLastToken(property), - after = sourceCode.getTokenAfter(property); - - if (astUtils.isTokenOnSameLine(before, first)) { - if (propertyNameMustBeSpaced) { - if (!sourceCode.isSpaceBetweenTokens(before, first) && astUtils.isTokenOnSameLine(before, first)) { - reportRequiredBeginningSpace(node, before); - } - } else { - if (sourceCode.isSpaceBetweenTokens(before, first)) { - reportNoBeginningSpace(node, before, first); - } - } - } - - if (astUtils.isTokenOnSameLine(last, after)) { - if (propertyNameMustBeSpaced) { - if (!sourceCode.isSpaceBetweenTokens(last, after) && astUtils.isTokenOnSameLine(last, after)) { - reportRequiredEndingSpace(node, after); - } - } else { - if (sourceCode.isSpaceBetweenTokens(last, after)) { - reportNoEndingSpace(node, after, last); - } - } - } - }; - } - - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - Property: checkSpacing("key"), - MemberExpression: checkSpacing("property") - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/consistent-return.js b/tools/node_modules/eslint/lib/rules/consistent-return.js deleted file mode 100644 index 68f9f9d8fbcad4..00000000000000 --- a/tools/node_modules/eslint/lib/rules/consistent-return.js +++ /dev/null @@ -1,197 +0,0 @@ -/** - * @fileoverview Rule to flag consistent return values - * @author Nicholas C. Zakas - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const lodash = require("lodash"); - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks whether or not a given node is an `Identifier` node which was named a given name. - * @param {ASTNode} node - A node to check. - * @param {string} name - An expected name of the node. - * @returns {boolean} `true` if the node is an `Identifier` node which was named as expected. - */ -function isIdentifier(node, name) { - return node.type === "Identifier" && node.name === name; -} - -/** - * Checks whether or not a given code path segment is unreachable. - * @param {CodePathSegment} segment - A CodePathSegment to check. - * @returns {boolean} `true` if the segment is unreachable. - */ -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 -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require `return` statements to either always or never specify values", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/consistent-return" - }, - - schema: [{ - type: "object", - properties: { - treatUndefinedAsUnspecified: { - type: "boolean", - default: false - } - }, - additionalProperties: false - }], - - messages: { - missingReturn: "Expected to return a value at the end of {{name}}.", - missingReturnValue: "{{name}} expected a return value.", - unexpectedReturnValue: "{{name}} expected no return value." - } - }, - - create(context) { - const options = context.options[0] || {}; - const treatUndefinedAsUnspecified = options.treatUndefinedAsUnspecified === true; - let funcInfo = null; - - /** - * Checks whether of not the implicit returning is consistent if the last - * code path segment is reachable. - * - * @param {ASTNode} node - A program/function node to check. - * @returns {void} - */ - function checkLastSegment(node) { - let loc, name; - - /* - * Skip if it expected no return value or unreachable. - * When unreachable, all paths are returned or thrown. - */ - if (!funcInfo.hasReturnValue || - funcInfo.codePath.currentSegments.every(isUnreachable) || - astUtils.isES5Constructor(node) || - isClassConstructor(node) - ) { - return; - } - - // Adjust a location and a message. - if (node.type === "Program") { - - // The head of program. - loc = { line: 1, column: 0 }; - name = "program"; - } else if (node.type === "ArrowFunctionExpression") { - - // `=>` token - loc = context.getSourceCode().getTokenBefore(node.body, astUtils.isArrowToken).loc.start; - } else if ( - node.parent.type === "MethodDefinition" || - (node.parent.type === "Property" && node.parent.method) - ) { - - // Method name. - loc = node.parent.key.loc.start; - } else { - - // Function name or `function` keyword. - loc = (node.id || node).loc.start; - } - - if (!name) { - name = astUtils.getFunctionNameWithKind(node); - } - - // Reports. - context.report({ - node, - loc, - messageId: "missingReturn", - data: { name } - }); - } - - return { - - // Initializes/Disposes state of each code path. - onCodePathStart(codePath, node) { - funcInfo = { - upper: funcInfo, - codePath, - hasReturn: false, - hasReturnValue: false, - messageId: "", - node - }; - }, - onCodePathEnd() { - funcInfo = funcInfo.upper; - }, - - // Reports a given return statement if it's inconsistent. - ReturnStatement(node) { - const argument = node.argument; - let hasReturnValue = Boolean(argument); - - if (treatUndefinedAsUnspecified && hasReturnValue) { - hasReturnValue = !isIdentifier(argument, "undefined") && argument.operator !== "void"; - } - - if (!funcInfo.hasReturn) { - funcInfo.hasReturn = true; - funcInfo.hasReturnValue = hasReturnValue; - funcInfo.messageId = hasReturnValue ? "missingReturnValue" : "unexpectedReturnValue"; - funcInfo.data = { - name: funcInfo.node.type === "Program" - ? "Program" - : lodash.upperFirst(astUtils.getFunctionNameWithKind(funcInfo.node)) - }; - } else if (funcInfo.hasReturnValue !== hasReturnValue) { - context.report({ - node, - messageId: funcInfo.messageId, - data: funcInfo.data - }); - } - }, - - // Reports a given program/function if the implicit returning is not consistent. - "Program:exit": checkLastSegment, - "FunctionDeclaration:exit": checkLastSegment, - "FunctionExpression:exit": checkLastSegment, - "ArrowFunctionExpression:exit": checkLastSegment - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/consistent-this.js b/tools/node_modules/eslint/lib/rules/consistent-this.js deleted file mode 100644 index 4bdcdfdc10e8f0..00000000000000 --- a/tools/node_modules/eslint/lib/rules/consistent-this.js +++ /dev/null @@ -1,151 +0,0 @@ -/** - * @fileoverview Rule to enforce consistent naming of "this" context variables - * @author Raphael Pigulla - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce consistent naming when capturing the current execution context", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/consistent-this" - }, - - schema: { - type: "array", - items: { - type: "string", - minLength: 1 - }, - uniqueItems: true - }, - - messages: { - aliasNotAssignedToThis: "Designated alias '{{name}}' is not assigned to 'this'.", - unexpectedAlias: "Unexpected alias '{{name}}' for 'this'." - } - }, - - create(context) { - let aliases = []; - - if (context.options.length === 0) { - aliases.push("that"); - } else { - aliases = context.options; - } - - /** - * Reports that a variable declarator or assignment expression is assigning - * a non-'this' value to the specified alias. - * @param {ASTNode} node - The assigning node. - * @param {string} name - the name of the alias that was incorrectly used. - * @returns {void} - */ - function reportBadAssignment(node, name) { - context.report({ node, messageId: "aliasNotAssignedToThis", data: { name } }); - } - - /** - * Checks that an assignment to an identifier only assigns 'this' to the - * appropriate alias, and the alias is only assigned to 'this'. - * @param {ASTNode} node - The assigning node. - * @param {Identifier} name - The name of the variable assigned to. - * @param {Expression} value - The value of the assignment. - * @returns {void} - */ - function checkAssignment(node, name, value) { - const isThis = value.type === "ThisExpression"; - - if (aliases.indexOf(name) !== -1) { - if (!isThis || node.operator && node.operator !== "=") { - reportBadAssignment(node, name); - } - } else if (isThis) { - context.report({ node, messageId: "unexpectedAlias", data: { name } }); - } - } - - /** - * Ensures that a variable declaration of the alias in a program or function - * is assigned to the correct value. - * @param {string} alias alias the check the assignment of. - * @param {Object} scope scope of the current code we are checking. - * @private - * @returns {void} - */ - function checkWasAssigned(alias, scope) { - const variable = scope.set.get(alias); - - if (!variable) { - return; - } - - 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(reference => { - const write = reference.writeExpr; - - return ( - reference.from === scope && - write && write.type === "ThisExpression" && - write.parent.operator === "=" - ); - })) { - variable.defs.map(def => def.node).forEach(node => { - reportBadAssignment(node, alias); - }); - } - } - - /** - * Check each alias to ensure that is was assinged to the correct value. - * @returns {void} - */ - function ensureWasAssigned() { - const scope = context.getScope(); - - aliases.forEach(alias => { - checkWasAssigned(alias, scope); - }); - } - - return { - "Program:exit": ensureWasAssigned, - "FunctionExpression:exit": ensureWasAssigned, - "FunctionDeclaration:exit": ensureWasAssigned, - - VariableDeclarator(node) { - const id = node.id; - const isDestructuring = - id.type === "ArrayPattern" || id.type === "ObjectPattern"; - - if (node.init !== null && !isDestructuring) { - checkAssignment(node, id.name, node.init); - } - }, - - AssignmentExpression(node) { - if (node.left.type === "Identifier") { - checkAssignment(node, node.left.name, node.right); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/constructor-super.js b/tools/node_modules/eslint/lib/rules/constructor-super.js deleted file mode 100644 index e4cdb099b3bf52..00000000000000 --- a/tools/node_modules/eslint/lib/rules/constructor-super.js +++ /dev/null @@ -1,397 +0,0 @@ -/** - * @fileoverview A rule to verify `super()` callings in constructor. - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks whether a given code path segment is reachable or not. - * - * @param {CodePathSegment} segment - A code path segment to check. - * @returns {boolean} `true` if the segment is reachable. - */ -function isReachable(segment) { - return segment.reachable; -} - -/** - * Checks whether or not a given node is a constructor. - * @param {ASTNode} node - A node to check. This node type is one of - * `Program`, `FunctionDeclaration`, `FunctionExpression`, and - * `ArrowFunctionExpression`. - * @returns {boolean} `true` if the node is a constructor. - */ -function isConstructorFunction(node) { - return ( - node.type === "FunctionExpression" && - node.parent.type === "MethodDefinition" && - node.parent.kind === "constructor" - ); -} - -/** - * Checks whether a given node can be a constructor or not. - * - * @param {ASTNode} node - A node to check. - * @returns {boolean} `true` if the node can be a constructor. - */ -function isPossibleConstructor(node) { - if (!node) { - return false; - } - - switch (node.type) { - case "ClassExpression": - case "FunctionExpression": - case "ThisExpression": - case "MemberExpression": - case "CallExpression": - case "NewExpression": - case "YieldExpression": - case "TaggedTemplateExpression": - case "MetaProperty": - return true; - - case "Identifier": - return node.name !== "undefined"; - - case "AssignmentExpression": - return isPossibleConstructor(node.right); - - case "LogicalExpression": - return ( - isPossibleConstructor(node.left) || - isPossibleConstructor(node.right) - ); - - case "ConditionalExpression": - return ( - isPossibleConstructor(node.alternate) || - isPossibleConstructor(node.consequent) - ); - - case "SequenceExpression": { - const lastExpression = node.expressions[node.expressions.length - 1]; - - return isPossibleConstructor(lastExpression); - } - - default: - return false; - } -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "require `super()` calls in constructors", - category: "ECMAScript 6", - recommended: true, - url: "https://eslint.org/docs/rules/constructor-super" - }, - - schema: [], - - messages: { - missingSome: "Lacked a call of 'super()' in some code paths.", - missingAll: "Expected to call 'super()'.", - - duplicate: "Unexpected duplicate 'super()'.", - badSuper: "Unexpected 'super()' because 'super' is not a constructor.", - unexpected: "Unexpected 'super()'." - } - }, - - create(context) { - - /* - * {{hasExtends: boolean, scope: Scope, codePath: CodePath}[]} - * Information for each constructor. - * - upper: Information of the upper constructor. - * - hasExtends: A flag which shows whether own class has a valid `extends` - * part. - * - scope: The scope of own class. - * - codePath: The code path object of the constructor. - */ - let funcInfo = null; - - /* - * {Map} - * Information for each code path segment. - * - calledInSomePaths: A flag of be called `super()` in some code paths. - * - calledInEveryPaths: A flag of be called `super()` in all code paths. - * - validNodes: - */ - let segInfoMap = Object.create(null); - - /** - * Gets the flag which shows `super()` is called in some paths. - * @param {CodePathSegment} segment - A code path segment to get. - * @returns {boolean} The flag which shows `super()` is called in some paths - */ - function isCalledInSomePath(segment) { - return segment.reachable && segInfoMap[segment.id].calledInSomePaths; - } - - /** - * Gets the flag which shows `super()` is called in all paths. - * @param {CodePathSegment} segment - A code path segment to get. - * @returns {boolean} The flag which shows `super()` is called in all paths. - */ - function isCalledInEveryPath(segment) { - - /* - * If specific segment is the looped segment of the current segment, - * skip the segment. - * If not skipped, this never becomes true after a loop. - */ - if (segment.nextSegments.length === 1 && - segment.nextSegments[0].isLoopedPrevSegment(segment) - ) { - return true; - } - return segment.reachable && segInfoMap[segment.id].calledInEveryPaths; - } - - return { - - /** - * Stacks a constructor information. - * @param {CodePath} codePath - A code path which was started. - * @param {ASTNode} node - The current node. - * @returns {void} - */ - onCodePathStart(codePath, node) { - if (isConstructorFunction(node)) { - - // Class > ClassBody > MethodDefinition > FunctionExpression - const classNode = node.parent.parent.parent; - const superClass = classNode.superClass; - - funcInfo = { - upper: funcInfo, - isConstructor: true, - hasExtends: Boolean(superClass), - superIsConstructor: isPossibleConstructor(superClass), - codePath - }; - } else { - funcInfo = { - upper: funcInfo, - isConstructor: false, - hasExtends: false, - superIsConstructor: false, - codePath - }; - } - }, - - /** - * Pops a constructor information. - * And reports if `super()` lacked. - * @param {CodePath} codePath - A code path which was ended. - * @param {ASTNode} node - The current node. - * @returns {void} - */ - onCodePathEnd(codePath, node) { - const hasExtends = funcInfo.hasExtends; - - // Pop. - funcInfo = funcInfo.upper; - - if (!hasExtends) { - return; - } - - // Reports if `super()` lacked. - const segments = codePath.returnedSegments; - const calledInEveryPaths = segments.every(isCalledInEveryPath); - const calledInSomePaths = segments.some(isCalledInSomePath); - - if (!calledInEveryPaths) { - context.report({ - messageId: calledInSomePaths - ? "missingSome" - : "missingAll", - node: node.parent - }); - } - }, - - /** - * Initialize information of a given code path segment. - * @param {CodePathSegment} segment - A code path segment to initialize. - * @returns {void} - */ - onCodePathSegmentStart(segment) { - if (!(funcInfo && funcInfo.isConstructor && funcInfo.hasExtends)) { - return; - } - - // Initialize info. - const info = segInfoMap[segment.id] = { - calledInSomePaths: false, - calledInEveryPaths: false, - validNodes: [] - }; - - // When there are previous segments, aggregates these. - const prevSegments = segment.prevSegments; - - if (prevSegments.length > 0) { - info.calledInSomePaths = prevSegments.some(isCalledInSomePath); - info.calledInEveryPaths = prevSegments.every(isCalledInEveryPath); - } - }, - - /** - * Update information of the code path segment when a code path was - * looped. - * @param {CodePathSegment} fromSegment - The code path segment of the - * end of a loop. - * @param {CodePathSegment} toSegment - A code path segment of the head - * of a loop. - * @returns {void} - */ - onCodePathSegmentLoop(fromSegment, toSegment) { - if (!(funcInfo && funcInfo.isConstructor && funcInfo.hasExtends)) { - return; - } - - // Update information inside of the loop. - const isRealLoop = toSegment.prevSegments.length >= 2; - - funcInfo.codePath.traverseSegments( - { first: toSegment, last: fromSegment }, - segment => { - const info = segInfoMap[segment.id]; - const prevSegments = segment.prevSegments; - - // Updates flags. - info.calledInSomePaths = prevSegments.some(isCalledInSomePath); - info.calledInEveryPaths = prevSegments.every(isCalledInEveryPath); - - // If flags become true anew, reports the valid nodes. - if (info.calledInSomePaths || isRealLoop) { - const nodes = info.validNodes; - - info.validNodes = []; - - for (let i = 0; i < nodes.length; ++i) { - const node = nodes[i]; - - context.report({ - messageId: "duplicate", - node - }); - } - } - } - ); - }, - - /** - * Checks for a call of `super()`. - * @param {ASTNode} node - A CallExpression node to check. - * @returns {void} - */ - "CallExpression:exit"(node) { - if (!(funcInfo && funcInfo.isConstructor)) { - return; - } - - // Skips except `super()`. - if (node.callee.type !== "Super") { - return; - } - - // Reports if needed. - if (funcInfo.hasExtends) { - const segments = funcInfo.codePath.currentSegments; - let duplicate = false; - let info = null; - - for (let i = 0; i < segments.length; ++i) { - const segment = segments[i]; - - if (segment.reachable) { - info = segInfoMap[segment.id]; - - duplicate = duplicate || info.calledInSomePaths; - info.calledInSomePaths = info.calledInEveryPaths = true; - } - } - - if (info) { - if (duplicate) { - context.report({ - messageId: "duplicate", - node - }); - } else if (!funcInfo.superIsConstructor) { - context.report({ - messageId: "badSuper", - node - }); - } else { - info.validNodes.push(node); - } - } - } else if (funcInfo.codePath.currentSegments.some(isReachable)) { - context.report({ - messageId: "unexpected", - node - }); - } - }, - - /** - * Set the mark to the returned path as `super()` was called. - * @param {ASTNode} node - A ReturnStatement node to check. - * @returns {void} - */ - ReturnStatement(node) { - if (!(funcInfo && funcInfo.isConstructor && funcInfo.hasExtends)) { - return; - } - - // Skips if no argument. - if (!node.argument) { - return; - } - - // Returning argument is a substitute of 'super()'. - const segments = funcInfo.codePath.currentSegments; - - for (let i = 0; i < segments.length; ++i) { - const segment = segments[i]; - - if (segment.reachable) { - const info = segInfoMap[segment.id]; - - info.calledInSomePaths = info.calledInEveryPaths = true; - } - } - }, - - /** - * Resets state. - * @returns {void} - */ - "Program:exit"() { - segInfoMap = Object.create(null); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/curly.js b/tools/node_modules/eslint/lib/rules/curly.js deleted file mode 100644 index ee12da71352372..00000000000000 --- a/tools/node_modules/eslint/lib/rules/curly.js +++ /dev/null @@ -1,382 +0,0 @@ -/** - * @fileoverview Rule to flag statements without curly braces - * @author Nicholas C. Zakas - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce consistent brace style for all control statements", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/curly" - }, - - schema: { - anyOf: [ - { - type: "array", - items: [ - { - enum: ["all"] - } - ], - minItems: 0, - maxItems: 1 - }, - { - type: "array", - items: [ - { - enum: ["multi", "multi-line", "multi-or-nest"] - }, - { - enum: ["consistent"] - } - ], - minItems: 0, - maxItems: 2 - } - ] - }, - - fixable: "code", - - messages: { - missingCurlyAfter: "Expected { after '{{name}}'.", - missingCurlyAfterCondition: "Expected { after '{{name}}' condition.", - unexpectedCurlyAfter: "Unnecessary { after '{{name}}'.", - unexpectedCurlyAfterCondition: "Unnecessary { after '{{name}}' condition." - } - }, - - create(context) { - - const multiOnly = (context.options[0] === "multi"); - const multiLine = (context.options[0] === "multi-line"); - const multiOrNest = (context.options[0] === "multi-or-nest"); - const consistent = (context.options[1] === "consistent"); - - const sourceCode = context.getSourceCode(); - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Determines if a given node is a one-liner that's on the same line as it's preceding code. - * @param {ASTNode} node The node to check. - * @returns {boolean} True if the node is a one-liner that's on the same line as it's preceding code. - * @private - */ - function isCollapsedOneLiner(node) { - const before = sourceCode.getTokenBefore(node); - const last = sourceCode.getLastToken(node); - const lastExcludingSemicolon = astUtils.isSemicolonToken(last) ? sourceCode.getTokenBefore(last) : last; - - return before.loc.start.line === lastExcludingSemicolon.loc.end.line; - } - - /** - * Determines if a given node is a one-liner. - * @param {ASTNode} node The node to check. - * @returns {boolean} True if the node is a one-liner. - * @private - */ - function isOneLiner(node) { - const first = sourceCode.getFirstToken(node), - last = sourceCode.getLastToken(node); - - return first.loc.start.line === last.loc.end.line; - } - - /** - * Checks if the given token is an `else` token or not. - * - * @param {Token} token - The token to check. - * @returns {boolean} `true` if the token is an `else` token. - */ - function isElseKeywordToken(token) { - return token.value === "else" && token.type === "Keyword"; - } - - /** - * Gets the `else` keyword token of a given `IfStatement` node. - * @param {ASTNode} node - A `IfStatement` node to get. - * @returns {Token} The `else` keyword token. - */ - function getElseKeyword(node) { - return node.alternate && sourceCode.getFirstTokenBetween(node.consequent, node.alternate, isElseKeywordToken); - } - - /** - * Checks a given IfStatement node requires braces of the consequent chunk. - * This returns `true` when below: - * - * 1. The given node has the `alternate` node. - * 2. There is a `IfStatement` which doesn't have `alternate` node in the - * trailing statement chain of the `consequent` node. - * - * @param {ASTNode} node - A IfStatement node to check. - * @returns {boolean} `true` if the node requires braces of the consequent chunk. - */ - function requiresBraceOfConsequent(node) { - if (node.alternate && node.consequent.type === "BlockStatement") { - if (node.consequent.body.length >= 2) { - return true; - } - - for ( - let currentNode = node.consequent.body[0]; - currentNode; - currentNode = astUtils.getTrailingStatement(currentNode) - ) { - if (currentNode.type === "IfStatement" && !currentNode.alternate) { - return true; - } - } - } - - return false; - } - - /** - * Determines if a semicolon needs to be inserted after removing a set of curly brackets, in order to avoid a SyntaxError. - * @param {Token} closingBracket The } token - * @returns {boolean} `true` if a semicolon needs to be inserted after the last statement in the block. - */ - function needsSemicolon(closingBracket) { - const tokenBefore = sourceCode.getTokenBefore(closingBracket); - const tokenAfter = sourceCode.getTokenAfter(closingBracket); - const lastBlockNode = sourceCode.getNodeByRangeIndex(tokenBefore.range[0]); - - if (astUtils.isSemicolonToken(tokenBefore)) { - - // If the last statement already has a semicolon, don't add another one. - return false; - } - - if (!tokenAfter) { - - // If there are no statements after this block, there is no need to add a semicolon. - return false; - } - - if (lastBlockNode.type === "BlockStatement" && lastBlockNode.parent.type !== "FunctionExpression" && lastBlockNode.parent.type !== "ArrowFunctionExpression") { - - /* - * If the last node surrounded by curly brackets is a BlockStatement (other than a FunctionExpression or an ArrowFunctionExpression), - * don't insert a semicolon. Otherwise, the semicolon would be parsed as a separate statement, which would cause - * a SyntaxError if it was followed by `else`. - */ - return false; - } - - if (tokenBefore.loc.end.line === tokenAfter.loc.start.line) { - - // If the next token is on the same line, insert a semicolon. - return true; - } - - if (/^[([/`+-]/.test(tokenAfter.value)) { - - // If the next token starts with a character that would disrupt ASI, insert a semicolon. - return true; - } - - if (tokenBefore.type === "Punctuator" && (tokenBefore.value === "++" || tokenBefore.value === "--")) { - - // If the last token is ++ or --, insert a semicolon to avoid disrupting ASI. - return true; - } - - // Otherwise, do not insert a semicolon. - return false; - } - - /** - * Prepares to check the body of a node to see if it's a block statement. - * @param {ASTNode} node The node to report if there's a problem. - * @param {ASTNode} body The body node to check for blocks. - * @param {string} name The name to report if there's a problem. - * @param {{ condition: boolean }} opts Options to pass to the report functions - * @returns {Object} a prepared check object, with "actual", "expected", "check" properties. - * "actual" will be `true` or `false` whether the body is already a block statement. - * "expected" will be `true` or `false` if the body should be a block statement or not, or - * `null` if it doesn't matter, depending on the rule options. It can be modified to change - * the final behavior of "check". - * "check" will be a function reporting appropriate problems depending on the other - * properties. - */ - function prepareCheck(node, body, name, opts) { - const hasBlock = (body.type === "BlockStatement"); - let expected = null; - - if (node.type === "IfStatement" && node.consequent === body && requiresBraceOfConsequent(node)) { - expected = true; - } else if (multiOnly) { - if (hasBlock && body.body.length === 1) { - expected = false; - } - } else if (multiLine) { - if (!isCollapsedOneLiner(body)) { - expected = true; - } - } else if (multiOrNest) { - if (hasBlock && body.body.length === 1 && isOneLiner(body.body[0])) { - const leadingComments = sourceCode.getCommentsBefore(body.body[0]); - - expected = leadingComments.length > 0; - } else if (!isOneLiner(body)) { - expected = true; - } - } else { - expected = true; - } - - return { - actual: hasBlock, - expected, - check() { - if (this.expected !== null && this.expected !== this.actual) { - if (this.expected) { - context.report({ - node, - loc: (name !== "else" ? node : getElseKeyword(node)).loc.start, - messageId: opts && opts.condition ? "missingCurlyAfterCondition" : "missingCurlyAfter", - data: { - name - }, - fix: fixer => fixer.replaceText(body, `{${sourceCode.getText(body)}}`) - }); - } else { - context.report({ - node, - loc: (name !== "else" ? node : getElseKeyword(node)).loc.start, - messageId: opts && opts.condition ? "unexpectedCurlyAfterCondition" : "unexpectedCurlyAfter", - data: { - name - }, - fix(fixer) { - - /* - * `do while` expressions sometimes need a space to be inserted after `do`. - * e.g. `do{foo()} while (bar)` should be corrected to `do foo() while (bar)` - */ - const needsPrecedingSpace = node.type === "DoWhileStatement" && - sourceCode.getTokenBefore(body).range[1] === body.range[0] && - !astUtils.canTokensBeAdjacent("do", sourceCode.getFirstToken(body, { skip: 1 })); - - const openingBracket = sourceCode.getFirstToken(body); - const closingBracket = sourceCode.getLastToken(body); - const lastTokenInBlock = sourceCode.getTokenBefore(closingBracket); - - if (needsSemicolon(closingBracket)) { - - /* - * If removing braces would cause a SyntaxError due to multiple statements on the same line (or - * change the semantics of the code due to ASI), don't perform a fix. - */ - return null; - } - - const resultingBodyText = sourceCode.getText().slice(openingBracket.range[1], lastTokenInBlock.range[0]) + - sourceCode.getText(lastTokenInBlock) + - sourceCode.getText().slice(lastTokenInBlock.range[1], closingBracket.range[0]); - - return fixer.replaceText(body, (needsPrecedingSpace ? " " : "") + resultingBodyText); - } - }); - } - } - } - }; - } - - /** - * Prepares to check the bodies of a "if", "else if" and "else" chain. - * @param {ASTNode} node The first IfStatement node of the chain. - * @returns {Object[]} prepared checks for each body of the chain. See `prepareCheck` for more - * information. - */ - function prepareIfChecks(node) { - const preparedChecks = []; - - for (let currentNode = node; currentNode; currentNode = currentNode.alternate) { - preparedChecks.push(prepareCheck(currentNode, currentNode.consequent, "if", { condition: true })); - if (currentNode.alternate && currentNode.alternate.type !== "IfStatement") { - preparedChecks.push(prepareCheck(currentNode, currentNode.alternate, "else")); - break; - } - } - - if (consistent) { - - /* - * If any node should have or already have braces, make sure they - * all have braces. - * If all nodes shouldn't have braces, make sure they don't. - */ - const expected = preparedChecks.some(preparedCheck => { - if (preparedCheck.expected !== null) { - return preparedCheck.expected; - } - return preparedCheck.actual; - }); - - preparedChecks.forEach(preparedCheck => { - preparedCheck.expected = expected; - }); - } - - return preparedChecks; - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - IfStatement(node) { - if (node.parent.type !== "IfStatement") { - prepareIfChecks(node).forEach(preparedCheck => { - preparedCheck.check(); - }); - } - }, - - WhileStatement(node) { - prepareCheck(node, node.body, "while", { condition: true }).check(); - }, - - DoWhileStatement(node) { - prepareCheck(node, node.body, "do").check(); - }, - - ForStatement(node) { - prepareCheck(node, node.body, "for", { condition: true }).check(); - }, - - ForInStatement(node) { - prepareCheck(node, node.body, "for-in").check(); - }, - - ForOfStatement(node) { - prepareCheck(node, node.body, "for-of").check(); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/default-case.js b/tools/node_modules/eslint/lib/rules/default-case.js deleted file mode 100644 index 3061265ed8ec4f..00000000000000 --- a/tools/node_modules/eslint/lib/rules/default-case.js +++ /dev/null @@ -1,97 +0,0 @@ -/** - * @fileoverview require default case in switch statements - * @author Aliaksei Shytkin - */ -"use strict"; - -const DEFAULT_COMMENT_PATTERN = /^no default$/i; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require `default` cases in `switch` statements", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/default-case" - }, - - schema: [{ - type: "object", - properties: { - commentPattern: { - type: "string" - } - }, - additionalProperties: false - }], - - messages: { - missingDefaultCase: "Expected a default case." - } - }, - - create(context) { - const options = context.options[0] || {}; - const commentPattern = options.commentPattern - ? new RegExp(options.commentPattern) - : DEFAULT_COMMENT_PATTERN; - - const sourceCode = context.getSourceCode(); - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Shortcut to get last element of array - * @param {*[]} collection Array - * @returns {*} Last element - */ - function last(collection) { - return collection[collection.length - 1]; - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - - SwitchStatement(node) { - - if (!node.cases.length) { - - /* - * skip check of empty switch because there is no easy way - * to extract comments inside it now - */ - return; - } - - const hasDefault = node.cases.some(v => v.test === null); - - if (!hasDefault) { - - let comment; - - const lastCase = last(node.cases); - const comments = sourceCode.getCommentsAfter(lastCase); - - if (comments.length) { - comment = last(comments); - } - - if (!comment || !commentPattern.test(comment.value.trim())) { - context.report({ node, messageId: "missingDefaultCase" }); - } - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/dot-location.js b/tools/node_modules/eslint/lib/rules/dot-location.js deleted file mode 100644 index 0eefec2eaffee0..00000000000000 --- a/tools/node_modules/eslint/lib/rules/dot-location.js +++ /dev/null @@ -1,96 +0,0 @@ -/** - * @fileoverview Validates newlines before and after dots - * @author Greg Cochard - */ - -"use strict"; - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce consistent newlines before and after dots", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/dot-location" - }, - - schema: [ - { - enum: ["object", "property"] - } - ], - - fixable: "code", - - messages: { - expectedDotAfterObject: "Expected dot to be on same line as object.", - expectedDotBeforeProperty: "Expected dot to be on same line as property." - } - }, - - create(context) { - - const config = context.options[0]; - - // default to onObject if no preference is passed - const onObject = config === "object" || !config; - - const sourceCode = context.getSourceCode(); - - /** - * Reports if the dot between object and property is on the correct loccation. - * @param {ASTNode} obj The object owning the property. - * @param {ASTNode} prop The property of the object. - * @param {ASTNode} node The corresponding node of the token. - * @returns {void} - */ - function checkDotLocation(obj, prop, node) { - const dot = sourceCode.getTokenBefore(prop); - const textBeforeDot = sourceCode.getText().slice(obj.range[1], dot.range[0]); - const textAfterDot = sourceCode.getText().slice(dot.range[1], prop.range[0]); - - if (dot.type === "Punctuator" && dot.value === ".") { - if (onObject) { - if (!astUtils.isTokenOnSameLine(obj, dot)) { - const neededTextAfterObj = astUtils.isDecimalInteger(obj) ? " " : ""; - - context.report({ - node, - loc: dot.loc.start, - messageId: "expectedDotAfterObject", - fix: fixer => fixer.replaceTextRange([obj.range[1], prop.range[0]], `${neededTextAfterObj}.${textBeforeDot}${textAfterDot}`) - }); - } - } else if (!astUtils.isTokenOnSameLine(dot, prop)) { - context.report({ - node, - loc: dot.loc.start, - messageId: "expectedDotBeforeProperty", - fix: fixer => fixer.replaceTextRange([obj.range[1], prop.range[0]], `${textBeforeDot}${textAfterDot}.`) - }); - } - } - } - - /** - * Checks the spacing of the dot within a member expression. - * @param {ASTNode} node The node to check. - * @returns {void} - */ - function checkNode(node) { - checkDotLocation(node.object, node.property, node); - } - - return { - MemberExpression: checkNode - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/dot-notation.js b/tools/node_modules/eslint/lib/rules/dot-notation.js deleted file mode 100644 index a1b091da0ea90d..00000000000000 --- a/tools/node_modules/eslint/lib/rules/dot-notation.js +++ /dev/null @@ -1,169 +0,0 @@ -/** - * @fileoverview Rule to warn about using dot notation instead of square bracket notation when possible. - * @author Josh Perez - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -const validIdentifier = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/; -const keywords = require("../util/keywords"); - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce dot notation whenever possible", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/dot-notation" - }, - - schema: [ - { - type: "object", - properties: { - allowKeywords: { - type: "boolean", - default: true - }, - allowPattern: { - type: "string", - default: "" - } - }, - additionalProperties: false - } - ], - - fixable: "code", - - messages: { - useDot: "[{{key}}] is better written in dot notation.", - useBrackets: ".{{key}} is a syntax error." - } - }, - - create(context) { - const options = context.options[0] || {}; - const allowKeywords = options.allowKeywords === void 0 || options.allowKeywords; - const sourceCode = context.getSourceCode(); - - let allowPattern; - - if (options.allowPattern) { - allowPattern = new RegExp(options.allowPattern); - } - - /** - * Check if the property is valid dot notation - * @param {ASTNode} node The dot notation node - * @param {string} value Value which is to be checked - * @returns {void} - */ - function checkComputedProperty(node, value) { - if ( - validIdentifier.test(value) && - (allowKeywords || keywords.indexOf(String(value)) === -1) && - !(allowPattern && allowPattern.test(value)) - ) { - const formattedValue = node.property.type === "Literal" ? JSON.stringify(value) : `\`${value}\``; - - context.report({ - node: node.property, - messageId: "useDot", - data: { - key: formattedValue - }, - fix(fixer) { - const leftBracket = sourceCode.getTokenAfter(node.object, astUtils.isOpeningBracketToken); - const rightBracket = sourceCode.getLastToken(node); - - if (sourceCode.getFirstTokenBetween(leftBracket, rightBracket, { includeComments: true, filter: astUtils.isCommentToken })) { - - // Don't perform any fixes if there are comments inside the brackets. - return null; - } - - const tokenAfterProperty = sourceCode.getTokenAfter(rightBracket); - const needsSpaceAfterProperty = tokenAfterProperty && - rightBracket.range[1] === tokenAfterProperty.range[0] && - !astUtils.canTokensBeAdjacent(String(value), tokenAfterProperty); - - const textBeforeDot = astUtils.isDecimalInteger(node.object) ? " " : ""; - const textAfterProperty = needsSpaceAfterProperty ? " " : ""; - - return fixer.replaceTextRange( - [leftBracket.range[0], rightBracket.range[1]], - `${textBeforeDot}.${value}${textAfterProperty}` - ); - } - }); - } - } - - return { - MemberExpression(node) { - if ( - node.computed && - node.property.type === "Literal" - ) { - checkComputedProperty(node, node.property.value); - } - if ( - node.computed && - node.property.type === "TemplateLiteral" && - node.property.expressions.length === 0 - ) { - checkComputedProperty(node, node.property.quasis[0].value.cooked); - } - if ( - !allowKeywords && - !node.computed && - keywords.indexOf(String(node.property.name)) !== -1 - ) { - context.report({ - node: node.property, - messageId: "useBrackets", - data: { - key: node.property.name - }, - fix(fixer) { - const dot = sourceCode.getTokenBefore(node.property); - const textAfterDot = sourceCode.text.slice(dot.range[1], node.property.range[0]); - - if (textAfterDot.trim()) { - - // Don't perform any fixes if there are comments between the dot and the property name. - return null; - } - - if (node.object.type === "Identifier" && node.object.name === "let") { - - /* - * A statement that starts with `let[` is parsed as a destructuring variable declaration, not - * a MemberExpression. - */ - return null; - } - - return fixer.replaceTextRange( - [dot.range[0], node.property.range[1]], - `[${textAfterDot}"${node.property.name}"]` - ); - } - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/eol-last.js b/tools/node_modules/eslint/lib/rules/eol-last.js deleted file mode 100644 index 84f4d45f176bbc..00000000000000 --- a/tools/node_modules/eslint/lib/rules/eol-last.js +++ /dev/null @@ -1,112 +0,0 @@ -/** - * @fileoverview Require or disallow newline at the end of files - * @author Nodeca Team - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const lodash = require("lodash"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "require or disallow newline at the end of files", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/eol-last" - }, - - fixable: "whitespace", - - schema: [ - { - enum: ["always", "never", "unix", "windows"] - } - ], - - messages: { - missing: "Newline required at end of file but not found.", - unexpected: "Newline not allowed at end of file." - } - }, - create(context) { - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - Program: function checkBadEOF(node) { - const sourceCode = context.getSourceCode(), - src = sourceCode.getText(), - location = { - column: lodash.last(sourceCode.lines).length, - line: sourceCode.lines.length - }, - LF = "\n", - CRLF = `\r${LF}`, - endsWithNewline = lodash.endsWith(src, LF); - - /* - * Empty source is always valid: No content in file so we don't - * need to lint for a newline on the last line of content. - */ - if (!src.length) { - return; - } - - let mode = context.options[0] || "always", - appendCRLF = false; - - if (mode === "unix") { - - // `"unix"` should behave exactly as `"always"` - mode = "always"; - } - if (mode === "windows") { - - // `"windows"` should behave exactly as `"always"`, but append CRLF in the fixer for backwards compatibility - mode = "always"; - appendCRLF = true; - } - if (mode === "always" && !endsWithNewline) { - - // File is not newline-terminated, but should be - context.report({ - node, - loc: location, - messageId: "missing", - fix(fixer) { - return fixer.insertTextAfterRange([0, src.length], appendCRLF ? CRLF : LF); - } - }); - } else if (mode === "never" && endsWithNewline) { - - // File is newline-terminated, but shouldn't be - context.report({ - node, - loc: location, - messageId: "unexpected", - fix(fixer) { - const finalEOLs = /(?:\r?\n)+$/, - match = finalEOLs.exec(sourceCode.text), - start = match.index, - end = sourceCode.text.length; - - return fixer.replaceTextRange([start, end], ""); - } - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/eqeqeq.js b/tools/node_modules/eslint/lib/rules/eqeqeq.js deleted file mode 100644 index a52de67d750e95..00000000000000 --- a/tools/node_modules/eslint/lib/rules/eqeqeq.js +++ /dev/null @@ -1,187 +0,0 @@ -/** - * @fileoverview Rule to flag statements that use != and == instead of !== and === - * @author Nicholas C. Zakas - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require the use of `===` and `!==`", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/eqeqeq" - }, - - schema: { - anyOf: [ - { - type: "array", - items: [ - { - enum: ["always"] - }, - { - type: "object", - properties: { - null: { - enum: ["always", "never", "ignore"], - default: "always" - } - }, - additionalProperties: false - } - ], - additionalItems: false - }, - { - type: "array", - items: [ - { - enum: ["smart", "allow-null"] - } - ], - additionalItems: false - } - ] - }, - - fixable: "code", - - messages: { - unexpected: "Expected '{{expectedOperator}}' and instead saw '{{actualOperator}}'." - } - }, - - create(context) { - const config = context.options[0] || "always"; - const options = context.options[1] || {}; - const sourceCode = context.getSourceCode(); - - const nullOption = (config === "always") - ? options.null || "always" - : "ignore"; - const enforceRuleForNull = (nullOption === "always"); - const enforceInverseRuleForNull = (nullOption === "never"); - - /** - * Checks if an expression is a typeof expression - * @param {ASTNode} node The node to check - * @returns {boolean} if the node is a typeof expression - */ - function isTypeOf(node) { - return node.type === "UnaryExpression" && node.operator === "typeof"; - } - - /** - * Checks if either operand of a binary expression is a typeof operation - * @param {ASTNode} node The node to check - * @returns {boolean} if one of the operands is typeof - * @private - */ - function isTypeOfBinary(node) { - return isTypeOf(node.left) || isTypeOf(node.right); - } - - /** - * Checks if operands are literals of the same type (via typeof) - * @param {ASTNode} node The node to check - * @returns {boolean} if operands are of same type - * @private - */ - function areLiteralsAndSameType(node) { - return node.left.type === "Literal" && node.right.type === "Literal" && - typeof node.left.value === typeof node.right.value; - } - - /** - * Checks if one of the operands is a literal null - * @param {ASTNode} node The node to check - * @returns {boolean} if operands are null - * @private - */ - function isNullCheck(node) { - return astUtils.isNullLiteral(node.right) || astUtils.isNullLiteral(node.left); - } - - /** - * Gets the location (line and column) of the binary expression's operator - * @param {ASTNode} node The binary expression node to check - * @returns {Object} { line, column } location of operator - * @private - */ - function getOperatorLocation(node) { - const opToken = sourceCode.getTokenAfter(node.left); - - 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} expectedOperator The operator that was expected (either '==', '!=', '===', or '!==') - * @returns {void} - * @private - */ - function report(node, expectedOperator) { - context.report({ - node, - loc: getOperatorLocation(node), - messageId: "unexpected", - 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.getFirstTokenBetween( - node.left, - node.right, - token => token.value === node.operator - ); - - return fixer.replaceText(operatorToken, expectedOperator); - } - return null; - } - }); - } - - return { - BinaryExpression(node) { - const isNull = isNullCheck(node); - - if (node.operator !== "==" && node.operator !== "!=") { - if (enforceInverseRuleForNull && isNull) { - report(node, node.operator.slice(0, -1)); - } - return; - } - - if (config === "smart" && (isTypeOfBinary(node) || - areLiteralsAndSameType(node) || isNull)) { - return; - } - - if (!enforceRuleForNull && isNull) { - return; - } - - report(node, `${node.operator}=`); - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/for-direction.js b/tools/node_modules/eslint/lib/rules/for-direction.js deleted file mode 100644 index c15d10e5f842a4..00000000000000 --- a/tools/node_modules/eslint/lib/rules/for-direction.js +++ /dev/null @@ -1,126 +0,0 @@ -/** - * @fileoverview enforce "for" loop update clause moving the counter in the right direction.(for-direction) - * @author Aladdin-ADD - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "enforce \"for\" loop update clause moving the counter in the right direction.", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/for-direction" - }, - - fixable: null, - schema: [], - - messages: { - incorrectDirection: "The update clause in this loop moves the variable in the wrong direction." - } - }, - - create(context) { - - /** - * report an error. - * @param {ASTNode} node the node to report. - * @returns {void} - */ - function report(node) { - context.report({ - node, - messageId: "incorrectDirection" - }); - } - - /** - * check the right side of the assignment - * @param {ASTNode} update UpdateExpression to check - * @param {int} dir expected direction that could either be turned around or invalidated - * @returns {int} return dir, the negated dir or zero if it's not clear for identifiers - */ - function getRightDirection(update, dir) { - if (update.right.type === "UnaryExpression") { - if (update.right.operator === "-") { - return -dir; - } - } else if (update.right.type === "Identifier") { - return 0; - } - return dir; - } - - /** - * check UpdateExpression add/sub the counter - * @param {ASTNode} update UpdateExpression to check - * @param {string} counter variable name to check - * @returns {int} if add return 1, if sub return -1, if nochange, return 0 - */ - function getUpdateDirection(update, counter) { - if (update.argument.type === "Identifier" && update.argument.name === counter) { - if (update.operator === "++") { - return 1; - } - if (update.operator === "--") { - return -1; - } - } - return 0; - } - - /** - * check AssignmentExpression add/sub the counter - * @param {ASTNode} update AssignmentExpression to check - * @param {string} counter variable name to check - * @returns {int} if add return 1, if sub return -1, if nochange, return 0 - */ - function getAssignmentDirection(update, counter) { - if (update.left.name === counter) { - if (update.operator === "+=") { - return getRightDirection(update, 1); - } - if (update.operator === "-=") { - return getRightDirection(update, -1); - } - } - return 0; - } - return { - ForStatement(node) { - - if (node.test && node.test.type === "BinaryExpression" && node.test.left.type === "Identifier" && node.update) { - const counter = node.test.left.name; - const operator = node.test.operator; - const update = node.update; - - let wrongDirection; - - if (operator === "<" || operator === "<=") { - wrongDirection = -1; - } else if (operator === ">" || operator === ">=") { - wrongDirection = 1; - } else { - return; - } - - if (update.type === "UpdateExpression") { - if (getUpdateDirection(update, counter) === wrongDirection) { - report(node); - } - } else if (update.type === "AssignmentExpression" && getAssignmentDirection(update, counter) === wrongDirection) { - report(node); - } - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/func-call-spacing.js b/tools/node_modules/eslint/lib/rules/func-call-spacing.js deleted file mode 100644 index 62bba144e6ff97..00000000000000 --- a/tools/node_modules/eslint/lib/rules/func-call-spacing.js +++ /dev/null @@ -1,169 +0,0 @@ -/** - * @fileoverview Rule to control spacing within function calls - * @author Matt DuVall - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "require or disallow spacing between function identifiers and their invocations", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/func-call-spacing" - }, - - fixable: "whitespace", - - schema: { - anyOf: [ - { - type: "array", - items: [ - { - enum: ["never"] - } - ], - minItems: 0, - maxItems: 1 - }, - { - type: "array", - items: [ - { - enum: ["always"] - }, - { - type: "object", - properties: { - allowNewlines: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - minItems: 0, - maxItems: 2 - } - ] - }, - - messages: { - unexpected: "Unexpected newline between function name and paren.", - missing: "Missing space between function name and paren." - } - }, - - create(context) { - - const never = context.options[0] !== "always"; - const allowNewlines = !never && context.options[1] && context.options[1].allowNewlines; - const sourceCode = context.getSourceCode(); - const text = sourceCode.getText(); - - /** - * Check if open space is present in a function name - * @param {ASTNode} node node to evaluate - * @returns {void} - * @private - */ - function checkSpacing(node) { - const lastToken = sourceCode.getLastToken(node); - const lastCalleeToken = sourceCode.getLastToken(node.callee); - const parenToken = sourceCode.getFirstTokenBetween(lastCalleeToken, lastToken, astUtils.isOpeningParenToken); - const prevToken = parenToken && sourceCode.getTokenBefore(parenToken); - - // Parens in NewExpression are optional - if (!(parenToken && parenToken.range[1] < node.range[1])) { - return; - } - - const textBetweenTokens = text.slice(prevToken.range[1], parenToken.range[0]).replace(/\/\*.*?\*\//g, ""); - const hasWhitespace = /\s/.test(textBetweenTokens); - const hasNewline = hasWhitespace && astUtils.LINEBREAK_MATCHER.test(textBetweenTokens); - - /* - * never allowNewlines hasWhitespace hasNewline message - * F F F F Missing space between function name and paren. - * F F F T (Invalid `!hasWhitespace && hasNewline`) - * F F T T Unexpected newline between function name and paren. - * F F T F (OK) - * F T T F (OK) - * F T T T (OK) - * F T F T (Invalid `!hasWhitespace && hasNewline`) - * F T F F Missing space between function name and paren. - * T T F F (Invalid `never && allowNewlines`) - * T T F T (Invalid `!hasWhitespace && hasNewline`) - * T T T T (Invalid `never && allowNewlines`) - * T T T F (Invalid `never && allowNewlines`) - * T F T F Unexpected space between function name and paren. - * T F T T Unexpected space between function name and paren. - * T F F T (Invalid `!hasWhitespace && hasNewline`) - * T F F F (OK) - * - * T T Unexpected space between function name and paren. - * F F Missing space between function name and paren. - * F F T Unexpected newline between function name and paren. - */ - - if (never && hasWhitespace) { - context.report({ - node, - loc: lastCalleeToken.loc.start, - messageId: "unexpected", - fix(fixer) { - - /* - * 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) { - context.report({ - node, - loc: lastCalleeToken.loc.start, - messageId: "missing", - fix(fixer) { - return fixer.insertTextBefore(parenToken, " "); - } - }); - } else if (!never && !allowNewlines && hasNewline) { - context.report({ - node, - loc: lastCalleeToken.loc.start, - messageId: "unexpected", - fix(fixer) { - return fixer.replaceTextRange([prevToken.range[1], parenToken.range[0]], " "); - } - }); - } - } - - return { - CallExpression: checkSpacing, - NewExpression: checkSpacing - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/func-name-matching.js b/tools/node_modules/eslint/lib/rules/func-name-matching.js deleted file mode 100644 index 5560c692083843..00000000000000 --- a/tools/node_modules/eslint/lib/rules/func-name-matching.js +++ /dev/null @@ -1,251 +0,0 @@ -/** - * @fileoverview Rule to require function names to match the name of the variable or property to which they are assigned. - * @author Annie Zhang, Pavel Strashkin - */ - -"use strict"; - -//-------------------------------------------------------------------------- -// Requirements -//-------------------------------------------------------------------------- - -const astUtils = require("../util/ast-utils"); -const esutils = require("esutils"); - -//-------------------------------------------------------------------------- -// Helpers -//-------------------------------------------------------------------------- - -/** - * Determines if a pattern is `module.exports` or `module["exports"]` - * @param {ASTNode} pattern The left side of the AssignmentExpression - * @returns {boolean} True if the pattern is `module.exports` or `module["exports"]` - */ -function isModuleExports(pattern) { - if (pattern.type === "MemberExpression" && pattern.object.type === "Identifier" && pattern.object.name === "module") { - - // module.exports - if (pattern.property.type === "Identifier" && pattern.property.name === "exports") { - return true; - } - - // module["exports"] - if (pattern.property.type === "Literal" && pattern.property.value === "exports") { - return true; - } - } - return false; -} - -/** - * Determines if a string name is a valid identifier - * @param {string} name The string to be checked - * @param {int} ecmaVersion The ECMAScript version if specified in the parserOptions config - * @returns {boolean} True if the string is a valid identifier - */ -function isIdentifier(name, ecmaVersion) { - if (ecmaVersion >= 6) { - return esutils.keyword.isIdentifierES6(name); - } - return esutils.keyword.isIdentifierES5(name); -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -const alwaysOrNever = { enum: ["always", "never"] }; -const optionsObject = { - type: "object", - properties: { - considerPropertyDescriptor: { - type: "boolean" - }, - includeCommonJSModuleExports: { - type: "boolean" - } - }, - additionalProperties: false -}; - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require function names to match the name of the variable or property to which they are assigned", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/func-name-matching" - }, - - schema: { - anyOf: [{ - type: "array", - additionalItems: false, - items: [alwaysOrNever, optionsObject] - }, { - type: "array", - additionalItems: false, - items: [optionsObject] - }] - }, - - messages: { - matchProperty: "Function name `{{funcName}}` should match property name `{{name}}`.", - matchVariable: "Function name `{{funcName}}` should match variable name `{{name}}`.", - notMatchProperty: "Function name `{{funcName}}` should not match property name `{{name}}`.", - notMatchVariable: "Function name `{{funcName}}` should not match variable name `{{name}}`." - } - }, - - create(context) { - 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 considerPropertyDescriptor = options.considerPropertyDescriptor; - const includeModuleExports = options.includeCommonJSModuleExports; - const ecmaVersion = context.parserOptions && context.parserOptions.ecmaVersion ? context.parserOptions.ecmaVersion : 5; - - /** - * Check whether node is a certain CallExpression. - * @param {string} objName object name - * @param {string} funcName function name - * @param {ASTNode} node The node to check - * @returns {boolean} `true` if node matches CallExpression - */ - function isPropertyCall(objName, funcName, node) { - if (!node) { - return false; - } - return node.type === "CallExpression" && - node.callee.object.name === objName && - node.callee.property.name === funcName; - } - - /** - * 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 - * @param {string} name The variable or property name - * @param {string} funcName The function name - * @param {boolean} isProp True if the reported node is a property assignment - * @returns {void} - */ - function report(node, name, funcName, isProp) { - let messageId; - - if (nameMatches === "always" && isProp) { - messageId = "matchProperty"; - } else if (nameMatches === "always") { - messageId = "matchVariable"; - } else if (isProp) { - messageId = "notMatchProperty"; - } else { - messageId = "notMatchVariable"; - } - context.report({ - node, - messageId, - data: { - name, - funcName - } - }); - } - - /** - * Determines whether a given node is a string literal - * @param {ASTNode} node The node to check - * @returns {boolean} `true` if the node is a string literal - */ - function isStringLiteral(node) { - return node.type === "Literal" && typeof node.value === "string"; - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - VariableDeclarator(node) { - if (!node.init || node.init.type !== "FunctionExpression" || node.id.type !== "Identifier") { - return; - } - if (node.init.id && shouldWarn(node.id.name, node.init.id.name)) { - report(node, node.id.name, node.init.id.name, false); - } - }, - - AssignmentExpression(node) { - if ( - node.right.type !== "FunctionExpression" || - (node.left.computed && node.left.property.type !== "Literal") || - (!includeModuleExports && isModuleExports(node.left)) || - (node.left.type !== "Identifier" && node.left.type !== "MemberExpression") - ) { - return; - } - - const isProp = node.left.type === "MemberExpression"; - const name = isProp ? astUtils.getStaticPropertyName(node.left) : node.left.name; - - if (node.right.id && isIdentifier(name) && shouldWarn(name, node.right.id.name)) { - report(node, name, node.right.id.name, isProp); - } - }, - - Property(node) { - if (node.value.type !== "FunctionExpression" || !node.value.id || node.computed && !isStringLiteral(node.key)) { - return; - } - - if (node.key.type === "Identifier") { - const functionName = node.value.id.name; - let propertyName = node.key.name; - - if (considerPropertyDescriptor && propertyName === "value") { - if (isPropertyCall("Object", "defineProperty", node.parent.parent) || isPropertyCall("Reflect", "defineProperty", node.parent.parent)) { - const property = node.parent.parent.arguments[1]; - - if (isStringLiteral(property) && shouldWarn(property.value, functionName)) { - report(node, property.value, functionName, true); - } - } else if (isPropertyCall("Object", "defineProperties", node.parent.parent.parent.parent)) { - propertyName = node.parent.parent.key.name; - if (!node.parent.parent.computed && shouldWarn(propertyName, functionName)) { - report(node, propertyName, functionName, true); - } - } else if (isPropertyCall("Object", "create", node.parent.parent.parent.parent)) { - propertyName = node.parent.parent.key.name; - if (!node.parent.parent.computed && shouldWarn(propertyName, functionName)) { - report(node, propertyName, functionName, true); - } - } else if (shouldWarn(propertyName, functionName)) { - report(node, propertyName, functionName, true); - } - } else if (shouldWarn(propertyName, functionName)) { - report(node, propertyName, functionName, true); - } - return; - } - - if ( - isStringLiteral(node.key) && - 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/node_modules/eslint/lib/rules/func-names.js b/tools/node_modules/eslint/lib/rules/func-names.js deleted file mode 100644 index 4ccbae0f0cb849..00000000000000 --- a/tools/node_modules/eslint/lib/rules/func-names.js +++ /dev/null @@ -1,179 +0,0 @@ -/** - * @fileoverview Rule to warn when a function expression does not have a name. - * @author Kyle T. Nunery - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -/** - * Checks whether or not a given variable is a function name. - * @param {eslint-scope.Variable} variable - A variable to check. - * @returns {boolean} `true` if the variable is a function name. - */ -function isFunctionName(variable) { - return variable && variable.defs[0].type === "FunctionName"; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require or disallow named `function` expressions", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/func-names" - }, - - schema: { - definitions: { - value: { - enum: [ - "always", - "as-needed", - "never" - ] - } - }, - items: [ - { - $ref: "#/definitions/value" - }, - { - type: "object", - properties: { - generators: { - $ref: "#/definitions/value" - } - }, - additionalProperties: false - } - ] - }, - - messages: { - unnamed: "Unexpected unnamed {{name}}.", - named: "Unexpected named {{name}}." - } - }, - - create(context) { - - /** - * Returns the config option for the given node. - * @param {ASTNode} node - A node to get the config for. - * @returns {string} The config option. - */ - function getConfigForNode(node) { - if ( - node.generator && - context.options.length > 1 && - context.options[1].generators - ) { - return context.options[1].generators; - } - - return context.options[0] || "always"; - } - - /** - * 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(node) { - const parent = node.parent; - - return (parent.type === "MethodDefinition" || ( - parent.type === "Property" && ( - parent.method || - parent.kind === "get" || - parent.kind === "set" - ) - )); - } - - /** - * 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); - } - - /** - * Reports that an unnamed function should be named - * @param {ASTNode} node - The node to report in the event of an error. - * @returns {void} - */ - function reportUnexpectedUnnamedFunction(node) { - context.report({ - node, - messageId: "unnamed", - data: { name: astUtils.getFunctionNameWithKind(node) } - }); - } - - /** - * Reports that a named function should be unnamed - * @param {ASTNode} node - The node to report in the event of an error. - * @returns {void} - */ - function reportUnexpectedNamedFunction(node) { - context.report({ - node, - messageId: "named", - data: { name: astUtils.getFunctionNameWithKind(node) } - }); - } - - return { - "FunctionExpression:exit"(node) { - - // Skip recursive functions. - const nameVar = context.getDeclaredVariables(node)[0]; - - if (isFunctionName(nameVar) && nameVar.references.length > 0) { - return; - } - - const hasName = Boolean(node.id && node.id.name); - const config = getConfigForNode(node); - - if (config === "never") { - if (hasName) { - reportUnexpectedNamedFunction(node); - } - } else if (config === "as-needed") { - if (!hasName && !hasInferredName(node)) { - reportUnexpectedUnnamedFunction(node); - } - } else { - if (!hasName && !isObjectOrClassMethod(node)) { - reportUnexpectedUnnamedFunction(node); - } - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/func-style.js b/tools/node_modules/eslint/lib/rules/func-style.js deleted file mode 100644 index e150b1a76f26a6..00000000000000 --- a/tools/node_modules/eslint/lib/rules/func-style.js +++ /dev/null @@ -1,98 +0,0 @@ -/** - * @fileoverview Rule to enforce a particular function style - * @author Nicholas C. Zakas - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce the consistent use of either `function` declarations or expressions", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/func-style" - }, - - schema: [ - { - enum: ["declaration", "expression"] - }, - { - type: "object", - properties: { - allowArrowFunctions: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - - messages: { - expression: "Expected a function expression.", - declaration: "Expected a function declaration." - } - }, - - create(context) { - - const style = context.options[0], - allowArrowFunctions = context.options[1] && context.options[1].allowArrowFunctions, - enforceDeclarations = (style === "declaration"), - stack = []; - - const nodesToCheck = { - FunctionDeclaration(node) { - stack.push(false); - - if (!enforceDeclarations && node.parent.type !== "ExportDefaultDeclaration") { - context.report({ node, messageId: "expression" }); - } - }, - "FunctionDeclaration:exit"() { - stack.pop(); - }, - - FunctionExpression(node) { - stack.push(false); - - if (enforceDeclarations && node.parent.type === "VariableDeclarator") { - context.report({ node: node.parent, messageId: "declaration" }); - } - }, - "FunctionExpression:exit"() { - stack.pop(); - }, - - ThisExpression() { - if (stack.length > 0) { - stack[stack.length - 1] = true; - } - } - }; - - if (!allowArrowFunctions) { - nodesToCheck.ArrowFunctionExpression = function() { - stack.push(false); - }; - - nodesToCheck["ArrowFunctionExpression:exit"] = function(node) { - const hasThisExpr = stack.pop(); - - if (enforceDeclarations && !hasThisExpr && node.parent.type === "VariableDeclarator") { - context.report({ node: node.parent, messageId: "declaration" }); - } - }; - } - - return nodesToCheck; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/function-paren-newline.js b/tools/node_modules/eslint/lib/rules/function-paren-newline.js deleted file mode 100644 index 37256484f4a16e..00000000000000 --- a/tools/node_modules/eslint/lib/rules/function-paren-newline.js +++ /dev/null @@ -1,233 +0,0 @@ -/** - * @fileoverview enforce consistent line breaks inside function parentheses - * @author Teddy Katz - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce consistent line breaks inside function parentheses", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/function-paren-newline" - }, - - fixable: "whitespace", - - schema: [ - { - oneOf: [ - { - enum: ["always", "never", "consistent", "multiline"] - }, - { - type: "object", - properties: { - minItems: { - type: "integer", - minimum: 0 - } - }, - additionalProperties: false - } - ] - } - ], - - messages: { - expectedBefore: "Expected newline before ')'.", - expectedAfter: "Expected newline after '('.", - unexpectedBefore: "Unexpected newline before '('.", - unexpectedAfter: "Unexpected newline after ')'." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - const rawOption = context.options[0] || "multiline"; - const multilineOption = rawOption === "multiline"; - const consistentOption = rawOption === "consistent"; - let minItems; - - if (typeof rawOption === "object") { - minItems = rawOption.minItems; - } else if (rawOption === "always") { - minItems = 0; - } else if (rawOption === "never") { - minItems = Infinity; - } else { - minItems = null; - } - - //---------------------------------------------------------------------- - // Helpers - //---------------------------------------------------------------------- - - /** - * Determines whether there should be newlines inside function parens - * @param {ASTNode[]} elements The arguments or parameters in the list - * @param {boolean} hasLeftNewline `true` if the left paren has a newline in the current code. - * @returns {boolean} `true` if there should be newlines inside the function parens - */ - function shouldHaveNewlines(elements, hasLeftNewline) { - if (multilineOption) { - return elements.some((element, index) => index !== elements.length - 1 && element.loc.end.line !== elements[index + 1].loc.start.line); - } - if (consistentOption) { - return hasLeftNewline; - } - return elements.length >= minItems; - } - - /** - * Validates a list of arguments or parameters - * @param {Object} parens An object with keys `leftParen` for the left paren token, and `rightParen` for the right paren token - * @param {ASTNode[]} elements The arguments or parameters in the list - * @returns {void} - */ - function validateParens(parens, elements) { - const leftParen = parens.leftParen; - const rightParen = parens.rightParen; - const tokenAfterLeftParen = sourceCode.getTokenAfter(leftParen); - const tokenBeforeRightParen = sourceCode.getTokenBefore(rightParen); - const hasLeftNewline = !astUtils.isTokenOnSameLine(leftParen, tokenAfterLeftParen); - const hasRightNewline = !astUtils.isTokenOnSameLine(tokenBeforeRightParen, rightParen); - const needsNewlines = shouldHaveNewlines(elements, hasLeftNewline); - - if (hasLeftNewline && !needsNewlines) { - context.report({ - node: leftParen, - messageId: "unexpectedAfter", - fix(fixer) { - return sourceCode.getText().slice(leftParen.range[1], tokenAfterLeftParen.range[0]).trim() - - // If there is a comment between the ( and the first element, don't do a fix. - ? null - : fixer.removeRange([leftParen.range[1], tokenAfterLeftParen.range[0]]); - } - }); - } else if (!hasLeftNewline && needsNewlines) { - context.report({ - node: leftParen, - messageId: "expectedAfter", - fix: fixer => fixer.insertTextAfter(leftParen, "\n") - }); - } - - if (hasRightNewline && !needsNewlines) { - context.report({ - node: rightParen, - messageId: "unexpectedBefore", - fix(fixer) { - return sourceCode.getText().slice(tokenBeforeRightParen.range[1], rightParen.range[0]).trim() - - // If there is a comment between the last element and the ), don't do a fix. - ? null - : fixer.removeRange([tokenBeforeRightParen.range[1], rightParen.range[0]]); - } - }); - } else if (!hasRightNewline && needsNewlines) { - context.report({ - node: rightParen, - messageId: "expectedBefore", - fix: fixer => fixer.insertTextBefore(rightParen, "\n") - }); - } - } - - /** - * Gets the left paren and right paren tokens of a node. - * @param {ASTNode} node The node with parens - * @returns {Object} An object with keys `leftParen` for the left paren token, and `rightParen` for the right paren token. - * Can also return `null` if an expression has no parens (e.g. a NewExpression with no arguments, or an ArrowFunctionExpression - * with a single parameter) - */ - function getParenTokens(node) { - switch (node.type) { - case "NewExpression": - if (!node.arguments.length && !( - astUtils.isOpeningParenToken(sourceCode.getLastToken(node, { skip: 1 })) && - astUtils.isClosingParenToken(sourceCode.getLastToken(node)) - )) { - - // If the NewExpression does not have parens (e.g. `new Foo`), return null. - return null; - } - - // falls through - - case "CallExpression": - return { - leftParen: sourceCode.getTokenAfter(node.callee, astUtils.isOpeningParenToken), - rightParen: sourceCode.getLastToken(node) - }; - - case "FunctionDeclaration": - case "FunctionExpression": { - const leftParen = sourceCode.getFirstToken(node, astUtils.isOpeningParenToken); - const rightParen = node.params.length - ? sourceCode.getTokenAfter(node.params[node.params.length - 1], astUtils.isClosingParenToken) - : sourceCode.getTokenAfter(leftParen); - - return { leftParen, rightParen }; - } - - case "ArrowFunctionExpression": { - const firstToken = sourceCode.getFirstToken(node); - - if (!astUtils.isOpeningParenToken(firstToken)) { - - // If the ArrowFunctionExpression has a single param without parens, return null. - return null; - } - - return { - leftParen: firstToken, - rightParen: sourceCode.getTokenBefore(node.body, astUtils.isClosingParenToken) - }; - } - - default: - throw new TypeError(`unexpected node with type ${node.type}`); - } - } - - /** - * Validates the parentheses for a node - * @param {ASTNode} node The node with parens - * @returns {void} - */ - function validateNode(node) { - const parens = getParenTokens(node); - - if (parens) { - validateParens(parens, astUtils.isFunction(node) ? node.params : node.arguments); - } - } - - //---------------------------------------------------------------------- - // Public - //---------------------------------------------------------------------- - - return { - ArrowFunctionExpression: validateNode, - CallExpression: validateNode, - FunctionDeclaration: validateNode, - FunctionExpression: validateNode, - NewExpression: validateNode - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/generator-star-spacing.js b/tools/node_modules/eslint/lib/rules/generator-star-spacing.js deleted file mode 100644 index 6f860290cec8b6..00000000000000 --- a/tools/node_modules/eslint/lib/rules/generator-star-spacing.js +++ /dev/null @@ -1,211 +0,0 @@ -/** - * @fileoverview Rule to check the spacing around the * in generator functions. - * @author Jamund Ferguson - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -const OVERRIDE_SCHEMA = { - oneOf: [ - { - enum: ["before", "after", "both", "neither"] - }, - { - type: "object", - properties: { - before: { type: "boolean" }, - after: { type: "boolean" } - }, - additionalProperties: false - } - ] -}; - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce consistent spacing around `*` operators in generator functions", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/generator-star-spacing" - }, - - fixable: "whitespace", - - schema: [ - { - oneOf: [ - { - enum: ["before", "after", "both", "neither"] - }, - { - type: "object", - properties: { - before: { type: "boolean" }, - after: { type: "boolean" }, - named: OVERRIDE_SCHEMA, - anonymous: OVERRIDE_SCHEMA, - method: OVERRIDE_SCHEMA - }, - additionalProperties: false - } - ] - } - ], - - messages: { - missingBefore: "Missing space before *.", - missingAfter: "Missing space after *.", - unexpectedBefore: "Unexpected space before *.", - unexpectedAfter: "Unexpected space after *." - } - }, - - create(context) { - - const optionDefinitions = { - before: { before: true, after: false }, - after: { before: false, after: true }, - both: { before: true, after: true }, - neither: { before: false, after: false } - }; - - /** - * Returns resolved option definitions based on an option and defaults - * - * @param {any} option - The option object or string value - * @param {Object} defaults - The defaults to use if options are not present - * @returns {Object} the resolved object definition - */ - function optionToDefinition(option, defaults) { - if (!option) { - return defaults; - } - - return typeof option === "string" - ? optionDefinitions[option] - : Object.assign({}, defaults, option); - } - - const modes = (function(option) { - const defaults = optionToDefinition(option, optionDefinitions.before); - - return { - named: optionToDefinition(option.named, defaults), - anonymous: optionToDefinition(option.anonymous, defaults), - method: optionToDefinition(option.method, defaults) - }; - }(context.options[0] || {})); - - const sourceCode = context.getSourceCode(); - - /** - * Checks if the given token is a star token or not. - * - * @param {Token} token - The token to check. - * @returns {boolean} `true` if the token is a star token. - */ - function isStarToken(token) { - return token.value === "*" && token.type === "Punctuator"; - } - - /** - * Gets the generator star token of the given function node. - * - * @param {ASTNode} node - The function node to get. - * @returns {Token} Found star token. - */ - function getStarToken(node) { - return sourceCode.getFirstToken( - (node.parent.method || node.parent.type === "MethodDefinition") ? node.parent : node, - isStarToken - ); - } - - /** - * capitalize a given string. - * @param {string} str the given string. - * @returns {string} the capitalized string. - */ - function capitalize(str) { - return str[0].toUpperCase() + str.slice(1); - } - - /** - * Checks the spacing between two tokens before or after the star token. - * - * @param {string} kind Either "named", "anonymous", or "method" - * @param {string} side Either "before" or "after". - * @param {Token} leftToken `function` keyword token if side is "before", or - * star token if side is "after". - * @param {Token} rightToken Star token if side is "before", or identifier - * token if side is "after". - * @returns {void} - */ - function checkSpacing(kind, side, leftToken, rightToken) { - if (!!(rightToken.range[0] - leftToken.range[1]) !== modes[kind][side]) { - const after = leftToken.value === "*"; - const spaceRequired = modes[kind][side]; - const node = after ? leftToken : rightToken; - const messageId = `${spaceRequired ? "missing" : "unexpected"}${capitalize(side)}`; - - context.report({ - node, - messageId, - fix(fixer) { - if (spaceRequired) { - if (after) { - return fixer.insertTextAfter(node, " "); - } - return fixer.insertTextBefore(node, " "); - } - return fixer.removeRange([leftToken.range[1], rightToken.range[0]]); - } - }); - } - } - - /** - * Enforces the spacing around the star if node is a generator function. - * - * @param {ASTNode} node A function expression or declaration node. - * @returns {void} - */ - function checkFunction(node) { - if (!node.generator) { - return; - } - - const starToken = getStarToken(node); - const prevToken = sourceCode.getTokenBefore(starToken); - const nextToken = sourceCode.getTokenAfter(starToken); - - let kind = "named"; - - if (node.parent.type === "MethodDefinition" || (node.parent.type === "Property" && node.parent.method)) { - kind = "method"; - } else if (!node.id) { - kind = "anonymous"; - } - - // Only check before when preceded by `function`|`static` keyword - if (!(kind === "method" && starToken === sourceCode.getFirstToken(node.parent))) { - checkSpacing(kind, "before", prevToken, starToken); - } - - checkSpacing(kind, "after", starToken, nextToken); - } - - return { - FunctionDeclaration: checkFunction, - FunctionExpression: checkFunction - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/getter-return.js b/tools/node_modules/eslint/lib/rules/getter-return.js deleted file mode 100644 index a1806c357b1afa..00000000000000 --- a/tools/node_modules/eslint/lib/rules/getter-return.js +++ /dev/null @@ -1,186 +0,0 @@ -/** - * @fileoverview Enforces that a return statement is present in property getters. - * @author Aladdin-ADD(hh_2013@foxmail.com) - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ -const TARGET_NODE_TYPE = /^(?:Arrow)?FunctionExpression$/; - -/** - * Checks a given code path segment is reachable. - * - * @param {CodePathSegment} segment - A segment to check. - * @returns {boolean} `true` if the segment is reachable. - */ -function isReachable(segment) { - return segment.reachable; -} - -/** - * Gets a readable location. - * - * - FunctionExpression -> the function name or `function` keyword. - * - * @param {ASTNode} node - A function node to get. - * @returns {ASTNode|Token} The node or the token of a location. - */ -function getId(node) { - return node.id || node; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "enforce `return` statements in getters", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/getter-return" - }, - - fixable: null, - - schema: [ - { - type: "object", - properties: { - allowImplicit: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - - messages: { - expected: "Expected to return a value in {{name}}.", - expectedAlways: "Expected {{name}} to always return a value." - } - }, - - create(context) { - - const options = context.options[0] || { allowImplicit: false }; - - let funcInfo = { - upper: null, - codePath: null, - hasReturn: false, - shouldCheck: false, - node: null - }; - - /** - * Checks whether or not the last code path segment is reachable. - * Then reports this function if the segment is reachable. - * - * If the last code path segment is reachable, there are paths which are not - * returned or thrown. - * - * @param {ASTNode} node - A node to check. - * @returns {void} - */ - function checkLastSegment(node) { - if (funcInfo.shouldCheck && - funcInfo.codePath.currentSegments.some(isReachable) - ) { - context.report({ - node, - loc: getId(node).loc.start, - messageId: funcInfo.hasReturn ? "expectedAlways" : "expected", - data: { - name: astUtils.getFunctionNameWithKind(funcInfo.node) - } - }); - } - } - - /** - * Checks whether a node means a getter function. - * @param {ASTNode} node - a node to check. - * @returns {boolean} if node means a getter, return true; else return false. - */ - function isGetter(node) { - const parent = node.parent; - - if (TARGET_NODE_TYPE.test(node.type) && node.body.type === "BlockStatement") { - if (parent.kind === "get") { - return true; - } - if (parent.type === "Property" && astUtils.getStaticPropertyName(parent) === "get" && parent.parent.type === "ObjectExpression") { - - // Object.defineProperty() - if (parent.parent.parent.type === "CallExpression" && - astUtils.getStaticPropertyName(parent.parent.parent.callee) === "defineProperty") { - return true; - } - - // Object.defineProperties() - if (parent.parent.parent.type === "Property" && - parent.parent.parent.parent.type === "ObjectExpression" && - parent.parent.parent.parent.parent.type === "CallExpression" && - astUtils.getStaticPropertyName(parent.parent.parent.parent.parent.callee) === "defineProperties") { - return true; - } - } - } - return false; - } - return { - - // Stacks this function's information. - onCodePathStart(codePath, node) { - funcInfo = { - upper: funcInfo, - codePath, - hasReturn: false, - shouldCheck: isGetter(node), - node - }; - }, - - // Pops this function's information. - onCodePathEnd() { - funcInfo = funcInfo.upper; - }, - - // Checks the return statement is valid. - ReturnStatement(node) { - if (funcInfo.shouldCheck) { - funcInfo.hasReturn = true; - - // if allowImplicit: false, should also check node.argument - if (!options.allowImplicit && !node.argument) { - context.report({ - node, - messageId: "expected", - data: { - name: astUtils.getFunctionNameWithKind(funcInfo.node) - } - }); - } - } - }, - - // Reports a given function if the last path is reachable. - "FunctionExpression:exit": checkLastSegment, - "ArrowFunctionExpression:exit": checkLastSegment - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/global-require.js b/tools/node_modules/eslint/lib/rules/global-require.js deleted file mode 100644 index 4af3a6a4669a79..00000000000000 --- a/tools/node_modules/eslint/lib/rules/global-require.js +++ /dev/null @@ -1,81 +0,0 @@ -/** - * @fileoverview Rule for disallowing require() outside of the top-level module context - * @author Jamund Ferguson - */ - -"use strict"; - -const ACCEPTABLE_PARENTS = [ - "AssignmentExpression", - "VariableDeclarator", - "MemberExpression", - "ExpressionStatement", - "CallExpression", - "ConditionalExpression", - "Program", - "VariableDeclaration" -]; - -/** - * Finds the eslint-scope reference in the given scope. - * @param {Object} scope The scope to search. - * @param {ASTNode} node The identifier node. - * @returns {Reference|null} Returns the found reference or null if none were found. - */ -function findReference(scope, node) { - 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) { - return references[0]; - } - return null; - -} - -/** - * Checks if the given identifier node is shadowed in the given scope. - * @param {Object} scope The current scope. - * @param {ASTNode} node The identifier node to check. - * @returns {boolean} Whether or not the name is shadowed. - */ -function isShadowed(scope, node) { - const reference = findReference(scope, node); - - return reference && reference.resolved && reference.resolved.defs.length > 0; -} - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require `require()` calls to be placed at top-level module scope", - category: "Node.js and CommonJS", - recommended: false, - url: "https://eslint.org/docs/rules/global-require" - }, - - schema: [], - messages: { - unexpected: "Unexpected require()." - } - }, - - create(context) { - return { - CallExpression(node) { - const currentScope = context.getScope(); - - if (node.callee.name === "require" && !isShadowed(currentScope, node.callee)) { - const isGoodRequire = context.getAncestors().every(parent => ACCEPTABLE_PARENTS.indexOf(parent.type) > -1); - - if (!isGoodRequire) { - context.report({ node, messageId: "unexpected" }); - } - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/guard-for-in.js b/tools/node_modules/eslint/lib/rules/guard-for-in.js deleted file mode 100644 index 2c0976d997b601..00000000000000 --- a/tools/node_modules/eslint/lib/rules/guard-for-in.js +++ /dev/null @@ -1,76 +0,0 @@ -/** - * @fileoverview Rule to flag for-in loops without if statements inside - * @author Nicholas C. Zakas - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require `for-in` loops to include an `if` statement", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/guard-for-in" - }, - - schema: [], - messages: { - wrap: "The body of a for-in should be wrapped in an if statement to filter unwanted properties from the prototype." - } - }, - - create(context) { - - return { - - ForInStatement(node) { - const body = node.body; - - // empty statement - if (body.type === "EmptyStatement") { - return; - } - - // if statement - if (body.type === "IfStatement") { - return; - } - - // empty block - if (body.type === "BlockStatement" && body.body.length === 0) { - return; - } - - // block with just if statement - if (body.type === "BlockStatement" && body.body.length === 1 && body.body[0].type === "IfStatement") { - return; - } - - // block that starts with if statement - if (body.type === "BlockStatement" && body.body.length >= 1 && body.body[0].type === "IfStatement") { - const i = body.body[0]; - - // ... whose consequent is a continue - if (i.consequent.type === "ContinueStatement") { - return; - } - - // ... whose consequent is a block that contains only a continue - if (i.consequent.type === "BlockStatement" && i.consequent.body.length === 1 && i.consequent.body[0].type === "ContinueStatement") { - return; - } - } - - context.report({ node, messageId: "wrap" }); - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/handle-callback-err.js b/tools/node_modules/eslint/lib/rules/handle-callback-err.js deleted file mode 100644 index 2966aff2e61fda..00000000000000 --- a/tools/node_modules/eslint/lib/rules/handle-callback-err.js +++ /dev/null @@ -1,95 +0,0 @@ -/** - * @fileoverview Ensure handling of errors when we know they exist. - * @author Jamund Ferguson - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require error handling in callbacks", - category: "Node.js and CommonJS", - recommended: false, - url: "https://eslint.org/docs/rules/handle-callback-err" - }, - - schema: [ - { - type: "string" - } - ], - messages: { - expected: "Expected error to be handled." - } - }, - - create(context) { - - const errorArgument = context.options[0] || "err"; - - /** - * Checks if the given argument should be interpreted as a regexp pattern. - * @param {string} stringToCheck The string which should be checked. - * @returns {boolean} Whether or not the string should be interpreted as a pattern. - */ - function isPattern(stringToCheck) { - const firstChar = stringToCheck[0]; - - return firstChar === "^"; - } - - /** - * Checks if the given name matches the configured error argument. - * @param {string} name The name which should be compared. - * @returns {boolean} Whether or not the given name matches the configured error variable name. - */ - function matchesConfiguredErrorName(name) { - if (isPattern(errorArgument)) { - const regexp = new RegExp(errorArgument); - - return regexp.test(name); - } - return name === errorArgument; - } - - /** - * Get the parameters of a given function scope. - * @param {Object} scope The function scope. - * @returns {Array} All parameters of the given scope. - */ - function getParameters(scope) { - return scope.variables.filter(variable => variable.defs[0] && variable.defs[0].type === "Parameter"); - } - - /** - * Check to see if we're handling the error object properly. - * @param {ASTNode} node The AST node to check. - * @returns {void} - */ - function checkForError(node) { - const scope = context.getScope(), - parameters = getParameters(scope), - firstParameter = parameters[0]; - - if (firstParameter && matchesConfiguredErrorName(firstParameter.name)) { - if (firstParameter.references.length === 0) { - context.report({ node, messageId: "expected" }); - } - } - } - - return { - FunctionDeclaration: checkForError, - FunctionExpression: checkForError, - ArrowFunctionExpression: checkForError - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/id-blacklist.js b/tools/node_modules/eslint/lib/rules/id-blacklist.js deleted file mode 100644 index 53be62e68a3626..00000000000000 --- a/tools/node_modules/eslint/lib/rules/id-blacklist.js +++ /dev/null @@ -1,127 +0,0 @@ -/** - * @fileoverview Rule that warns when identifier names that are - * blacklisted in the configuration are used. - * @author Keith Cirkel (http://keithcirkel.co.uk) - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow specified identifiers", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/id-blacklist" - }, - - schema: { - type: "array", - items: { - type: "string" - }, - uniqueItems: true - }, - messages: { - blacklisted: "Identifier '{{name}}' is blacklisted." - } - }, - - create(context) { - - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - const blacklist = context.options; - - - /** - * Checks if a string matches the provided pattern - * @param {string} name The string to check. - * @returns {boolean} if the string is a match - * @private - */ - function isInvalid(name) { - return blacklist.indexOf(name) !== -1; - } - - /** - * Verifies if we should report an error or not based on the effective - * parent node and the identifier name. - * @param {ASTNode} effectiveParent The effective parent node of the node to be reported - * @param {string} name The identifier name of the identifier node - * @returns {boolean} whether an error should be reported or not - */ - function shouldReport(effectiveParent, name) { - return effectiveParent.type !== "CallExpression" && - effectiveParent.type !== "NewExpression" && - isInvalid(name); - } - - /** - * Reports an AST node as a rule violation. - * @param {ASTNode} node The node to report. - * @returns {void} - * @private - */ - function report(node) { - context.report({ - node, - messageId: "blacklisted", - data: { - name: node.name - } - }); - } - - return { - - Identifier(node) { - const name = node.name, - effectiveParent = (node.parent.type === "MemberExpression") ? node.parent.parent : node.parent; - - // MemberExpressions get special rules - if (node.parent.type === "MemberExpression") { - - // Always check object names - if (node.parent.object.type === "Identifier" && - node.parent.object.name === node.name) { - if (isInvalid(name)) { - report(node); - } - - // Report AssignmentExpressions only if they are the left side of the assignment - } else if (effectiveParent.type === "AssignmentExpression" && - (effectiveParent.right.type !== "MemberExpression" || - effectiveParent.left.type === "MemberExpression" && - effectiveParent.left.property.name === node.name)) { - if (isInvalid(name)) { - report(node); - } - } - - // Properties have their own rules - } else if (node.parent.type === "Property") { - - if (shouldReport(effectiveParent, name)) { - report(node); - } - - // Report anything that is a match and not a CallExpression - } else if (shouldReport(effectiveParent, name)) { - report(node); - } - } - - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/id-length.js b/tools/node_modules/eslint/lib/rules/id-length.js deleted file mode 100644 index c8586ea3481895..00000000000000 --- a/tools/node_modules/eslint/lib/rules/id-length.js +++ /dev/null @@ -1,122 +0,0 @@ -/** - * @fileoverview Rule that warns when identifier names are shorter or longer - * than the values provided in configuration. - * @author Burak Yigit Kaya aka BYK - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce minimum and maximum identifier lengths", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/id-length" - }, - - schema: [ - { - type: "object", - properties: { - min: { - type: "integer", - default: 2 - }, - max: { - type: "integer" - }, - exceptions: { - type: "array", - uniqueItems: true, - items: { - type: "string" - } - }, - properties: { - enum: ["always", "never"] - } - }, - additionalProperties: false - } - ], - messages: { - tooShort: "Identifier name '{{name}}' is too short (< {{min}}).", - tooLong: "Identifier name '{{name}}' is too long (> {{max}})." - } - }, - - create(context) { - const options = context.options[0] || {}; - const minLength = typeof options.min !== "undefined" ? options.min : 2; - const maxLength = typeof options.max !== "undefined" ? options.max : Infinity; - const properties = options.properties !== "never"; - const exceptions = (options.exceptions ? options.exceptions : []) - .reduce((obj, item) => { - obj[item] = true; - - return obj; - }, {}); - - const SUPPORTED_EXPRESSIONS = { - MemberExpression: properties && function(parent) { - return !parent.computed && ( - - // regular property assignment - (parent.parent.left === parent && parent.parent.type === "AssignmentExpression" || - - // or the last identifier in an ObjectPattern destructuring - parent.parent.type === "Property" && parent.parent.value === parent && - parent.parent.parent.type === "ObjectPattern" && parent.parent.parent.parent.left === parent.parent.parent) - ); - }, - AssignmentPattern(parent, node) { - return parent.left === node; - }, - VariableDeclarator(parent, node) { - return parent.id === node; - }, - Property: properties && function(parent, node) { - return parent.key === node; - }, - ImportDefaultSpecifier: true, - RestElement: true, - FunctionExpression: true, - ArrowFunctionExpression: true, - ClassDeclaration: true, - FunctionDeclaration: true, - MethodDefinition: true, - CatchClause: true - }; - - return { - Identifier(node) { - const name = node.name; - const parent = node.parent; - - const isShort = name.length < minLength; - const isLong = name.length > maxLength; - - if (!(isShort || isLong) || exceptions[name]) { - return; // Nothing to report - } - - const isValidExpression = SUPPORTED_EXPRESSIONS[parent.type]; - - if (isValidExpression && (isValidExpression === true || isValidExpression(parent, node))) { - context.report({ - node, - messageId: isShort ? "tooShort" : "tooLong", - data: { name, min: minLength, max: maxLength } - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/id-match.js b/tools/node_modules/eslint/lib/rules/id-match.js deleted file mode 100644 index 3978a5ef684b7f..00000000000000 --- a/tools/node_modules/eslint/lib/rules/id-match.js +++ /dev/null @@ -1,225 +0,0 @@ -/** - * @fileoverview Rule to flag non-matching identifiers - * @author Matthieu Larcher - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require identifiers to match a specified regular expression", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/id-match" - }, - - schema: [ - { - type: "string" - }, - { - type: "object", - properties: { - properties: { - type: "boolean", - default: false - }, - onlyDeclarations: { - type: "boolean", - default: false - }, - ignoreDestructuring: { - type: "boolean", - default: false - } - } - } - ], - messages: { - notMatch: "Identifier '{{name}}' does not match the pattern '{{pattern}}'." - } - }, - - create(context) { - - //-------------------------------------------------------------------------- - // Options - //-------------------------------------------------------------------------- - const pattern = context.options[0] || "^.+$", - regexp = new RegExp(pattern); - - const options = context.options[1] || {}, - properties = !!options.properties, - onlyDeclarations = !!options.onlyDeclarations, - ignoreDestructuring = !!options.ignoreDestructuring; - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - // contains reported nodes to avoid reporting twice on destructuring with shorthand notation - const reported = new Map(); - const ALLOWED_PARENT_TYPES = new Set(["CallExpression", "NewExpression"]); - const DECLARATION_TYPES = new Set(["FunctionDeclaration", "VariableDeclarator"]); - const IMPORT_TYPES = new Set(["ImportSpecifier", "ImportNamespaceSpecifier", "ImportDefaultSpecifier"]); - - /** - * Checks if a string matches the provided pattern - * @param {string} name The string to check. - * @returns {boolean} if the string is a match - * @private - */ - function isInvalid(name) { - return !regexp.test(name); - } - - /** - * Checks if a parent of a node is an ObjectPattern. - * @param {ASTNode} node The node to check. - * @returns {boolean} if the node is inside an ObjectPattern - * @private - */ - function isInsideObjectPattern(node) { - let { parent } = node; - - while (parent) { - if (parent.type === "ObjectPattern") { - return true; - } - - parent = parent.parent; - } - - return false; - } - - /** - * Verifies if we should report an error or not based on the effective - * parent node and the identifier name. - * @param {ASTNode} effectiveParent The effective parent node of the node to be reported - * @param {string} name The identifier name of the identifier node - * @returns {boolean} whether an error should be reported or not - */ - function shouldReport(effectiveParent, name) { - return (!onlyDeclarations || DECLARATION_TYPES.has(effectiveParent.type)) && - !ALLOWED_PARENT_TYPES.has(effectiveParent.type) && isInvalid(name); - } - - /** - * Reports an AST node as a rule violation. - * @param {ASTNode} node The node to report. - * @returns {void} - * @private - */ - function report(node) { - if (!reported.has(node)) { - context.report({ - node, - messageId: "notMatch", - data: { - name: node.name, - pattern - } - }); - reported.set(node, true); - } - } - - return { - - Identifier(node) { - const name = node.name, - parent = node.parent, - effectiveParent = (parent.type === "MemberExpression") ? parent.parent : parent; - - if (parent.type === "MemberExpression") { - - if (!properties) { - return; - } - - // Always check object names - if (parent.object.type === "Identifier" && - parent.object.name === name) { - if (isInvalid(name)) { - report(node); - } - - // Report AssignmentExpressions left side's assigned variable id - } else if (effectiveParent.type === "AssignmentExpression" && - effectiveParent.left.type === "MemberExpression" && - effectiveParent.left.property.name === node.name) { - if (isInvalid(name)) { - report(node); - } - - // Report AssignmentExpressions only if they are the left side of the assignment - } else if (effectiveParent.type === "AssignmentExpression" && effectiveParent.right.type !== "MemberExpression") { - if (isInvalid(name)) { - report(node); - } - } - - /* - * Properties have their own rules, and - * AssignmentPattern nodes can be treated like Properties: - * e.g.: const { no_camelcased = false } = bar; - */ - } else if (parent.type === "Property" || parent.type === "AssignmentPattern") { - - if (parent.parent && parent.parent.type === "ObjectPattern") { - if (parent.shorthand && parent.value.left && isInvalid(name)) { - - report(node); - } - - const assignmentKeyEqualsValue = parent.key.name === parent.value.name; - - // prevent checking righthand side of destructured object - if (!assignmentKeyEqualsValue && parent.key === node) { - return; - } - - const valueIsInvalid = parent.value.name && isInvalid(name); - - // ignore destructuring if the option is set, unless a new identifier is created - if (valueIsInvalid && !(assignmentKeyEqualsValue && ignoreDestructuring)) { - report(node); - } - } - - // never check properties or always ignore destructuring - if (!properties || (ignoreDestructuring && isInsideObjectPattern(node))) { - return; - } - - // don't check right hand side of AssignmentExpression to prevent duplicate warnings - if (parent.right !== node && shouldReport(effectiveParent, name)) { - report(node); - } - - // Check if it's an import specifier - } else if (IMPORT_TYPES.has(parent.type)) { - - // Report only if the local imported identifier is invalid - if (parent.local && parent.local.name === node.name && isInvalid(name)) { - report(node); - } - - // Report anything that is invalid that isn't a CallExpression - } else if (shouldReport(effectiveParent, name)) { - report(node); - } - } - - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/implicit-arrow-linebreak.js b/tools/node_modules/eslint/lib/rules/implicit-arrow-linebreak.js deleted file mode 100644 index ad0d70da66cc76..00000000000000 --- a/tools/node_modules/eslint/lib/rules/implicit-arrow-linebreak.js +++ /dev/null @@ -1,236 +0,0 @@ -/** - * @fileoverview enforce the location of arrow function bodies - * @author Sharmila Jesupaul - */ -"use strict"; - -const { - isArrowToken, - isParenthesised, - isOpeningParenToken -} = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce the location of arrow function bodies", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/implicit-arrow-linebreak" - }, - - fixable: "whitespace", - - schema: [ - { - enum: ["beside", "below"] - } - ], - messages: { - expected: "Expected a linebreak before this expression.", - unexpected: "Expected no linebreak before this expression." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - //---------------------------------------------------------------------- - // Helpers - //---------------------------------------------------------------------- - /** - * Gets the applicable preference for a particular keyword - * @returns {string} The applicable option for the keyword, e.g. 'beside' - */ - function getOption() { - return context.options[0] || "beside"; - } - - /** - * Formats the comments depending on whether it's a line or block comment. - * @param {Comment[]} comments The array of comments between the arrow and body - * @param {Integer} column The column number of the first token - * @returns {string} A string of comment text joined by line breaks - */ - function formatComments(comments, column) { - const whiteSpaces = " ".repeat(column); - - return `${comments.map(comment => { - - if (comment.type === "Line") { - return `//${comment.value}`; - } - - return `/*${comment.value}*/`; - }).join(`\n${whiteSpaces}`)}\n${whiteSpaces}`; - } - - /** - * Finds the first token to prepend comments to depending on the parent type - * @param {Node} node The validated node - * @returns {Token|Node} The node to prepend comments to - */ - function findFirstToken(node) { - switch (node.parent.type) { - case "VariableDeclarator": - - // If the parent is first or only declarator, return the declaration, else, declarator - return sourceCode.getFirstToken( - node.parent.parent.declarations.length === 1 || - node.parent.parent.declarations[0].id.name === node.parent.id.name - ? node.parent.parent : node.parent - ); - case "CallExpression": - case "Property": - - // find the object key - return sourceCode.getFirstToken(node.parent); - default: - return node; - } - } - - /** - * Helper function for adding parentheses fixes for nodes containing nested arrow functions - * @param {Fixer} fixer Fixer - * @param {Token} arrow - The arrow token - * @param {ASTNode} arrowBody - The arrow function body - * @returns {Function[]} autofixer -- wraps function bodies with parentheses - */ - function addParentheses(fixer, arrow, arrowBody) { - const parenthesesFixes = []; - let closingParentheses = ""; - - let followingBody = arrowBody; - let currentArrow = arrow; - - while (currentArrow) { - if (!isParenthesised(sourceCode, followingBody)) { - parenthesesFixes.push( - fixer.insertTextAfter(currentArrow, " (") - ); - - const paramsToken = sourceCode.getTokenBefore(currentArrow, token => - isOpeningParenToken(token) || token.type === "Identifier"); - - const whiteSpaces = " ".repeat(paramsToken.loc.start.column); - - closingParentheses = `\n${whiteSpaces})${closingParentheses}`; - } - - currentArrow = sourceCode.getTokenAfter(currentArrow, isArrowToken); - - if (currentArrow) { - followingBody = sourceCode.getTokenAfter(currentArrow, token => !isOpeningParenToken(token)); - } - } - - return [...parenthesesFixes, - fixer.insertTextAfter(arrowBody, closingParentheses) - ]; - } - - /** - * Autofixes the function body to collapse onto the same line as the arrow. - * If comments exist, prepends the comments before the arrow function. - * If the function body contains arrow functions, appends the function bodies with parentheses. - * @param {Token} arrowToken The arrow token. - * @param {ASTNode} arrowBody the function body - * @param {ASTNode} node The evaluated node - * @returns {Function} autofixer -- validates the node to adhere to besides - */ - function autoFixBesides(arrowToken, arrowBody, node) { - return fixer => { - const placeBesides = fixer.replaceTextRange([arrowToken.range[1], arrowBody.range[0]], " "); - - const comments = sourceCode.getCommentsInside(node).filter(comment => - comment.loc.start.line < arrowBody.loc.start.line); - - if (comments.length) { - - // If the grandparent is not a variable declarator - if ( - arrowBody.parent && - arrowBody.parent.parent && - arrowBody.parent.parent.type !== "VariableDeclarator" - ) { - - // If any arrow functions follow, return the necessary parens fixes. - if (sourceCode.getTokenAfter(arrowToken, isArrowToken) && arrowBody.parent.parent.type !== "VariableDeclarator") { - return addParentheses(fixer, arrowToken, arrowBody); - } - - // If any arrow functions precede, the necessary fixes have already been returned, so return null. - if (sourceCode.getTokenBefore(arrowToken, isArrowToken) && arrowBody.parent.parent.type !== "VariableDeclarator") { - return null; - } - } - - const firstToken = findFirstToken(node); - - const commentText = formatComments(comments, firstToken.loc.start.column); - - const commentBeforeExpression = fixer.insertTextBeforeRange( - firstToken.range, - commentText - ); - - return [placeBesides, commentBeforeExpression]; - } - - return placeBesides; - }; - } - - /** - * Validates the location of an arrow function body - * @param {ASTNode} node The arrow function body - * @returns {void} - */ - function validateExpression(node) { - const option = getOption(); - - let tokenBefore = sourceCode.getTokenBefore(node.body); - const hasParens = tokenBefore.value === "("; - - if (node.type === "BlockStatement") { - return; - } - - let fixerTarget = node.body; - - if (hasParens) { - - // Gets the first token before the function body that is not an open paren - tokenBefore = sourceCode.getTokenBefore(node.body, token => token.value !== "("); - fixerTarget = sourceCode.getTokenAfter(tokenBefore); - } - - if (tokenBefore.loc.end.line === fixerTarget.loc.start.line && option === "below") { - context.report({ - node: fixerTarget, - messageId: "expected", - fix: fixer => fixer.insertTextBefore(fixerTarget, "\n") - }); - } else if (tokenBefore.loc.end.line !== fixerTarget.loc.start.line && option === "beside") { - context.report({ - node: fixerTarget, - messageId: "unexpected", - fix: autoFixBesides(tokenBefore, fixerTarget, node) - }); - } - } - - //---------------------------------------------------------------------- - // Public - //---------------------------------------------------------------------- - return { - ArrowFunctionExpression: node => validateExpression(node) - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/indent-legacy.js b/tools/node_modules/eslint/lib/rules/indent-legacy.js deleted file mode 100644 index 2a712c520a28c0..00000000000000 --- a/tools/node_modules/eslint/lib/rules/indent-legacy.js +++ /dev/null @@ -1,1141 +0,0 @@ -/** - * @fileoverview This option sets a specific tab width for your code - * - * This rule has been ported and modified from nodeca. - * @author Vitaly Puzrin - * @author Gyandeep Singh - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -/* istanbul ignore next: this rule has known coverage issues, but it's deprecated and shouldn't be updated in the future anyway. */ -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce consistent indentation", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/indent-legacy" - }, - - deprecated: true, - - replacedBy: ["indent"], - - fixable: "whitespace", - - schema: [ - { - oneOf: [ - { - enum: ["tab"] - }, - { - type: "integer", - minimum: 0 - } - ] - }, - { - type: "object", - properties: { - SwitchCase: { - type: "integer", - minimum: 0 - }, - VariableDeclarator: { - oneOf: [ - { - type: "integer", - minimum: 0 - }, - { - type: "object", - properties: { - var: { - type: "integer", - minimum: 0 - }, - let: { - type: "integer", - minimum: 0 - }, - const: { - type: "integer", - minimum: 0 - } - } - } - ] - }, - outerIIFEBody: { - type: "integer", - minimum: 0 - }, - MemberExpression: { - type: "integer", - minimum: 0 - }, - FunctionDeclaration: { - type: "object", - properties: { - parameters: { - oneOf: [ - { - type: "integer", - minimum: 0 - }, - { - enum: ["first"] - } - ] - }, - body: { - type: "integer", - minimum: 0 - } - } - }, - FunctionExpression: { - type: "object", - properties: { - parameters: { - oneOf: [ - { - type: "integer", - minimum: 0 - }, - { - enum: ["first"] - } - ] - }, - body: { - type: "integer", - 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 - } - ], - messages: { - expected: "Expected indentation of {{expected}} but found {{actual}}." - } - }, - - create(context) { - const DEFAULT_VARIABLE_INDENT = 1; - const DEFAULT_PARAMETER_INDENT = null; // For backwards compatibility, don't check parameter indentation unless specified in the config - const DEFAULT_FUNCTION_BODY_INDENT = 1; - - let indentType = "space"; - let indentSize = 4; - const options = { - SwitchCase: 0, - VariableDeclarator: { - var: DEFAULT_VARIABLE_INDENT, - let: DEFAULT_VARIABLE_INDENT, - const: DEFAULT_VARIABLE_INDENT - }, - outerIIFEBody: null, - FunctionDeclaration: { - parameters: DEFAULT_PARAMETER_INDENT, - body: DEFAULT_FUNCTION_BODY_INDENT - }, - FunctionExpression: { - parameters: DEFAULT_PARAMETER_INDENT, - body: DEFAULT_FUNCTION_BODY_INDENT - }, - CallExpression: { - arguments: DEFAULT_PARAMETER_INDENT - }, - ArrayExpression: 1, - ObjectExpression: 1 - }; - - const sourceCode = context.getSourceCode(); - - if (context.options.length) { - if (context.options[0] === "tab") { - indentSize = 1; - indentType = "tab"; - } else /* istanbul ignore else : this will be caught by options validation */ if (typeof context.options[0] === "number") { - indentSize = context.options[0]; - indentType = "space"; - } - - if (context.options[1]) { - const opts = context.options[1]; - - options.SwitchCase = opts.SwitchCase || 0; - const variableDeclaratorRules = opts.VariableDeclarator; - - if (typeof variableDeclaratorRules === "number") { - options.VariableDeclarator = { - var: variableDeclaratorRules, - let: variableDeclaratorRules, - const: variableDeclaratorRules - }; - } else if (typeof variableDeclaratorRules === "object") { - Object.assign(options.VariableDeclarator, variableDeclaratorRules); - } - - if (typeof opts.outerIIFEBody === "number") { - options.outerIIFEBody = opts.outerIIFEBody; - } - - if (typeof opts.MemberExpression === "number") { - options.MemberExpression = opts.MemberExpression; - } - - if (typeof opts.FunctionDeclaration === "object") { - Object.assign(options.FunctionDeclaration, opts.FunctionDeclaration); - } - - 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; - } - } - } - - const caseIndentStore = {}; - - /** - * Creates an error message for a line, given the expected/actual indentation. - * @param {int} expectedAmount The expected amount of indentation characters for this line - * @param {int} actualSpaces The actual number of indentation spaces that were found on this line - * @param {int} actualTabs The actual number of indentation tabs that were found on this line - * @returns {string} An error message for this line - */ - function createErrorMessageData(expectedAmount, actualSpaces, actualTabs) { - const expectedStatement = `${expectedAmount} ${indentType}${expectedAmount === 1 ? "" : "s"}`; // e.g. "2 tabs" - const foundSpacesWord = `space${actualSpaces === 1 ? "" : "s"}`; // e.g. "space" - const foundTabsWord = `tab${actualTabs === 1 ? "" : "s"}`; // e.g. "tabs" - let foundStatement; - - if (actualSpaces > 0 && actualTabs > 0) { - foundStatement = `${actualSpaces} ${foundSpacesWord} and ${actualTabs} ${foundTabsWord}`; // e.g. "1 space and 2 tabs" - } else if (actualSpaces > 0) { - - /* - * Abbreviate the message if the expected indentation is also spaces. - * e.g. 'Expected 4 spaces but found 2' rather than 'Expected 4 spaces but found 2 spaces' - */ - foundStatement = indentType === "space" ? actualSpaces : `${actualSpaces} ${foundSpacesWord}`; - } else if (actualTabs > 0) { - foundStatement = indentType === "tab" ? actualTabs : `${actualTabs} ${foundTabsWord}`; - } else { - foundStatement = "0"; - } - return { - expected: expectedStatement, - actual: foundStatement - }; - } - - /** - * Reports a given indent violation - * @param {ASTNode} node Node violating the indent rule - * @param {int} needed Expected indentation character count - * @param {int} gottenSpaces Indentation space count in the actual node/code - * @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 - * @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. - return; - } - - const desiredIndent = (indentType === "space" ? " " : "\t").repeat(needed); - - const textRange = isLastNodeCheck - ? [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, - loc, - messageId: "expected", - data: createErrorMessageData(needed, gottenSpaces, gottenTabs), - fix: fixer => fixer.replaceTextRange(textRange, desiredIndent) - }); - } - - /** - * Get the actual indent of node - * @param {ASTNode|Token} node Node to examine - * @param {boolean} [byLastLine=false] get indent of node's last line - * @returns {Object} The node's indent. Contains keys `space` and `tab`, representing the indent of each character. Also - * contains keys `goodChar` and `badChar`, where `goodChar` is the amount of the user's desired indentation character, and - * `badChar` is the amount of the other indentation character. - */ - function getNodeIndent(node, byLastLine) { - const token = byLastLine ? sourceCode.getLastToken(node) : sourceCode.getFirstToken(node); - const srcCharsBeforeNode = sourceCode.getText(token, token.loc.start.column).split(""); - const indentChars = srcCharsBeforeNode.slice(0, srcCharsBeforeNode.findIndex(char => char !== " " && char !== "\t")); - const spaces = indentChars.filter(char => char === " ").length; - const tabs = indentChars.filter(char => char === "\t").length; - - return { - space: spaces, - tab: tabs, - goodChar: indentType === "space" ? spaces : tabs, - badChar: indentType === "space" ? tabs : spaces - }; - } - - /** - * Checks node is the first in its own start line. By default it looks by start line. - * @param {ASTNode} node The node to check - * @param {boolean} [byEndLocation=false] Lookup based on start position or end - * @returns {boolean} true if its the first in the its start line - */ - function isNodeFirstInLine(node, byEndLocation) { - const firstToken = byEndLocation === true ? sourceCode.getLastToken(node, 1) : sourceCode.getTokenBefore(node), - startLine = byEndLocation === true ? node.loc.end.line : node.loc.start.line, - endLine = firstToken ? firstToken.loc.end.line : -1; - - return startLine !== endLine; - } - - /** - * Check indent for node - * @param {ASTNode} node Node to check - * @param {int} neededIndent needed indent - * @returns {void} - */ - function checkNodeIndent(node, neededIndent) { - const actualIndent = getNodeIndent(node, false); - - if ( - node.type !== "ArrayExpression" && - node.type !== "ObjectExpression" && - (actualIndent.goodChar !== neededIndent || actualIndent.badChar !== 0) && - isNodeFirstInLine(node) - ) { - report(node, neededIndent, actualIndent.space, actualIndent.tab); - } - - if (node.type === "IfStatement" && node.alternate) { - const elseToken = sourceCode.getTokenBefore(node.alternate); - - checkNodeIndent(elseToken, neededIndent); - - if (!isNodeFirstInLine(node.alternate)) { - 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); - } - } - - /** - * Check indent for nodes list - * @param {ASTNode[]} nodes list of node objects - * @param {int} indent needed indent - * @returns {void} - */ - function checkNodesIndent(nodes, indent) { - nodes.forEach(node => checkNodeIndent(node, indent)); - } - - /** - * Check last node line indent this detects, that block closed correctly - * @param {ASTNode} node Node to examine - * @param {int} lastLineIndent needed indent - * @returns {void} - */ - function checkLastNodeLineIndent(node, lastLineIndent) { - const lastToken = sourceCode.getLastToken(node); - const endIndent = getNodeIndent(lastToken, true); - - if ((endIndent.goodChar !== lastLineIndent || endIndent.badChar !== 0) && isNodeFirstInLine(node, true)) { - report( - node, - lastLineIndent, - endIndent.space, - endIndent.tab, - { line: lastToken.loc.start.line, column: lastToken.loc.start.column }, - true - ); - } - } - - /** - * 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) { - - /* - * in case if return statement ends with ');' we have traverse back to ')' - * otherwise we'll measure indent for ';' and replace ')' - */ - const lastToken = sourceCode.getLastToken(node, astUtils.isClosingParenToken); - 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 - * @param {int} firstLineIndent needed indent - * @returns {void} - */ - function checkFirstNodeLineIndent(node, firstLineIndent) { - const startIndent = getNodeIndent(node, false); - - if ((startIndent.goodChar !== firstLineIndent || startIndent.badChar !== 0) && isNodeFirstInLine(node)) { - report( - node, - firstLineIndent, - startIndent.space, - startIndent.tab, - { line: node.loc.start.line, column: node.loc.start.column } - ); - } - } - - /** - * Returns a parent node of given node based on a specified type - * 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, stopAtList) { - let parent = node.parent; - const stopAtSet = new Set(stopAtList || ["Program"]); - - while (parent.type !== type && !stopAtSet.has(parent.type) && parent.type !== "Program") { - parent = parent.parent; - } - - return parent.type === type ? parent : null; - } - - /** - * Returns the VariableDeclarator 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 getVariableDeclaratorNode(node) { - return getParentNodeByType(node, "VariableDeclarator"); - } - - /** - * Check to see if the node is part of the multi-line variable declaration. - * Also if its on the same line as the varNode - * @param {ASTNode} node node to check - * @param {ASTNode} varNode variable declaration node to check against - * @returns {boolean} True if all the above condition satisfy - */ - function isNodeInVarOnTop(node, varNode) { - return varNode && - varNode.parent.loc.start.line === node.loc.start.line && - varNode.parent.declarations.length > 1; - } - - /** - * Check to see if the argument before the callee node is multi-line and - * there should only be 1 argument before the callee node - * @param {ASTNode} node node to check - * @returns {boolean} True if arguments are multi-line - */ - function isArgBeforeCalleeNodeMultiline(node) { - const parent = node.parent; - - if (parent.arguments.length >= 2 && parent.arguments[1] === node) { - return parent.arguments[0].loc.end.line > parent.arguments[0].loc.start.line; - } - - return false; - } - - /** - * Check to see if the node is a file level IIFE - * @param {ASTNode} node The function node to check. - * @returns {boolean} True if the node is the outer IIFE - */ - function isOuterIIFE(node) { - const parent = node.parent; - let stmt = parent.parent; - - /* - * Verify that the node is an IIEF - */ - if ( - parent.type !== "CallExpression" || - parent.callee !== node) { - - return false; - } - - /* - * Navigate legal ancestors to determine whether this IIEF is outer - */ - while ( - stmt.type === "UnaryExpression" && ( - stmt.operator === "!" || - stmt.operator === "~" || - stmt.operator === "+" || - stmt.operator === "-") || - stmt.type === "AssignmentExpression" || - stmt.type === "LogicalExpression" || - stmt.type === "SequenceExpression" || - stmt.type === "VariableDeclarator") { - - stmt = stmt.parent; - } - - return (( - stmt.type === "ExpressionStatement" || - stmt.type === "VariableDeclaration") && - stmt.parent && stmt.parent.type === "Program" - ); - } - - /** - * Check indent for function block content - * @param {ASTNode} node A BlockStatement node that is inside of a function. - * @returns {void} - */ - function checkIndentInFunctionBlock(node) { - - /* - * Search first caller in chain. - * Ex.: - * - * Models <- Identifier - * .User - * .find() - * .exec(function() { - * // function body - * }); - * - * Looks for 'Models' - */ - const calleeNode = node.parent; // FunctionExpression - let indent; - - if (calleeNode.parent && - (calleeNode.parent.type === "Property" || - calleeNode.parent.type === "ArrayExpression")) { - - // If function is part of array or object, comma can be put at left - indent = getNodeIndent(calleeNode, false).goodChar; - } else { - - // If function is standalone, simple calculate indent - indent = getNodeIndent(calleeNode).goodChar; - } - - if (calleeNode.parent.type === "CallExpression") { - const calleeParent = calleeNode.parent; - - if (calleeNode.type !== "FunctionExpression" && calleeNode.type !== "ArrowFunctionExpression") { - if (calleeParent && calleeParent.loc.start.line < node.loc.start.line) { - indent = getNodeIndent(calleeParent).goodChar; - } - } else { - if (isArgBeforeCalleeNodeMultiline(calleeNode) && - calleeParent.callee.loc.start.line === calleeParent.callee.loc.end.line && - !isNodeFirstInLine(calleeNode)) { - indent = getNodeIndent(calleeParent).goodChar; - } - } - } - - /* - * function body indent should be indent + indent size, unless this - * is a FunctionDeclaration, FunctionExpression, or outer IIFE and the corresponding options are enabled. - */ - let functionOffset = indentSize; - - if (options.outerIIFEBody !== null && isOuterIIFE(calleeNode)) { - functionOffset = options.outerIIFEBody * indentSize; - } else if (calleeNode.type === "FunctionExpression") { - functionOffset = options.FunctionExpression.body * indentSize; - } else if (calleeNode.type === "FunctionDeclaration") { - functionOffset = options.FunctionDeclaration.body * indentSize; - } - indent += functionOffset; - - // check if the node is inside a variable - const parentVarNode = getVariableDeclaratorNode(node); - - if (parentVarNode && isNodeInVarOnTop(node, parentVarNode)) { - indent += indentSize * options.VariableDeclarator[parentVarNode.parent.kind]; - } - - if (node.body.length > 0) { - checkNodesIndent(node.body, indent); - } - - checkLastNodeLineIndent(node, indent - functionOffset); - } - - - /** - * Checks if the given node starts and ends on the same line - * @param {ASTNode} node The node to check - * @returns {boolean} Whether or not the block starts and ends on the same line. - */ - function isSingleLineNode(node) { - const lastToken = sourceCode.getLastToken(node), - startLine = node.loc.start.line, - endLine = lastToken.loc.end.line; - - return startLine === endLine; - } - - /** - * Check to see if the first element inside an array is an object and on the same line as the node - * If the node is not an array then it will return false. - * @param {ASTNode} node node to check - * @returns {boolean} success/failure - */ - function isFirstArrayElementOnSameLine(node) { - if (node.type === "ArrayExpression" && node.elements[0]) { - return node.elements[0].loc.start.line === node.loc.start.line && node.elements[0].type === "ObjectExpression"; - } - return false; - - } - - /** - * Check indent for array block content or object block content - * @param {ASTNode} node node to examine - * @returns {void} - */ - function checkIndentInArrayOrObjectBlock(node) { - - // Skip inline - if (isSingleLineNode(node)) { - return; - } - - 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(elem => elem !== null); - - let nodeIndent; - let elementsIndent; - const parentVarNode = getVariableDeclaratorNode(node); - - // TODO - come up with a better strategy in future - if (isNodeFirstInLine(node)) { - const parent = node.parent; - - 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 === parent.loc.start.line) { - nodeIndent += (indentSize * options.VariableDeclarator[parentVarNode.parent.kind]); - } else if (parent.type === "ObjectExpression" || parent.type === "ArrayExpression") { - const parentElements = node.parent.type === "ObjectExpression" ? node.parent.properties : node.parent.elements; - - if (parentElements[0] && - 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) && parent.type !== "MemberExpression" && parent.type !== "ExpressionStatement" && parent.type !== "AssignmentExpression" && parent.type !== "Property") { - nodeIndent += indentSize; - } - - checkFirstNodeLineIndent(node, nodeIndent); - } else { - nodeIndent = getNodeIndent(node).goodChar; - } - - 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]; - } - - /* - * Check if the node is a multiple variable declaration; if so, then - * make sure indentation takes that into account. - */ - if (isNodeInVarOnTop(node, parentVarNode)) { - elementsIndent += indentSize * options.VariableDeclarator[parentVarNode.parent.kind]; - } - - checkNodesIndent(elements, elementsIndent); - - if (elements.length > 0) { - - // Skip last block line check if last item in same line - if (elements[elements.length - 1].loc.end.line === node.loc.end.line) { - return; - } - } - - checkLastNodeLineIndent(node, nodeIndent + - (isNodeInVarOnTop(node, parentVarNode) ? options.VariableDeclarator[parentVarNode.parent.kind] * indentSize : 0)); - } - - /** - * Check if the node or node body is a BlockStatement or not - * @param {ASTNode} node node to test - * @returns {boolean} True if it or its body is a block statement - */ - function isNodeBodyBlock(node) { - return node.type === "BlockStatement" || node.type === "ClassBody" || (node.body && node.body.type === "BlockStatement") || - (node.consequent && node.consequent.type === "BlockStatement"); - } - - /** - * Check indentation for blocks - * @param {ASTNode} node node to check - * @returns {void} - */ - function blockIndentationCheck(node) { - - // Skip inline blocks - if (isSingleLineNode(node)) { - return; - } - - if (node.parent && ( - node.parent.type === "FunctionExpression" || - node.parent.type === "FunctionDeclaration" || - node.parent.type === "ArrowFunctionExpression") - ) { - checkIndentInFunctionBlock(node); - return; - } - - let indent; - let nodesToCheck = []; - - /* - * For this statements we should check indent from statement beginning, - * not from the beginning of the block. - */ - const statementsWithProperties = [ - "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; - } - - if (node.type === "IfStatement" && node.consequent.type !== "BlockStatement") { - nodesToCheck = [node.consequent]; - } else if (Array.isArray(node.body)) { - nodesToCheck = node.body; - } else { - nodesToCheck = [node.body]; - } - - if (nodesToCheck.length > 0) { - checkNodesIndent(nodesToCheck, indent + indentSize); - } - - if (node.type === "BlockStatement") { - checkLastNodeLineIndent(node, indent); - } - } - - /** - * Filter out the elements which are on the same line of each other or the node. - * basically have only 1 elements from each line except the variable declaration line. - * @param {ASTNode} node Variable declaration node - * @returns {ASTNode[]} Filtered elements - */ - function filterOutSameLineVars(node) { - return node.declarations.reduce((finalCollection, elem) => { - const lastElem = finalCollection[finalCollection.length - 1]; - - if ((elem.loc.start.line !== node.loc.start.line && !lastElem) || - (lastElem && lastElem.loc.start.line !== elem.loc.start.line)) { - finalCollection.push(elem); - } - - return finalCollection; - }, []); - } - - /** - * Check indentation for variable declarations - * @param {ASTNode} node node to examine - * @returns {void} - */ - function checkIndentInVariableDeclarations(node) { - const elements = filterOutSameLineVars(node); - const nodeIndent = getNodeIndent(node).goodChar; - const lastElement = elements[elements.length - 1]; - - const elementsIndent = nodeIndent + indentSize * options.VariableDeclarator[node.kind]; - - checkNodesIndent(elements, elementsIndent); - - // Only check the last line if there is any token after the last item - if (sourceCode.getLastToken(node).loc.end.line <= lastElement.loc.end.line) { - return; - } - - const tokenBeforeLastElement = sourceCode.getTokenBefore(lastElement); - - if (tokenBeforeLastElement.value === ",") { - - // Special case for comma-first syntax where the semicolon is indented - checkLastNodeLineIndent(node, getNodeIndent(tokenBeforeLastElement).goodChar); - } else { - checkLastNodeLineIndent(node, elementsIndent - indentSize); - } - } - - /** - * Check and decide whether to check for indentation for blockless nodes - * Scenarios are for or while statements without braces around them - * @param {ASTNode} node node to examine - * @returns {void} - */ - function blockLessNodes(node) { - if (node.body.type !== "BlockStatement") { - blockIndentationCheck(node); - } - } - - /** - * Returns the expected indentation for the case statement - * @param {ASTNode} node node to examine - * @param {int} [providedSwitchIndent] indent for switch statement - * @returns {int} indent size - */ - function expectedCaseIndent(node, providedSwitchIndent) { - const switchNode = (node.type === "SwitchStatement") ? node : node.parent; - const switchIndent = typeof providedSwitchIndent === "undefined" - ? getNodeIndent(switchNode).goodChar - : providedSwitchIndent; - let caseIndent; - - if (caseIndentStore[switchNode.loc.start.line]) { - return caseIndentStore[switchNode.loc.start.line]; - } - - if (switchNode.cases.length > 0 && options.SwitchCase === 0) { - caseIndent = switchIndent; - } else { - caseIndent = switchIndent + (indentSize * options.SwitchCase); - } - - caseIndentStore[switchNode.loc.start.line] = caseIndent; - return caseIndent; - - } - - /** - * 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) { - - // Root nodes should have no indent - checkNodesIndent(node.body, getNodeIndent(node).goodChar); - } - }, - - ClassBody: blockIndentationCheck, - - BlockStatement: blockIndentationCheck, - - WhileStatement: blockLessNodes, - - ForStatement: blockLessNodes, - - ForInStatement: blockLessNodes, - - ForOfStatement: blockLessNodes, - - DoWhileStatement: blockLessNodes, - - IfStatement(node) { - if (node.consequent.type !== "BlockStatement" && node.consequent.loc.start.line > node.loc.start.line) { - blockIndentationCheck(node); - } - }, - - VariableDeclaration(node) { - if (node.declarations[node.declarations.length - 1].loc.start.line > node.declarations[0].loc.start.line) { - checkIndentInVariableDeclarations(node); - } - }, - - ObjectExpression(node) { - checkIndentInArrayOrObjectBlock(node); - }, - - ArrayExpression(node) { - checkIndentInArrayOrObjectBlock(node); - }, - - MemberExpression(node) { - - if (typeof options.MemberExpression === "undefined") { - return; - } - - if (isSingleLineNode(node)) { - return; - } - - /* - * The typical layout of variable declarations and assignments - * alter the expectation of correct indentation. Skip them. - * TODO: Add appropriate configuration options for variable - * declarations and assignments. - */ - if (getParentNodeByType(node, "VariableDeclarator", ["FunctionExpression", "ArrowFunctionExpression"])) { - return; - } - - if (getParentNodeByType(node, "AssignmentExpression", ["FunctionExpression"])) { - return; - } - - const propertyIndent = getNodeIndent(node).goodChar + indentSize * options.MemberExpression; - - const checkNodes = [node.property]; - - const dot = sourceCode.getTokenBefore(node.property); - - if (dot.type === "Punctuator" && dot.value === ".") { - checkNodes.push(dot); - } - - checkNodesIndent(checkNodes, propertyIndent); - }, - - SwitchStatement(node) { - - // Switch is not a 'BlockStatement' - const switchIndent = getNodeIndent(node).goodChar; - const caseIndent = expectedCaseIndent(node, switchIndent); - - checkNodesIndent(node.cases, caseIndent); - - - checkLastNodeLineIndent(node, switchIndent); - }, - - SwitchCase(node) { - - // Skip inline cases - if (isSingleLineNode(node)) { - return; - } - const caseIndent = expectedCaseIndent(node); - - checkNodesIndent(node.consequent, caseIndent + indentSize); - }, - - FunctionDeclaration(node) { - if (isSingleLineNode(node)) { - return; - } - if (options.FunctionDeclaration.parameters === "first" && node.params.length) { - checkNodesIndent(node.params.slice(1), node.params[0].loc.start.column); - } else if (options.FunctionDeclaration.parameters !== null) { - checkNodesIndent(node.params, getNodeIndent(node).goodChar + indentSize * options.FunctionDeclaration.parameters); - } - }, - - FunctionExpression(node) { - if (isSingleLineNode(node)) { - return; - } - if (options.FunctionExpression.parameters === "first" && node.params.length) { - checkNodesIndent(node.params.slice(1), node.params[0].loc.start.column); - } 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/node_modules/eslint/lib/rules/indent.js b/tools/node_modules/eslint/lib/rules/indent.js deleted file mode 100644 index 08b9250f05c09d..00000000000000 --- a/tools/node_modules/eslint/lib/rules/indent.js +++ /dev/null @@ -1,1608 +0,0 @@ -/** - * @fileoverview This rule sets a specific indentation style and width for your code - * - * @author Teddy Katz - * @author Vitaly Puzrin - * @author Gyandeep Singh - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const lodash = require("lodash"); -const astUtils = require("../util/ast-utils"); -const createTree = require("functional-red-black-tree"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -const KNOWN_NODES = new Set([ - "AssignmentExpression", - "AssignmentPattern", - "ArrayExpression", - "ArrayPattern", - "ArrowFunctionExpression", - "AwaitExpression", - "BlockStatement", - "BinaryExpression", - "BreakStatement", - "CallExpression", - "CatchClause", - "ClassBody", - "ClassDeclaration", - "ClassExpression", - "ConditionalExpression", - "ContinueStatement", - "DoWhileStatement", - "DebuggerStatement", - "EmptyStatement", - "ExperimentalRestProperty", - "ExperimentalSpreadProperty", - "ExpressionStatement", - "ForStatement", - "ForInStatement", - "ForOfStatement", - "FunctionDeclaration", - "FunctionExpression", - "Identifier", - "IfStatement", - "Literal", - "LabeledStatement", - "LogicalExpression", - "MemberExpression", - "MetaProperty", - "MethodDefinition", - "NewExpression", - "ObjectExpression", - "ObjectPattern", - "Program", - "Property", - "RestElement", - "ReturnStatement", - "SequenceExpression", - "SpreadElement", - "Super", - "SwitchCase", - "SwitchStatement", - "TaggedTemplateExpression", - "TemplateElement", - "TemplateLiteral", - "ThisExpression", - "ThrowStatement", - "TryStatement", - "UnaryExpression", - "UpdateExpression", - "VariableDeclaration", - "VariableDeclarator", - "WhileStatement", - "WithStatement", - "YieldExpression", - "JSXIdentifier", - "JSXNamespacedName", - "JSXMemberExpression", - "JSXEmptyExpression", - "JSXExpressionContainer", - "JSXElement", - "JSXClosingElement", - "JSXOpeningElement", - "JSXAttribute", - "JSXSpreadAttribute", - "JSXText", - "ExportDefaultDeclaration", - "ExportNamedDeclaration", - "ExportAllDeclaration", - "ExportSpecifier", - "ImportDeclaration", - "ImportSpecifier", - "ImportDefaultSpecifier", - "ImportNamespaceSpecifier" -]); - -/* - * General rule strategy: - * 1. An OffsetStorage instance stores a map of desired offsets, where each token has a specified offset from another - * specified token or to the first column. - * 2. As the AST is traversed, modify the desired offsets of tokens accordingly. For example, when entering a - * BlockStatement, offset all of the tokens in the BlockStatement by 1 indent level from the opening curly - * brace of the BlockStatement. - * 3. After traversing the AST, calculate the expected indentation levels of every token according to the - * OffsetStorage container. - * 4. For each line, compare the expected indentation of the first token to the actual indentation in the file, - * and report the token if the two values are not equal. - */ - - -/** - * A mutable balanced binary search tree that stores (key, value) pairs. The keys are numeric, and must be unique. - * This is intended to be a generic wrapper around a balanced binary search tree library, so that the underlying implementation - * can easily be swapped out. - */ -class BinarySearchTree { - - /** - * Creates an empty tree - */ - constructor() { - this._rbTree = createTree(); - } - - /** - * Inserts an entry into the tree. - * @param {number} key The entry's key - * @param {*} value The entry's value - * @returns {void} - */ - insert(key, value) { - const iterator = this._rbTree.find(key); - - if (iterator.valid) { - this._rbTree = iterator.update(value); - } else { - this._rbTree = this._rbTree.insert(key, value); - } - } - - /** - * Finds the entry with the largest key less than or equal to the provided key - * @param {number} key The provided key - * @returns {{key: number, value: *}|null} The found entry, or null if no such entry exists. - */ - findLe(key) { - const iterator = this._rbTree.le(key); - - return iterator && { key: iterator.key, value: iterator.value }; - } - - /** - * Deletes all of the keys in the interval [start, end) - * @param {number} start The start of the range - * @param {number} end The end of the range - * @returns {void} - */ - deleteRange(start, end) { - - // Exit without traversing the tree if the range has zero size. - if (start === end) { - return; - } - const iterator = this._rbTree.ge(start); - - while (iterator.valid && iterator.key < end) { - this._rbTree = this._rbTree.remove(iterator.key); - iterator.next(); - } - } -} - -/** - * A helper class to get token-based info related to indentation - */ -class TokenInfo { - - /** - * @param {SourceCode} sourceCode A SourceCode object - */ - constructor(sourceCode) { - this.sourceCode = sourceCode; - this.firstTokensByLineNumber = sourceCode.tokensAndComments.reduce((map, token) => { - if (!map.has(token.loc.start.line)) { - map.set(token.loc.start.line, token); - } - if (!map.has(token.loc.end.line) && sourceCode.text.slice(token.range[1] - token.loc.end.column, token.range[1]).trim()) { - map.set(token.loc.end.line, token); - } - return map; - }, new Map()); - } - - /** - * Gets the first token on a given token's line - * @param {Token|ASTNode} token a node or token - * @returns {Token} The first token on the given line - */ - getFirstTokenOfLine(token) { - return this.firstTokensByLineNumber.get(token.loc.start.line); - } - - /** - * Determines whether a token is the first token in its line - * @param {Token} token The token - * @returns {boolean} `true` if the token is the first on its line - */ - isFirstTokenOfLine(token) { - return this.getFirstTokenOfLine(token) === token; - } - - /** - * Get the actual indent of a token - * @param {Token} token Token to examine. This should be the first token on its line. - * @returns {string} The indentation characters that precede the token - */ - getTokenIndent(token) { - return this.sourceCode.text.slice(token.range[0] - token.loc.start.column, token.range[0]); - } -} - -/** - * A class to store information on desired offsets of tokens from each other - */ -class OffsetStorage { - - /** - * @param {TokenInfo} tokenInfo a TokenInfo instance - * @param {number} indentSize The desired size of each indentation level - * @param {string} indentType The indentation character - */ - constructor(tokenInfo, indentSize, indentType) { - this._tokenInfo = tokenInfo; - this._indentSize = indentSize; - this._indentType = indentType; - - this._tree = new BinarySearchTree(); - this._tree.insert(0, { offset: 0, from: null, force: false }); - - this._lockedFirstTokens = new WeakMap(); - this._desiredIndentCache = new WeakMap(); - this._ignoredTokens = new WeakSet(); - } - - _getOffsetDescriptor(token) { - return this._tree.findLe(token.range[0]).value; - } - - /** - * Sets the offset column of token B to match the offset column of token A. - * **WARNING**: This matches a *column*, even if baseToken is not the first token on its line. In - * most cases, `setDesiredOffset` should be used instead. - * @param {Token} baseToken The first token - * @param {Token} offsetToken The second token, whose offset should be matched to the first token - * @returns {void} - */ - matchOffsetOf(baseToken, offsetToken) { - - /* - * lockedFirstTokens is a map from a token whose indentation is controlled by the "first" option to - * the token that it depends on. For example, with the `ArrayExpression: first` option, the first - * token of each element in the array after the first will be mapped to the first token of the first - * element. The desired indentation of each of these tokens is computed based on the desired indentation - * of the "first" element, rather than through the normal offset mechanism. - */ - this._lockedFirstTokens.set(offsetToken, baseToken); - } - - /** - * Sets the desired offset of a token. - * - * This uses a line-based offset collapsing behavior to handle tokens on the same line. - * For example, consider the following two cases: - * - * ( - * [ - * bar - * ] - * ) - * - * ([ - * bar - * ]) - * - * Based on the first case, it's clear that the `bar` token needs to have an offset of 1 indent level (4 spaces) from - * the `[` token, and the `[` token has to have an offset of 1 indent level from the `(` token. Since the `(` token is - * the first on its line (with an indent of 0 spaces), the `bar` token needs to be offset by 2 indent levels (8 spaces) - * from the start of its line. - * - * However, in the second case `bar` should only be indented by 4 spaces. This is because the offset of 1 indent level - * between the `(` and the `[` tokens gets "collapsed" because the two tokens are on the same line. As a result, the - * `(` token is mapped to the `[` token with an offset of 0, and the rule correctly decides that `bar` should be indented - * by 1 indent level from the start of the line. - * - * This is useful because rule listeners can usually just call `setDesiredOffset` for all the tokens in the node, - * without needing to check which lines those tokens are on. - * - * Note that since collapsing only occurs when two tokens are on the same line, there are a few cases where non-intuitive - * behavior can occur. For example, consider the following cases: - * - * foo( - * ). - * bar( - * baz - * ) - * - * foo( - * ).bar( - * baz - * ) - * - * Based on the first example, it would seem that `bar` should be offset by 1 indent level from `foo`, and `baz` - * should be offset by 1 indent level from `bar`. However, this is not correct, because it would result in `baz` - * being indented by 2 indent levels in the second case (since `foo`, `bar`, and `baz` are all on separate lines, no - * collapsing would occur). - * - * Instead, the correct way would be to offset `baz` by 1 level from `bar`, offset `bar` by 1 level from the `)`, and - * offset the `)` by 0 levels from `foo`. This ensures that the offset between `bar` and the `)` are correctly collapsed - * in the second case. - * - * @param {Token} token The token - * @param {Token} fromToken The token that `token` should be offset from - * @param {number} offset The desired indent level - * @returns {void} - */ - setDesiredOffset(token, fromToken, offset) { - return this.setDesiredOffsets(token.range, fromToken, offset); - } - - /** - * Sets the desired offset of all tokens in a range - * It's common for node listeners in this file to need to apply the same offset to a large, contiguous range of tokens. - * Moreover, the offset of any given token is usually updated multiple times (roughly once for each node that contains - * it). This means that the offset of each token is updated O(AST depth) times. - * It would not be performant to store and update the offsets for each token independently, because the rule would end - * up having a time complexity of O(number of tokens * AST depth), which is quite slow for large files. - * - * Instead, the offset tree is represented as a collection of contiguous offset ranges in a file. For example, the following - * list could represent the state of the offset tree at a given point: - * - * * Tokens starting in the interval [0, 15) are aligned with the beginning of the file - * * Tokens starting in the interval [15, 30) are offset by 1 indent level from the `bar` token - * * Tokens starting in the interval [30, 43) are offset by 1 indent level from the `foo` token - * * Tokens starting in the interval [43, 820) are offset by 2 indent levels from the `bar` token - * * Tokens starting in the interval [820, ∞) are offset by 1 indent level from the `baz` token - * - * The `setDesiredOffsets` methods inserts ranges like the ones above. The third line above would be inserted by using: - * `setDesiredOffsets([30, 43], fooToken, 1);` - * - * @param {[number, number]} range A [start, end] pair. All tokens with range[0] <= token.start < range[1] will have the offset applied. - * @param {Token} fromToken The token that this is offset from - * @param {number} offset The desired indent level - * @param {boolean} force `true` if this offset should not use the normal collapsing behavior. This should almost always be false. - * @returns {void} - */ - setDesiredOffsets(range, fromToken, offset, force) { - - /* - * Offset ranges are stored as a collection of nodes, where each node maps a numeric key to an offset - * descriptor. The tree for the example above would have the following nodes: - * - * * key: 0, value: { offset: 0, from: null } - * * key: 15, value: { offset: 1, from: barToken } - * * key: 30, value: { offset: 1, from: fooToken } - * * key: 43, value: { offset: 2, from: barToken } - * * key: 820, value: { offset: 1, from: bazToken } - * - * To find the offset descriptor for any given token, one needs to find the node with the largest key - * which is <= token.start. To make this operation fast, the nodes are stored in a balanced binary - * search tree indexed by key. - */ - - const descriptorToInsert = { offset, from: fromToken, force }; - - const descriptorAfterRange = this._tree.findLe(range[1]).value; - - const fromTokenIsInRange = fromToken && fromToken.range[0] >= range[0] && fromToken.range[1] <= range[1]; - const fromTokenDescriptor = fromTokenIsInRange && this._getOffsetDescriptor(fromToken); - - // First, remove any existing nodes in the range from the tree. - this._tree.deleteRange(range[0] + 1, range[1]); - - // Insert a new node into the tree for this range - this._tree.insert(range[0], descriptorToInsert); - - /* - * To avoid circular offset dependencies, keep the `fromToken` token mapped to whatever it was mapped to previously, - * even if it's in the current range. - */ - if (fromTokenIsInRange) { - this._tree.insert(fromToken.range[0], fromTokenDescriptor); - this._tree.insert(fromToken.range[1], descriptorToInsert); - } - - /* - * To avoid modifying the offset of tokens after the range, insert another node to keep the offset of the following - * tokens the same as it was before. - */ - this._tree.insert(range[1], descriptorAfterRange); - } - - /** - * Gets the desired indent of a token - * @param {Token} token The token - * @returns {string} The desired indent of the token - */ - getDesiredIndent(token) { - if (!this._desiredIndentCache.has(token)) { - - if (this._ignoredTokens.has(token)) { - - /* - * If the token is ignored, use the actual indent of the token as the desired indent. - * This ensures that no errors are reported for this token. - */ - this._desiredIndentCache.set( - token, - this._tokenInfo.getTokenIndent(token) - ); - } else if (this._lockedFirstTokens.has(token)) { - const firstToken = this._lockedFirstTokens.get(token); - - this._desiredIndentCache.set( - token, - - // (indentation for the first element's line) - this.getDesiredIndent(this._tokenInfo.getFirstTokenOfLine(firstToken)) + - - // (space between the start of the first element's line and the first element) - this._indentType.repeat(firstToken.loc.start.column - this._tokenInfo.getFirstTokenOfLine(firstToken).loc.start.column) - ); - } else { - const offsetInfo = this._getOffsetDescriptor(token); - const offset = ( - offsetInfo.from && - offsetInfo.from.loc.start.line === token.loc.start.line && - !/^\s*?\n/.test(token.value) && - !offsetInfo.force - ) ? 0 : offsetInfo.offset * this._indentSize; - - this._desiredIndentCache.set( - token, - (offsetInfo.from ? this.getDesiredIndent(offsetInfo.from) : "") + this._indentType.repeat(offset) - ); - } - } - return this._desiredIndentCache.get(token); - } - - /** - * Ignores a token, preventing it from being reported. - * @param {Token} token The token - * @returns {void} - */ - ignoreToken(token) { - if (this._tokenInfo.isFirstTokenOfLine(token)) { - this._ignoredTokens.add(token); - } - } - - /** - * Gets the first token that the given token's indentation is dependent on - * @param {Token} token The token - * @returns {Token} The token that the given token depends on, or `null` if the given token is at the top level - */ - getFirstDependency(token) { - return this._getOffsetDescriptor(token).from; - } -} - -const ELEMENT_LIST_SCHEMA = { - oneOf: [ - { - type: "integer", - minimum: 0 - }, - { - enum: ["first", "off"] - } - ] -}; - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce consistent indentation", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/indent" - }, - - fixable: "whitespace", - - schema: [ - { - oneOf: [ - { - enum: ["tab"] - }, - { - type: "integer", - minimum: 0 - } - ] - }, - { - type: "object", - properties: { - SwitchCase: { - type: "integer", - minimum: 0, - default: 0 - }, - VariableDeclarator: { - oneOf: [ - ELEMENT_LIST_SCHEMA, - { - type: "object", - properties: { - var: ELEMENT_LIST_SCHEMA, - let: ELEMENT_LIST_SCHEMA, - const: ELEMENT_LIST_SCHEMA - }, - additionalProperties: false - } - ] - }, - outerIIFEBody: { - type: "integer", - minimum: 0 - }, - MemberExpression: { - oneOf: [ - { - type: "integer", - minimum: 0 - }, - { - enum: ["off"] - } - ] - }, - FunctionDeclaration: { - type: "object", - properties: { - parameters: ELEMENT_LIST_SCHEMA, - body: { - type: "integer", - minimum: 0 - } - }, - additionalProperties: false - }, - FunctionExpression: { - type: "object", - properties: { - parameters: ELEMENT_LIST_SCHEMA, - body: { - type: "integer", - minimum: 0 - } - }, - additionalProperties: false - }, - CallExpression: { - type: "object", - properties: { - arguments: ELEMENT_LIST_SCHEMA - }, - additionalProperties: false - }, - ArrayExpression: ELEMENT_LIST_SCHEMA, - ObjectExpression: ELEMENT_LIST_SCHEMA, - ImportDeclaration: ELEMENT_LIST_SCHEMA, - flatTernaryExpressions: { - type: "boolean", - default: false - }, - ignoredNodes: { - type: "array", - items: { - type: "string", - not: { - pattern: ":exit$" - } - } - }, - ignoreComments: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - messages: { - wrongIndentation: "Expected indentation of {{expected}} but found {{actual}}." - } - }, - - create(context) { - const DEFAULT_VARIABLE_INDENT = 1; - const DEFAULT_PARAMETER_INDENT = 1; - const DEFAULT_FUNCTION_BODY_INDENT = 1; - - let indentType = "space"; - let indentSize = 4; - const options = { - SwitchCase: 0, - VariableDeclarator: { - var: DEFAULT_VARIABLE_INDENT, - let: DEFAULT_VARIABLE_INDENT, - const: DEFAULT_VARIABLE_INDENT - }, - outerIIFEBody: 1, - FunctionDeclaration: { - parameters: DEFAULT_PARAMETER_INDENT, - body: DEFAULT_FUNCTION_BODY_INDENT - }, - FunctionExpression: { - parameters: DEFAULT_PARAMETER_INDENT, - body: DEFAULT_FUNCTION_BODY_INDENT - }, - CallExpression: { - arguments: DEFAULT_PARAMETER_INDENT - }, - MemberExpression: 1, - ArrayExpression: 1, - ObjectExpression: 1, - ImportDeclaration: 1, - flatTernaryExpressions: false, - ignoredNodes: [], - ignoreComments: false - }; - - if (context.options.length) { - if (context.options[0] === "tab") { - indentSize = 1; - indentType = "tab"; - } else { - indentSize = context.options[0]; - indentType = "space"; - } - - if (context.options[1]) { - Object.assign(options, context.options[1]); - - if (typeof options.VariableDeclarator === "number" || options.VariableDeclarator === "first") { - options.VariableDeclarator = { - var: options.VariableDeclarator, - let: options.VariableDeclarator, - const: options.VariableDeclarator - }; - } - } - } - - const sourceCode = context.getSourceCode(); - const tokenInfo = new TokenInfo(sourceCode); - const offsets = new OffsetStorage(tokenInfo, indentSize, indentType === "space" ? " " : "\t"); - const parameterParens = new WeakSet(); - - /** - * Creates an error message for a line, given the expected/actual indentation. - * @param {int} expectedAmount The expected amount of indentation characters for this line - * @param {int} actualSpaces The actual number of indentation spaces that were found on this line - * @param {int} actualTabs The actual number of indentation tabs that were found on this line - * @returns {string} An error message for this line - */ - function createErrorMessageData(expectedAmount, actualSpaces, actualTabs) { - const expectedStatement = `${expectedAmount} ${indentType}${expectedAmount === 1 ? "" : "s"}`; // e.g. "2 tabs" - const foundSpacesWord = `space${actualSpaces === 1 ? "" : "s"}`; // e.g. "space" - const foundTabsWord = `tab${actualTabs === 1 ? "" : "s"}`; // e.g. "tabs" - let foundStatement; - - if (actualSpaces > 0) { - - /* - * Abbreviate the message if the expected indentation is also spaces. - * e.g. 'Expected 4 spaces but found 2' rather than 'Expected 4 spaces but found 2 spaces' - */ - foundStatement = indentType === "space" ? actualSpaces : `${actualSpaces} ${foundSpacesWord}`; - } else if (actualTabs > 0) { - foundStatement = indentType === "tab" ? actualTabs : `${actualTabs} ${foundTabsWord}`; - } else { - foundStatement = "0"; - } - return { - expected: expectedStatement, - actual: foundStatement - }; - } - - /** - * Reports a given indent violation - * @param {Token} token Token violating the indent rule - * @param {string} neededIndent Expected indentation string - * @returns {void} - */ - function report(token, neededIndent) { - const actualIndent = Array.from(tokenInfo.getTokenIndent(token)); - const numSpaces = actualIndent.filter(char => char === " ").length; - const numTabs = actualIndent.filter(char => char === "\t").length; - - context.report({ - node: token, - messageId: "wrongIndentation", - data: createErrorMessageData(neededIndent.length, numSpaces, numTabs), - loc: { - start: { line: token.loc.start.line, column: 0 }, - end: { line: token.loc.start.line, column: token.loc.start.column } - }, - fix(fixer) { - const range = [token.range[0] - token.loc.start.column, token.range[0]]; - const newText = neededIndent; - - return fixer.replaceTextRange(range, newText); - } - }); - } - - /** - * Checks if a token's indentation is correct - * @param {Token} token Token to examine - * @param {string} desiredIndent Desired indentation of the string - * @returns {boolean} `true` if the token's indentation is correct - */ - function validateTokenIndent(token, desiredIndent) { - const indentation = tokenInfo.getTokenIndent(token); - - return indentation === desiredIndent || - - // To avoid conflicts with no-mixed-spaces-and-tabs, don't report mixed spaces and tabs. - indentation.includes(" ") && indentation.includes("\t"); - } - - /** - * Check to see if the node is a file level IIFE - * @param {ASTNode} node The function node to check. - * @returns {boolean} True if the node is the outer IIFE - */ - function isOuterIIFE(node) { - - /* - * Verify that the node is an IIFE - */ - if (!node.parent || node.parent.type !== "CallExpression" || node.parent.callee !== node) { - return false; - } - - /* - * Navigate legal ancestors to determine whether this IIFE is outer. - * A "legal ancestor" is an expression or statement that causes the function to get executed immediately. - * For example, `!(function(){})()` is an outer IIFE even though it is preceded by a ! operator. - */ - let statement = node.parent && node.parent.parent; - - while ( - statement.type === "UnaryExpression" && ["!", "~", "+", "-"].indexOf(statement.operator) > -1 || - statement.type === "AssignmentExpression" || - statement.type === "LogicalExpression" || - statement.type === "SequenceExpression" || - statement.type === "VariableDeclarator" - ) { - statement = statement.parent; - } - - return (statement.type === "ExpressionStatement" || statement.type === "VariableDeclaration") && statement.parent.type === "Program"; - } - - /** - * Counts the number of linebreaks that follow the last non-whitespace character in a string - * @param {string} string The string to check - * @returns {number} The number of JavaScript linebreaks that follow the last non-whitespace character, - * or the total number of linebreaks if the string is all whitespace. - */ - function countTrailingLinebreaks(string) { - const trailingWhitespace = string.match(/\s*$/)[0]; - const linebreakMatches = trailingWhitespace.match(astUtils.createGlobalLinebreakMatcher()); - - return linebreakMatches === null ? 0 : linebreakMatches.length; - } - - /** - * Check indentation for lists of elements (arrays, objects, function params) - * @param {ASTNode[]} elements List of elements that should be offset - * @param {Token} startToken The start token of the list that element should be aligned against, e.g. '[' - * @param {Token} endToken The end token of the list, e.g. ']' - * @param {number|string} offset The amount that the elements should be offset - * @returns {void} - */ - function addElementListIndent(elements, startToken, endToken, offset) { - - /** - * Gets the first token of a given element, including surrounding parentheses. - * @param {ASTNode} element A node in the `elements` list - * @returns {Token} The first token of this element - */ - function getFirstToken(element) { - let token = sourceCode.getTokenBefore(element); - - while (astUtils.isOpeningParenToken(token) && token !== startToken) { - token = sourceCode.getTokenBefore(token); - } - return sourceCode.getTokenAfter(token); - } - - // Run through all the tokens in the list, and offset them by one indent level (mainly for comments, other things will end up overridden) - offsets.setDesiredOffsets( - [startToken.range[1], endToken.range[0]], - startToken, - typeof offset === "number" ? offset : 1 - ); - offsets.setDesiredOffset(endToken, startToken, 0); - - // If the preference is "first" but there is no first element (e.g. sparse arrays w/ empty first slot), fall back to 1 level. - if (offset === "first" && elements.length && !elements[0]) { - return; - } - elements.forEach((element, index) => { - if (!element) { - - // Skip holes in arrays - return; - } - if (offset === "off") { - - // Ignore the first token of every element if the "off" option is used - offsets.ignoreToken(getFirstToken(element)); - } - - // Offset the following elements correctly relative to the first element - if (index === 0) { - return; - } - if (offset === "first" && tokenInfo.isFirstTokenOfLine(getFirstToken(element))) { - offsets.matchOffsetOf(getFirstToken(elements[0]), getFirstToken(element)); - } else { - const previousElement = elements[index - 1]; - const firstTokenOfPreviousElement = previousElement && getFirstToken(previousElement); - const previousElementLastToken = previousElement && sourceCode.getLastToken(previousElement); - - if ( - previousElement && - previousElementLastToken.loc.end.line - countTrailingLinebreaks(previousElementLastToken.value) > startToken.loc.end.line - ) { - offsets.setDesiredOffsets( - [previousElement.range[1], element.range[1]], - firstTokenOfPreviousElement, - 0 - ); - } - } - }); - } - - /** - * Check and decide whether to check for indentation for blockless nodes - * Scenarios are for or while statements without braces around them - * @param {ASTNode} node node to examine - * @returns {void} - */ - function addBlocklessNodeIndent(node) { - if (node.type !== "BlockStatement") { - const lastParentToken = sourceCode.getTokenBefore(node, astUtils.isNotOpeningParenToken); - - let firstBodyToken = sourceCode.getFirstToken(node); - let lastBodyToken = sourceCode.getLastToken(node); - - while ( - astUtils.isOpeningParenToken(sourceCode.getTokenBefore(firstBodyToken)) && - astUtils.isClosingParenToken(sourceCode.getTokenAfter(lastBodyToken)) - ) { - firstBodyToken = sourceCode.getTokenBefore(firstBodyToken); - lastBodyToken = sourceCode.getTokenAfter(lastBodyToken); - } - - offsets.setDesiredOffsets([firstBodyToken.range[0], lastBodyToken.range[1]], lastParentToken, 1); - - /* - * For blockless nodes with semicolon-first style, don't indent the semicolon. - * e.g. - * if (foo) bar() - * ; [1, 2, 3].map(foo) - */ - const lastToken = sourceCode.getLastToken(node); - - if (node.type !== "EmptyStatement" && astUtils.isSemicolonToken(lastToken)) { - offsets.setDesiredOffset(lastToken, lastParentToken, 0); - } - } - } - - /** - * Checks the indentation for nodes that are like function calls (`CallExpression` and `NewExpression`) - * @param {ASTNode} node A CallExpression or NewExpression node - * @returns {void} - */ - function addFunctionCallIndent(node) { - let openingParen; - - if (node.arguments.length) { - openingParen = sourceCode.getFirstTokenBetween(node.callee, node.arguments[0], astUtils.isOpeningParenToken); - } else { - openingParen = sourceCode.getLastToken(node, 1); - } - const closingParen = sourceCode.getLastToken(node); - - parameterParens.add(openingParen); - parameterParens.add(closingParen); - offsets.setDesiredOffset(openingParen, sourceCode.getTokenBefore(openingParen), 0); - - addElementListIndent(node.arguments, openingParen, closingParen, options.CallExpression.arguments); - } - - /** - * Checks the indentation of parenthesized values, given a list of tokens in a program - * @param {Token[]} tokens A list of tokens - * @returns {void} - */ - function addParensIndent(tokens) { - const parenStack = []; - const parenPairs = []; - - tokens.forEach(nextToken => { - - // Accumulate a list of parenthesis pairs - if (astUtils.isOpeningParenToken(nextToken)) { - parenStack.push(nextToken); - } else if (astUtils.isClosingParenToken(nextToken)) { - parenPairs.unshift({ left: parenStack.pop(), right: nextToken }); - } - }); - - parenPairs.forEach(pair => { - const leftParen = pair.left; - const rightParen = pair.right; - - // We only want to handle parens around expressions, so exclude parentheses that are in function parameters and function call arguments. - if (!parameterParens.has(leftParen) && !parameterParens.has(rightParen)) { - const parenthesizedTokens = new Set(sourceCode.getTokensBetween(leftParen, rightParen)); - - parenthesizedTokens.forEach(token => { - if (!parenthesizedTokens.has(offsets.getFirstDependency(token))) { - offsets.setDesiredOffset(token, leftParen, 1); - } - }); - } - - offsets.setDesiredOffset(rightParen, leftParen, 0); - }); - } - - /** - * Ignore all tokens within an unknown node whose offset do not depend - * on another token's offset within the unknown node - * @param {ASTNode} node Unknown Node - * @returns {void} - */ - function ignoreNode(node) { - const unknownNodeTokens = new Set(sourceCode.getTokens(node, { includeComments: true })); - - unknownNodeTokens.forEach(token => { - if (!unknownNodeTokens.has(offsets.getFirstDependency(token))) { - const firstTokenOfLine = tokenInfo.getFirstTokenOfLine(token); - - if (token === firstTokenOfLine) { - offsets.ignoreToken(token); - } else { - offsets.setDesiredOffset(token, firstTokenOfLine, 0); - } - } - }); - } - - /** - * Check whether the given token is on the first line of a statement. - * @param {Token} token The token to check. - * @param {ASTNode} leafNode The expression node that the token belongs directly. - * @returns {boolean} `true` if the token is on the first line of a statement. - */ - function isOnFirstLineOfStatement(token, leafNode) { - let node = leafNode; - - while (node.parent && !node.parent.type.endsWith("Statement") && !node.parent.type.endsWith("Declaration")) { - node = node.parent; - } - node = node.parent; - - return !node || node.loc.start.line === token.loc.start.line; - } - - /** - * Check whether there are any blank (whitespace-only) lines between - * two tokens on separate lines. - * @param {Token} firstToken The first token. - * @param {Token} secondToken The second token. - * @returns {boolean} `true` if the tokens are on separate lines and - * there exists a blank line between them, `false` otherwise. - */ - function hasBlankLinesBetween(firstToken, secondToken) { - const firstTokenLine = firstToken.loc.end.line; - const secondTokenLine = secondToken.loc.start.line; - - if (firstTokenLine === secondTokenLine || firstTokenLine === secondTokenLine - 1) { - return false; - } - - for (let line = firstTokenLine + 1; line < secondTokenLine; ++line) { - if (!tokenInfo.firstTokensByLineNumber.has(line)) { - return true; - } - } - - return false; - } - - const ignoredNodeFirstTokens = new Set(); - - const baseOffsetListeners = { - "ArrayExpression, ArrayPattern"(node) { - const openingBracket = sourceCode.getFirstToken(node); - const closingBracket = sourceCode.getTokenAfter(lodash.findLast(node.elements) || openingBracket, astUtils.isClosingBracketToken); - - addElementListIndent(node.elements, openingBracket, closingBracket, options.ArrayExpression); - }, - - "ObjectExpression, ObjectPattern"(node) { - const openingCurly = sourceCode.getFirstToken(node); - const closingCurly = sourceCode.getTokenAfter( - node.properties.length ? node.properties[node.properties.length - 1] : openingCurly, - astUtils.isClosingBraceToken - ); - - addElementListIndent(node.properties, openingCurly, closingCurly, options.ObjectExpression); - }, - - ArrowFunctionExpression(node) { - const firstToken = sourceCode.getFirstToken(node); - - if (astUtils.isOpeningParenToken(firstToken)) { - const openingParen = firstToken; - const closingParen = sourceCode.getTokenBefore(node.body, astUtils.isClosingParenToken); - - parameterParens.add(openingParen); - parameterParens.add(closingParen); - addElementListIndent(node.params, openingParen, closingParen, options.FunctionExpression.parameters); - } - addBlocklessNodeIndent(node.body); - }, - - AssignmentExpression(node) { - const operator = sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator); - - offsets.setDesiredOffsets([operator.range[0], node.range[1]], sourceCode.getLastToken(node.left), 1); - offsets.ignoreToken(operator); - offsets.ignoreToken(sourceCode.getTokenAfter(operator)); - }, - - "BinaryExpression, LogicalExpression"(node) { - const operator = sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator); - - /* - * For backwards compatibility, don't check BinaryExpression indents, e.g. - * var foo = bar && - * baz; - */ - - const tokenAfterOperator = sourceCode.getTokenAfter(operator); - - offsets.ignoreToken(operator); - offsets.ignoreToken(tokenAfterOperator); - offsets.setDesiredOffset(tokenAfterOperator, operator, 0); - }, - - "BlockStatement, ClassBody"(node) { - - let blockIndentLevel; - - if (node.parent && isOuterIIFE(node.parent)) { - blockIndentLevel = options.outerIIFEBody; - } else if (node.parent && (node.parent.type === "FunctionExpression" || node.parent.type === "ArrowFunctionExpression")) { - blockIndentLevel = options.FunctionExpression.body; - } else if (node.parent && node.parent.type === "FunctionDeclaration") { - blockIndentLevel = options.FunctionDeclaration.body; - } else { - blockIndentLevel = 1; - } - - /* - * For blocks that aren't lone statements, ensure that the opening curly brace - * is aligned with the parent. - */ - if (!astUtils.STATEMENT_LIST_PARENTS.has(node.parent.type)) { - offsets.setDesiredOffset(sourceCode.getFirstToken(node), sourceCode.getFirstToken(node.parent), 0); - } - addElementListIndent(node.body, sourceCode.getFirstToken(node), sourceCode.getLastToken(node), blockIndentLevel); - }, - - CallExpression: addFunctionCallIndent, - - - "ClassDeclaration[superClass], ClassExpression[superClass]"(node) { - const classToken = sourceCode.getFirstToken(node); - const extendsToken = sourceCode.getTokenBefore(node.superClass, astUtils.isNotOpeningParenToken); - - offsets.setDesiredOffsets([extendsToken.range[0], node.body.range[0]], classToken, 1); - }, - - ConditionalExpression(node) { - const firstToken = sourceCode.getFirstToken(node); - - // `flatTernaryExpressions` option is for the following style: - // var a = - // foo > 0 ? bar : - // foo < 0 ? baz : - // /*else*/ qiz ; - if (!options.flatTernaryExpressions || - !astUtils.isTokenOnSameLine(node.test, node.consequent) || - isOnFirstLineOfStatement(firstToken, node) - ) { - const questionMarkToken = sourceCode.getFirstTokenBetween(node.test, node.consequent, token => token.type === "Punctuator" && token.value === "?"); - const colonToken = sourceCode.getFirstTokenBetween(node.consequent, node.alternate, token => token.type === "Punctuator" && token.value === ":"); - - const firstConsequentToken = sourceCode.getTokenAfter(questionMarkToken); - const lastConsequentToken = sourceCode.getTokenBefore(colonToken); - const firstAlternateToken = sourceCode.getTokenAfter(colonToken); - - offsets.setDesiredOffset(questionMarkToken, firstToken, 1); - offsets.setDesiredOffset(colonToken, firstToken, 1); - - offsets.setDesiredOffset(firstConsequentToken, firstToken, 1); - - /* - * The alternate and the consequent should usually have the same indentation. - * If they share part of a line, align the alternate against the first token of the consequent. - * This allows the alternate to be indented correctly in cases like this: - * foo ? ( - * bar - * ) : ( // this '(' is aligned with the '(' above, so it's considered to be aligned with `foo` - * baz // as a result, `baz` is offset by 1 rather than 2 - * ) - */ - if (lastConsequentToken.loc.end.line === firstAlternateToken.loc.start.line) { - offsets.setDesiredOffset(firstAlternateToken, firstConsequentToken, 0); - } else { - - /** - * If the alternate and consequent do not share part of a line, offset the alternate from the first - * token of the conditional expression. For example: - * foo ? bar - * : baz - * - * If `baz` were aligned with `bar` rather than being offset by 1 from `foo`, `baz` would end up - * having no expected indentation. - */ - offsets.setDesiredOffset(firstAlternateToken, firstToken, 1); - } - } - }, - - "DoWhileStatement, WhileStatement, ForInStatement, ForOfStatement": node => addBlocklessNodeIndent(node.body), - - ExportNamedDeclaration(node) { - if (node.declaration === null) { - const closingCurly = sourceCode.getLastToken(node, astUtils.isClosingBraceToken); - - // Indent the specifiers in `export {foo, bar, baz}` - addElementListIndent(node.specifiers, sourceCode.getFirstToken(node, { skip: 1 }), closingCurly, 1); - - if (node.source) { - - // Indent everything after and including the `from` token in `export {foo, bar, baz} from 'qux'` - offsets.setDesiredOffsets([closingCurly.range[1], node.range[1]], sourceCode.getFirstToken(node), 1); - } - } - }, - - ForStatement(node) { - const forOpeningParen = sourceCode.getFirstToken(node, 1); - - if (node.init) { - offsets.setDesiredOffsets(node.init.range, forOpeningParen, 1); - } - if (node.test) { - offsets.setDesiredOffsets(node.test.range, forOpeningParen, 1); - } - if (node.update) { - offsets.setDesiredOffsets(node.update.range, forOpeningParen, 1); - } - addBlocklessNodeIndent(node.body); - }, - - "FunctionDeclaration, FunctionExpression"(node) { - const closingParen = sourceCode.getTokenBefore(node.body); - const openingParen = sourceCode.getTokenBefore(node.params.length ? node.params[0] : closingParen); - - parameterParens.add(openingParen); - parameterParens.add(closingParen); - addElementListIndent(node.params, openingParen, closingParen, options[node.type].parameters); - }, - - IfStatement(node) { - addBlocklessNodeIndent(node.consequent); - if (node.alternate && node.alternate.type !== "IfStatement") { - addBlocklessNodeIndent(node.alternate); - } - }, - - ImportDeclaration(node) { - if (node.specifiers.some(specifier => specifier.type === "ImportSpecifier")) { - const openingCurly = sourceCode.getFirstToken(node, astUtils.isOpeningBraceToken); - const closingCurly = sourceCode.getLastToken(node, astUtils.isClosingBraceToken); - - addElementListIndent(node.specifiers.filter(specifier => specifier.type === "ImportSpecifier"), openingCurly, closingCurly, options.ImportDeclaration); - } - - const fromToken = sourceCode.getLastToken(node, token => token.type === "Identifier" && token.value === "from"); - const sourceToken = sourceCode.getLastToken(node, token => token.type === "String"); - const semiToken = sourceCode.getLastToken(node, token => token.type === "Punctuator" && token.value === ";"); - - if (fromToken) { - const end = semiToken && semiToken.range[1] === sourceToken.range[1] ? node.range[1] : sourceToken.range[1]; - - offsets.setDesiredOffsets([fromToken.range[0], end], sourceCode.getFirstToken(node), 1); - } - }, - - "MemberExpression, JSXMemberExpression, MetaProperty"(node) { - const object = node.type === "MetaProperty" ? node.meta : node.object; - const firstNonObjectToken = sourceCode.getFirstTokenBetween(object, node.property, astUtils.isNotClosingParenToken); - const secondNonObjectToken = sourceCode.getTokenAfter(firstNonObjectToken); - - const objectParenCount = sourceCode.getTokensBetween(object, node.property, { filter: astUtils.isClosingParenToken }).length; - const firstObjectToken = objectParenCount - ? sourceCode.getTokenBefore(object, { skip: objectParenCount - 1 }) - : sourceCode.getFirstToken(object); - const lastObjectToken = sourceCode.getTokenBefore(firstNonObjectToken); - const firstPropertyToken = node.computed ? firstNonObjectToken : secondNonObjectToken; - - if (node.computed) { - - // For computed MemberExpressions, match the closing bracket with the opening bracket. - offsets.setDesiredOffset(sourceCode.getLastToken(node), firstNonObjectToken, 0); - offsets.setDesiredOffsets(node.property.range, firstNonObjectToken, 1); - } - - /* - * If the object ends on the same line that the property starts, match against the last token - * of the object, to ensure that the MemberExpression is not indented. - * - * Otherwise, match against the first token of the object, e.g. - * foo - * .bar - * .baz // <-- offset by 1 from `foo` - */ - const offsetBase = lastObjectToken.loc.end.line === firstPropertyToken.loc.start.line - ? lastObjectToken - : firstObjectToken; - - if (typeof options.MemberExpression === "number") { - - // Match the dot (for non-computed properties) or the opening bracket (for computed properties) against the object. - offsets.setDesiredOffset(firstNonObjectToken, offsetBase, options.MemberExpression); - - /* - * For computed MemberExpressions, match the first token of the property against the opening bracket. - * Otherwise, match the first token of the property against the object. - */ - offsets.setDesiredOffset(secondNonObjectToken, node.computed ? firstNonObjectToken : offsetBase, options.MemberExpression); - } else { - - // If the MemberExpression option is off, ignore the dot and the first token of the property. - offsets.ignoreToken(firstNonObjectToken); - offsets.ignoreToken(secondNonObjectToken); - - // To ignore the property indentation, ensure that the property tokens depend on the ignored tokens. - offsets.setDesiredOffset(firstNonObjectToken, offsetBase, 0); - offsets.setDesiredOffset(secondNonObjectToken, firstNonObjectToken, 0); - } - }, - - NewExpression(node) { - - // Only indent the arguments if the NewExpression has parens (e.g. `new Foo(bar)` or `new Foo()`, but not `new Foo` - if (node.arguments.length > 0 || - astUtils.isClosingParenToken(sourceCode.getLastToken(node)) && - astUtils.isOpeningParenToken(sourceCode.getLastToken(node, 1))) { - addFunctionCallIndent(node); - } - }, - - Property(node) { - if (!node.shorthand && !node.method && node.kind === "init") { - const colon = sourceCode.getFirstTokenBetween(node.key, node.value, astUtils.isColonToken); - - offsets.ignoreToken(sourceCode.getTokenAfter(colon)); - } - }, - - SwitchStatement(node) { - const openingCurly = sourceCode.getTokenAfter(node.discriminant, astUtils.isOpeningBraceToken); - const closingCurly = sourceCode.getLastToken(node); - - offsets.setDesiredOffsets([openingCurly.range[1], closingCurly.range[0]], openingCurly, options.SwitchCase); - - if (node.cases.length) { - sourceCode.getTokensBetween( - node.cases[node.cases.length - 1], - closingCurly, - { includeComments: true, filter: astUtils.isCommentToken } - ).forEach(token => offsets.ignoreToken(token)); - } - }, - - SwitchCase(node) { - if (!(node.consequent.length === 1 && node.consequent[0].type === "BlockStatement")) { - const caseKeyword = sourceCode.getFirstToken(node); - const tokenAfterCurrentCase = sourceCode.getTokenAfter(node); - - offsets.setDesiredOffsets([caseKeyword.range[1], tokenAfterCurrentCase.range[0]], caseKeyword, 1); - } - }, - - TemplateLiteral(node) { - node.expressions.forEach((expression, index) => { - const previousQuasi = node.quasis[index]; - const nextQuasi = node.quasis[index + 1]; - const tokenToAlignFrom = previousQuasi.loc.start.line === previousQuasi.loc.end.line - ? sourceCode.getFirstToken(previousQuasi) - : null; - - offsets.setDesiredOffsets([previousQuasi.range[1], nextQuasi.range[0]], tokenToAlignFrom, 1); - offsets.setDesiredOffset(sourceCode.getFirstToken(nextQuasi), tokenToAlignFrom, 0); - }); - }, - - VariableDeclaration(node) { - let variableIndent = Object.prototype.hasOwnProperty.call(options.VariableDeclarator, node.kind) - ? options.VariableDeclarator[node.kind] - : DEFAULT_VARIABLE_INDENT; - - const firstToken = sourceCode.getFirstToken(node), - lastToken = sourceCode.getLastToken(node); - - if (options.VariableDeclarator[node.kind] === "first") { - if (node.declarations.length > 1) { - addElementListIndent( - node.declarations, - firstToken, - lastToken, - "first" - ); - return; - } - - variableIndent = DEFAULT_VARIABLE_INDENT; - } - - if (node.declarations[node.declarations.length - 1].loc.start.line > node.loc.start.line) { - - /* - * VariableDeclarator indentation is a bit different from other forms of indentation, in that the - * indentation of an opening bracket sometimes won't match that of a closing bracket. For example, - * the following indentations are correct: - * - * var foo = { - * ok: true - * }; - * - * var foo = { - * ok: true, - * }, - * bar = 1; - * - * Account for when exiting the AST (after indentations have already been set for the nodes in - * the declaration) by manually increasing the indentation level of the tokens in this declarator - * on the same line as the start of the declaration, provided that there are declarators that - * follow this one. - */ - offsets.setDesiredOffsets(node.range, firstToken, variableIndent, true); - } else { - offsets.setDesiredOffsets(node.range, firstToken, variableIndent); - } - - if (astUtils.isSemicolonToken(lastToken)) { - offsets.ignoreToken(lastToken); - } - }, - - VariableDeclarator(node) { - if (node.init) { - const equalOperator = sourceCode.getTokenBefore(node.init, astUtils.isNotOpeningParenToken); - const tokenAfterOperator = sourceCode.getTokenAfter(equalOperator); - - offsets.ignoreToken(equalOperator); - offsets.ignoreToken(tokenAfterOperator); - offsets.setDesiredOffsets([tokenAfterOperator.range[0], node.range[1]], equalOperator, 1); - offsets.setDesiredOffset(equalOperator, sourceCode.getLastToken(node.id), 0); - } - }, - - "JSXAttribute[value]"(node) { - const equalsToken = sourceCode.getFirstTokenBetween(node.name, node.value, token => token.type === "Punctuator" && token.value === "="); - - offsets.setDesiredOffsets([equalsToken.range[0], node.value.range[1]], sourceCode.getFirstToken(node.name), 1); - }, - - JSXElement(node) { - if (node.closingElement) { - addElementListIndent(node.children, sourceCode.getFirstToken(node.openingElement), sourceCode.getFirstToken(node.closingElement), 1); - } - }, - - JSXOpeningElement(node) { - const firstToken = sourceCode.getFirstToken(node); - let closingToken; - - if (node.selfClosing) { - closingToken = sourceCode.getLastToken(node, { skip: 1 }); - offsets.setDesiredOffset(sourceCode.getLastToken(node), closingToken, 0); - } else { - closingToken = sourceCode.getLastToken(node); - } - offsets.setDesiredOffsets(node.name.range, sourceCode.getFirstToken(node)); - addElementListIndent(node.attributes, firstToken, closingToken, 1); - }, - - JSXClosingElement(node) { - const firstToken = sourceCode.getFirstToken(node); - - offsets.setDesiredOffsets(node.name.range, firstToken, 1); - }, - - JSXExpressionContainer(node) { - const openingCurly = sourceCode.getFirstToken(node); - const closingCurly = sourceCode.getLastToken(node); - - offsets.setDesiredOffsets( - [openingCurly.range[1], closingCurly.range[0]], - openingCurly, - 1 - ); - }, - - "*"(node) { - const firstToken = sourceCode.getFirstToken(node); - - // Ensure that the children of every node are indented at least as much as the first token. - if (firstToken && !ignoredNodeFirstTokens.has(firstToken)) { - offsets.setDesiredOffsets(node.range, firstToken, 0); - } - } - }; - - const listenerCallQueue = []; - - /* - * To ignore the indentation of a node: - * 1. Don't call the node's listener when entering it (if it has a listener) - * 2. Don't set any offsets against the first token of the node. - * 3. Call `ignoreNode` on the node sometime after exiting it and before validating offsets. - */ - const offsetListeners = lodash.mapValues( - baseOffsetListeners, - - /* - * Offset listener calls are deferred until traversal is finished, and are called as - * part of the final `Program:exit` listener. This is necessary because a node might - * be matched by multiple selectors. - * - * Example: Suppose there is an offset listener for `Identifier`, and the user has - * specified in configuration that `MemberExpression > Identifier` should be ignored. - * Due to selector specificity rules, the `Identifier` listener will get called first. However, - * if a given Identifier node is supposed to be ignored, then the `Identifier` offset listener - * should not have been called at all. Without doing extra selector matching, we don't know - * whether the Identifier matches the `MemberExpression > Identifier` selector until the - * `MemberExpression > Identifier` listener is called. - * - * To avoid this, the `Identifier` listener isn't called until traversal finishes and all - * ignored nodes are known. - */ - listener => - node => - listenerCallQueue.push({ listener, node }) - ); - - // For each ignored node selector, set up a listener to collect it into the `ignoredNodes` set. - const ignoredNodes = new Set(); - - /** - * Ignores a node - * @param {ASTNode} node The node to ignore - * @returns {void} - */ - function addToIgnoredNodes(node) { - ignoredNodes.add(node); - ignoredNodeFirstTokens.add(sourceCode.getFirstToken(node)); - } - - const ignoredNodeListeners = options.ignoredNodes.reduce( - (listeners, ignoredSelector) => Object.assign(listeners, { [ignoredSelector]: addToIgnoredNodes }), - {} - ); - - /* - * Join the listeners, and add a listener to verify that all tokens actually have the correct indentation - * at the end. - * - * Using Object.assign will cause some offset listeners to be overwritten if the same selector also appears - * in `ignoredNodeListeners`. This isn't a problem because all of the matching nodes will be ignored, - * so those listeners wouldn't be called anyway. - */ - return Object.assign( - offsetListeners, - ignoredNodeListeners, - { - "*:exit"(node) { - - // If a node's type is nonstandard, we can't tell how its children should be offset, so ignore it. - if (!KNOWN_NODES.has(node.type)) { - addToIgnoredNodes(node); - } - }, - "Program:exit"() { - - // If ignoreComments option is enabled, ignore all comment tokens. - if (options.ignoreComments) { - sourceCode.getAllComments() - .forEach(comment => offsets.ignoreToken(comment)); - } - - // Invoke the queued offset listeners for the nodes that aren't ignored. - listenerCallQueue - .filter(nodeInfo => !ignoredNodes.has(nodeInfo.node)) - .forEach(nodeInfo => nodeInfo.listener(nodeInfo.node)); - - // Update the offsets for ignored nodes to prevent their child tokens from being reported. - ignoredNodes.forEach(ignoreNode); - - addParensIndent(sourceCode.ast.tokens); - - /* - * Create a Map from (tokenOrComment) => (precedingToken). - * This is necessary because sourceCode.getTokenBefore does not handle a comment as an argument correctly. - */ - const precedingTokens = sourceCode.ast.comments.reduce((commentMap, comment) => { - const tokenOrCommentBefore = sourceCode.getTokenBefore(comment, { includeComments: true }); - - return commentMap.set(comment, commentMap.has(tokenOrCommentBefore) ? commentMap.get(tokenOrCommentBefore) : tokenOrCommentBefore); - }, new WeakMap()); - - sourceCode.lines.forEach((line, lineIndex) => { - const lineNumber = lineIndex + 1; - - if (!tokenInfo.firstTokensByLineNumber.has(lineNumber)) { - - // Don't check indentation on blank lines - return; - } - - const firstTokenOfLine = tokenInfo.firstTokensByLineNumber.get(lineNumber); - - if (firstTokenOfLine.loc.start.line !== lineNumber) { - - // Don't check the indentation of multi-line tokens (e.g. template literals or block comments) twice. - return; - } - - // If the token matches the expected expected indentation, don't report it. - if (validateTokenIndent(firstTokenOfLine, offsets.getDesiredIndent(firstTokenOfLine))) { - return; - } - - if (astUtils.isCommentToken(firstTokenOfLine)) { - const tokenBefore = precedingTokens.get(firstTokenOfLine); - const tokenAfter = tokenBefore ? sourceCode.getTokenAfter(tokenBefore) : sourceCode.ast.tokens[0]; - - const mayAlignWithBefore = tokenBefore && !hasBlankLinesBetween(tokenBefore, firstTokenOfLine); - const mayAlignWithAfter = tokenAfter && !hasBlankLinesBetween(firstTokenOfLine, tokenAfter); - - // If a comment matches the expected indentation of the token immediately before or after, don't report it. - if ( - mayAlignWithBefore && validateTokenIndent(firstTokenOfLine, offsets.getDesiredIndent(tokenBefore)) || - mayAlignWithAfter && validateTokenIndent(firstTokenOfLine, offsets.getDesiredIndent(tokenAfter)) - ) { - return; - } - } - - // Otherwise, report the token/comment. - report(firstTokenOfLine, offsets.getDesiredIndent(firstTokenOfLine)); - }); - } - } - ); - } -}; diff --git a/tools/node_modules/eslint/lib/rules/init-declarations.js b/tools/node_modules/eslint/lib/rules/init-declarations.js deleted file mode 100644 index 484cbef0a57c4c..00000000000000 --- a/tools/node_modules/eslint/lib/rules/init-declarations.js +++ /dev/null @@ -1,140 +0,0 @@ -/** - * @fileoverview A rule to control the style of variable initializations. - * @author Colin Ihrig - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks whether or not a given node is a for loop. - * @param {ASTNode} block - A node to check. - * @returns {boolean} `true` when the node is a for loop. - */ -function isForLoop(block) { - return block.type === "ForInStatement" || - block.type === "ForOfStatement" || - block.type === "ForStatement"; -} - -/** - * Checks whether or not a given declarator node has its initializer. - * @param {ASTNode} node - A declarator node to check. - * @returns {boolean} `true` when the node has its initializer. - */ -function isInitialized(node) { - const declaration = node.parent; - const block = declaration.parent; - - if (isForLoop(block)) { - if (block.type === "ForStatement") { - return block.init === declaration; - } - return block.left === declaration; - } - return Boolean(node.init); -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require or disallow initialization in variable declarations", - category: "Variables", - recommended: false, - url: "https://eslint.org/docs/rules/init-declarations" - }, - - schema: { - anyOf: [ - { - type: "array", - items: [ - { - enum: ["always"] - } - ], - minItems: 0, - maxItems: 1 - }, - { - type: "array", - items: [ - { - enum: ["never"] - }, - { - type: "object", - properties: { - ignoreForLoopInit: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - minItems: 0, - maxItems: 2 - } - ] - }, - messages: { - initialized: "Variable '{{idName}}' should be initialized on declaration.", - notInitialized: "Variable '{{idName}}' should not be initialized on declaration." - } - }, - - create(context) { - - const MODE_ALWAYS = "always", - MODE_NEVER = "never"; - - const mode = context.options[0] || MODE_ALWAYS; - const params = context.options[1] || {}; - - //-------------------------------------------------------------------------- - // Public API - //-------------------------------------------------------------------------- - - return { - "VariableDeclaration:exit"(node) { - - const kind = node.kind, - declarations = node.declarations; - - for (let i = 0; i < declarations.length; ++i) { - const declaration = declarations[i], - id = declaration.id, - initialized = isInitialized(declaration), - isIgnoredForLoop = params.ignoreForLoopInit && isForLoop(node.parent); - let messageId = ""; - - if (mode === MODE_ALWAYS && !initialized) { - messageId = "initialized"; - } else if (mode === MODE_NEVER && kind !== "const" && initialized && !isIgnoredForLoop) { - messageId = "notInitialized"; - } - - if (id.type === "Identifier" && messageId) { - context.report({ - node: declaration, - messageId, - data: { - idName: id.name - } - }); - } - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/jsx-quotes.js b/tools/node_modules/eslint/lib/rules/jsx-quotes.js deleted file mode 100644 index 372dc2f42e7497..00000000000000 --- a/tools/node_modules/eslint/lib/rules/jsx-quotes.js +++ /dev/null @@ -1,95 +0,0 @@ -/** - * @fileoverview A rule to ensure consistent quotes used in jsx syntax. - * @author Mathias Schreck - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Constants -//------------------------------------------------------------------------------ - -const QUOTE_SETTINGS = { - "prefer-double": { - quote: "\"", - description: "singlequote", - convert(str) { - return str.replace(/'/g, "\""); - } - }, - "prefer-single": { - quote: "'", - description: "doublequote", - convert(str) { - return str.replace(/"/g, "'"); - } - } -}; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce the consistent use of either double or single quotes in JSX attributes", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/jsx-quotes" - }, - - fixable: "whitespace", - - schema: [ - { - enum: ["prefer-single", "prefer-double"] - } - ], - messages: { - unexpected: "Unexpected usage of {{description}}." - } - }, - - create(context) { - const quoteOption = context.options[0] || "prefer-double", - setting = QUOTE_SETTINGS[quoteOption]; - - /** - * Checks if the given string literal node uses the expected quotes - * @param {ASTNode} node - A string literal node. - * @returns {boolean} Whether or not the string literal used the expected quotes. - * @public - */ - function usesExpectedQuotes(node) { - return node.value.indexOf(setting.quote) !== -1 || astUtils.isSurroundedBy(node.raw, setting.quote); - } - - return { - JSXAttribute(node) { - const attributeValue = node.value; - - if (attributeValue && astUtils.isStringLiteral(attributeValue) && !usesExpectedQuotes(attributeValue)) { - context.report({ - node: attributeValue, - messageId: "unexpected", - data: { - description: setting.description - }, - fix(fixer) { - return fixer.replaceText(attributeValue, setting.convert(attributeValue.raw)); - } - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/key-spacing.js b/tools/node_modules/eslint/lib/rules/key-spacing.js deleted file mode 100644 index 31ba9522e9bb72..00000000000000 --- a/tools/node_modules/eslint/lib/rules/key-spacing.js +++ /dev/null @@ -1,679 +0,0 @@ -/** - * @fileoverview Rule to specify spacing of object literal keys and values - * @author Brandon Mills - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks whether a string contains a line terminator as defined in - * http://www.ecma-international.org/ecma-262/5.1/#sec-7.3 - * @param {string} str String to test. - * @returns {boolean} True if str contains a line terminator. - */ -function containsLineTerminator(str) { - return astUtils.LINEBREAK_MATCHER.test(str); -} - -/** - * Gets the last element of an array. - * @param {Array} arr An array. - * @returns {any} Last element of arr. - */ -function last(arr) { - return arr[arr.length - 1]; -} - -/** - * Checks whether a node is contained on a single line. - * @param {ASTNode} node AST Node being evaluated. - * @returns {boolean} True if the node is a single line. - */ -function isSingleLine(node) { - return (node.loc.end.line === node.loc.start.line); -} - -/** - * Initializes a single option property from the configuration with defaults for undefined values - * @param {Object} toOptions Object to be initialized - * @param {Object} fromOptions Object to be initialized from - * @returns {Object} The object with correctly initialized options and values - */ -function initOptionProperty(toOptions, fromOptions) { - toOptions.mode = fromOptions.mode || "strict"; - - // Set value of beforeColon - if (typeof fromOptions.beforeColon !== "undefined") { - toOptions.beforeColon = +fromOptions.beforeColon; - } else { - toOptions.beforeColon = 0; - } - - // Set value of afterColon - if (typeof fromOptions.afterColon !== "undefined") { - toOptions.afterColon = +fromOptions.afterColon; - } else { - toOptions.afterColon = 1; - } - - // Set align if exists - if (typeof fromOptions.align !== "undefined") { - if (typeof fromOptions.align === "object") { - toOptions.align = fromOptions.align; - } else { // "string" - toOptions.align = { - on: fromOptions.align, - mode: toOptions.mode, - beforeColon: toOptions.beforeColon, - afterColon: toOptions.afterColon - }; - } - } - - return toOptions; -} - -/** - * Initializes all the option values (singleLine, multiLine and align) from the configuration with defaults for undefined values - * @param {Object} toOptions Object to be initialized - * @param {Object} fromOptions Object to be initialized from - * @returns {Object} The object with correctly initialized options and values - */ -function initOptions(toOptions, fromOptions) { - if (typeof fromOptions.align === "object") { - - // Initialize the alignment configuration - toOptions.align = initOptionProperty({}, fromOptions.align); - toOptions.align.on = fromOptions.align.on || "colon"; - toOptions.align.mode = fromOptions.align.mode || "strict"; - - toOptions.multiLine = initOptionProperty({}, (fromOptions.multiLine || fromOptions)); - toOptions.singleLine = initOptionProperty({}, (fromOptions.singleLine || fromOptions)); - - } else { // string or undefined - toOptions.multiLine = initOptionProperty({}, (fromOptions.multiLine || fromOptions)); - toOptions.singleLine = initOptionProperty({}, (fromOptions.singleLine || fromOptions)); - - // If alignment options are defined in multiLine, pull them out into the general align configuration - if (toOptions.multiLine.align) { - toOptions.align = { - on: toOptions.multiLine.align.on, - mode: toOptions.multiLine.align.mode || toOptions.multiLine.mode, - beforeColon: toOptions.multiLine.align.beforeColon, - afterColon: toOptions.multiLine.align.afterColon - }; - } - } - - return toOptions; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce consistent spacing between keys and values in object literal properties", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/key-spacing" - }, - - fixable: "whitespace", - - schema: [{ - anyOf: [ - { - type: "object", - properties: { - align: { - anyOf: [ - { - enum: ["colon", "value"] - }, - { - type: "object", - properties: { - mode: { - enum: ["strict", "minimum"], - default: "strict" - }, - on: { - enum: ["colon", "value"], - default: "colon" - }, - beforeColon: { - type: "boolean", - default: false - }, - afterColon: { - type: "boolean", - default: true - } - }, - additionalProperties: false - } - ] - }, - mode: { - enum: ["strict", "minimum"], - default: "strict" - }, - beforeColon: { - type: "boolean", - default: false - }, - afterColon: { - type: "boolean", - default: true - } - }, - additionalProperties: false - }, - { - type: "object", - properties: { - singleLine: { - type: "object", - properties: { - mode: { - enum: ["strict", "minimum"], - default: "strict" - }, - beforeColon: { - type: "boolean", - default: false - }, - afterColon: { - type: "boolean", - default: true - } - }, - additionalProperties: false - }, - multiLine: { - type: "object", - properties: { - align: { - anyOf: [ - { - enum: ["colon", "value"] - }, - { - type: "object", - properties: { - mode: { - enum: ["strict", "minimum"], - default: "strict" - }, - on: { - enum: ["colon", "value"], - default: "colon" - }, - beforeColon: { - type: "boolean", - default: false - }, - afterColon: { - type: "boolean", - default: true - } - }, - additionalProperties: false - } - ] - }, - mode: { - enum: ["strict", "minimum"], - default: "strict" - }, - beforeColon: { - type: "boolean", - default: false - }, - afterColon: { - type: "boolean", - default: true - } - }, - additionalProperties: false - } - }, - additionalProperties: false - }, - { - type: "object", - properties: { - singleLine: { - type: "object", - properties: { - mode: { - enum: ["strict", "minimum"], - default: "strict" - }, - beforeColon: { - type: "boolean", - default: false - }, - afterColon: { - type: "boolean", - default: true - } - }, - additionalProperties: false - }, - multiLine: { - type: "object", - properties: { - mode: { - enum: ["strict", "minimum"], - default: "strict" - }, - beforeColon: { - type: "boolean", - default: false - }, - afterColon: { - type: "boolean", - default: true - } - }, - additionalProperties: false - }, - align: { - type: "object", - properties: { - mode: { - enum: ["strict", "minimum"], - default: "strict" - }, - on: { - enum: ["colon", "value"], - default: "colon" - }, - beforeColon: { - type: "boolean", - default: false - }, - afterColon: { - type: "boolean", - default: true - } - }, - additionalProperties: false - } - }, - additionalProperties: false - } - ] - }], - messages: { - extraKey: "Extra space after {{computed}}key '{{key}}'.", - extraValue: "Extra space before value for {{computed}}key '{{key}}'.", - missingKey: "Missing space after {{computed}}key '{{key}}'.", - missingValue: "Missing space before value for {{computed}}key '{{key}}'." - } - }, - - create(context) { - - /** - * OPTIONS - * "key-spacing": [2, { - * beforeColon: false, - * afterColon: true, - * align: "colon" // Optional, or "value" - * } - */ - const options = context.options[0] || {}, - ruleOptions = initOptions({}, options), - multiLineOptions = ruleOptions.multiLine, - singleLineOptions = ruleOptions.singleLine, - alignmentOptions = ruleOptions.align || null; - - const sourceCode = context.getSourceCode(); - - /** - * Checks whether a property is a member of the property group it follows. - * @param {ASTNode} lastMember The last Property known to be in the group. - * @param {ASTNode} candidate The next Property that might be in the group. - * @returns {boolean} True if the candidate property is part of the group. - */ - function continuesPropertyGroup(lastMember, candidate) { - const groupEndLine = lastMember.loc.start.line, - candidateStartLine = candidate.loc.start.line; - - if (candidateStartLine - groupEndLine <= 1) { - return true; - } - - /* - * Check that the first comment is adjacent to the end of the group, the - * last comment is adjacent to the candidate property, and that successive - * comments are adjacent to each other. - */ - const leadingComments = sourceCode.getCommentsBefore(candidate); - - if ( - leadingComments.length && - leadingComments[0].loc.start.line - groupEndLine <= 1 && - candidateStartLine - last(leadingComments).loc.end.line <= 1 - ) { - for (let i = 1; i < leadingComments.length; i++) { - if (leadingComments[i].loc.start.line - leadingComments[i - 1].loc.end.line > 1) { - return false; - } - } - return true; - } - - return false; - } - - /** - * Determines if the given property is key-value property. - * @param {ASTNode} property Property node to check. - * @returns {boolean} Whether the property is a key-value property. - */ - function isKeyValueProperty(property) { - return !( - (property.method || - property.shorthand || - property.kind !== "init" || property.type !== "Property") // Could be "ExperimentalSpreadProperty" or "SpreadElement" - ); - } - - /** - * Starting from the given a node (a property.key node here) looks forward - * until it finds the last token before a colon punctuator and returns it. - * @param {ASTNode} node The node to start looking from. - * @returns {ASTNode} The last token before a colon punctuator. - */ - function getLastTokenBeforeColon(node) { - const colonToken = sourceCode.getTokenAfter(node, astUtils.isColonToken); - - return sourceCode.getTokenBefore(colonToken); - } - - /** - * Starting from the given a node (a property.key node here) looks forward - * until it finds the colon punctuator and returns it. - * @param {ASTNode} node The node to start looking from. - * @returns {ASTNode} The colon punctuator. - */ - function getNextColon(node) { - return sourceCode.getTokenAfter(node, astUtils.isColonToken); - } - - /** - * Gets an object literal property's key as the identifier name or string value. - * @param {ASTNode} property Property node whose key to retrieve. - * @returns {string} The property's key. - */ - function getKey(property) { - const key = property.key; - - if (property.computed) { - return sourceCode.getText().slice(key.range[0], key.range[1]); - } - - return property.key.name || property.key.value; - } - - /** - * Reports an appropriately-formatted error if spacing is incorrect on one - * side of the colon. - * @param {ASTNode} property Key-value pair in an object literal. - * @param {string} side Side being verified - either "key" or "value". - * @param {string} whitespace Actual whitespace string. - * @param {int} expected Expected whitespace length. - * @param {string} mode Value of the mode as "strict" or "minimum" - * @returns {void} - */ - function report(property, side, whitespace, expected, mode) { - const diff = whitespace.length - expected, - nextColon = getNextColon(property.key), - tokenBeforeColon = sourceCode.getTokenBefore(nextColon, { includeComments: true }), - tokenAfterColon = sourceCode.getTokenAfter(nextColon, { includeComments: true }), - isKeySide = side === "key", - locStart = isKeySide ? tokenBeforeColon.loc.start : tokenAfterColon.loc.start, - isExtra = diff > 0, - diffAbs = Math.abs(diff), - spaces = Array(diffAbs + 1).join(" "); - - if (( - diff && mode === "strict" || - diff < 0 && mode === "minimum" || - diff > 0 && !expected && mode === "minimum") && - !(expected && containsLineTerminator(whitespace)) - ) { - let fix; - - if (isExtra) { - let range; - - // Remove whitespace - if (isKeySide) { - range = [tokenBeforeColon.range[1], tokenBeforeColon.range[1] + diffAbs]; - } else { - range = [tokenAfterColon.range[0] - diffAbs, tokenAfterColon.range[0]]; - } - fix = function(fixer) { - return fixer.removeRange(range); - }; - } else { - - // Add whitespace - if (isKeySide) { - fix = function(fixer) { - return fixer.insertTextAfter(tokenBeforeColon, spaces); - }; - } else { - fix = function(fixer) { - return fixer.insertTextBefore(tokenAfterColon, spaces); - }; - } - } - - let messageId = ""; - - if (isExtra) { - messageId = side === "key" ? "extraKey" : "extraValue"; - } else { - messageId = side === "key" ? "missingKey" : "missingValue"; - } - - context.report({ - node: property[side], - loc: locStart, - messageId, - data: { - computed: property.computed ? "computed " : "", - key: getKey(property) - }, - fix - }); - } - } - - /** - * Gets the number of characters in a key, including quotes around string - * keys and braces around computed property keys. - * @param {ASTNode} property Property of on object literal. - * @returns {int} Width of the key. - */ - function getKeyWidth(property) { - const startToken = sourceCode.getFirstToken(property); - const endToken = getLastTokenBeforeColon(property.key); - - return endToken.range[1] - startToken.range[0]; - } - - /** - * Gets the whitespace around the colon in an object literal property. - * @param {ASTNode} property Property node from an object literal. - * @returns {Object} Whitespace before and after the property's colon. - */ - function getPropertyWhitespace(property) { - const whitespace = /(\s*):(\s*)/.exec(sourceCode.getText().slice( - property.key.range[1], property.value.range[0] - )); - - if (whitespace) { - return { - beforeColon: whitespace[1], - afterColon: whitespace[2] - }; - } - return null; - } - - /** - * Creates groups of properties. - * @param {ASTNode} node ObjectExpression node being evaluated. - * @returns {Array.} Groups of property AST node lists. - */ - function createGroups(node) { - if (node.properties.length === 1) { - return [node.properties]; - } - - return node.properties.reduce((groups, property) => { - const currentGroup = last(groups), - prev = last(currentGroup); - - if (!prev || continuesPropertyGroup(prev, property)) { - currentGroup.push(property); - } else { - groups.push([property]); - } - - return groups; - }, [ - [] - ]); - } - - /** - * Verifies correct vertical alignment of a group of properties. - * @param {ASTNode[]} properties List of Property AST nodes. - * @returns {void} - */ - function verifyGroupAlignment(properties) { - const length = properties.length, - widths = properties.map(getKeyWidth), // Width of keys, including quotes - align = alignmentOptions.on; // "value" or "colon" - let targetWidth = Math.max(...widths), - beforeColon, afterColon, mode; - - if (alignmentOptions && length > 1) { // When aligning values within a group, use the alignment configuration. - beforeColon = alignmentOptions.beforeColon; - afterColon = alignmentOptions.afterColon; - mode = alignmentOptions.mode; - } else { - beforeColon = multiLineOptions.beforeColon; - afterColon = multiLineOptions.afterColon; - mode = alignmentOptions.mode; - } - - // Conditionally include one space before or after colon - targetWidth += (align === "colon" ? beforeColon : afterColon); - - for (let i = 0; i < length; i++) { - const property = properties[i]; - const whitespace = getPropertyWhitespace(property); - - if (whitespace) { // Object literal getters/setters lack a colon - const width = widths[i]; - - if (align === "value") { - report(property, "key", whitespace.beforeColon, beforeColon, mode); - report(property, "value", whitespace.afterColon, targetWidth - width, mode); - } else { // align = "colon" - report(property, "key", whitespace.beforeColon, targetWidth - width, mode); - report(property, "value", whitespace.afterColon, afterColon, mode); - } - } - } - } - - /** - * Verifies vertical alignment, taking into account groups of properties. - * @param {ASTNode} node ObjectExpression node being evaluated. - * @returns {void} - */ - function verifyAlignment(node) { - createGroups(node).forEach(group => { - verifyGroupAlignment(group.filter(isKeyValueProperty)); - }); - } - - /** - * Verifies spacing of property conforms to specified options. - * @param {ASTNode} node Property node being evaluated. - * @param {Object} lineOptions Configured singleLine or multiLine options - * @returns {void} - */ - function verifySpacing(node, lineOptions) { - const actual = getPropertyWhitespace(node); - - if (actual) { // Object literal getters/setters lack colons - report(node, "key", actual.beforeColon, lineOptions.beforeColon, lineOptions.mode); - report(node, "value", actual.afterColon, lineOptions.afterColon, lineOptions.mode); - } - } - - /** - * Verifies spacing of each property in a list. - * @param {ASTNode[]} properties List of Property AST nodes. - * @returns {void} - */ - function verifyListSpacing(properties) { - const length = properties.length; - - for (let i = 0; i < length; i++) { - verifySpacing(properties[i], singleLineOptions); - } - } - - //-------------------------------------------------------------------------- - // Public API - //-------------------------------------------------------------------------- - - if (alignmentOptions) { // Verify vertical alignment - - return { - ObjectExpression(node) { - if (isSingleLine(node)) { - verifyListSpacing(node.properties.filter(isKeyValueProperty)); - } else { - verifyAlignment(node); - } - } - }; - - } - - // Obey beforeColon and afterColon in each property as configured - return { - Property(node) { - verifySpacing(node, isSingleLine(node.parent) ? singleLineOptions : multiLineOptions); - } - }; - - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/keyword-spacing.js b/tools/node_modules/eslint/lib/rules/keyword-spacing.js deleted file mode 100644 index 83ad6282688bab..00000000000000 --- a/tools/node_modules/eslint/lib/rules/keyword-spacing.js +++ /dev/null @@ -1,590 +0,0 @@ -/** - * @fileoverview Rule to enforce spacing before and after keywords. - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"), - keywords = require("../util/keywords"); - -//------------------------------------------------------------------------------ -// Constants -//------------------------------------------------------------------------------ - -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)$/; -const KEYS = keywords.concat(["as", "async", "await", "from", "get", "let", "of", "set", "yield"]); - -// check duplications. -(function() { - KEYS.sort(); - for (let i = 1; i < KEYS.length; ++i) { - if (KEYS[i] === KEYS[i - 1]) { - throw new Error(`Duplication was found in the keyword list: ${KEYS[i]}`); - } - } -}()); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks whether or not a given token is a "Template" token ends with "${". - * - * @param {Token} token - A token to check. - * @returns {boolean} `true` if the token is a "Template" token ends with "${". - */ -function isOpenParenOfTemplate(token) { - return token.type === "Template" && TEMPLATE_OPEN_PAREN.test(token.value); -} - -/** - * Checks whether or not a given token is a "Template" token starts with "}". - * - * @param {Token} token - A token to check. - * @returns {boolean} `true` if the token is a "Template" token starts with "}". - */ -function isCloseParenOfTemplate(token) { - return token.type === "Template" && TEMPLATE_CLOSE_PAREN.test(token.value); -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce consistent spacing before and after keywords", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/keyword-spacing" - }, - - fixable: "whitespace", - - schema: [ - { - type: "object", - properties: { - before: { type: "boolean", default: true }, - after: { type: "boolean", default: true }, - overrides: { - type: "object", - properties: KEYS.reduce((retv, key) => { - retv[key] = { - type: "object", - properties: { - before: { type: "boolean", default: true }, - after: { type: "boolean", default: true } - }, - additionalProperties: false - }; - return retv; - }, {}), - additionalProperties: false - } - }, - additionalProperties: false - } - ], - messages: { - expectedBefore: "Expected space(s) before \"{{value}}\".", - expectedAfter: "Expected space(s) after \"{{value}}\".", - unexpectedBefore: "Unexpected space(s) before \"{{value}}\".", - unexpectedAfter: "Unexpected space(s) after \"{{value}}\"." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - /** - * Reports a given token if there are not space(s) before the token. - * - * @param {Token} token - A token to report. - * @param {RegExp} pattern - A pattern of the previous token to check. - * @returns {void} - */ - function expectSpaceBefore(token, pattern) { - const prevToken = sourceCode.getTokenBefore(token); - - if (prevToken && - (CHECK_TYPE.test(prevToken.type) || pattern.test(prevToken.value)) && - !isOpenParenOfTemplate(prevToken) && - astUtils.isTokenOnSameLine(prevToken, token) && - !sourceCode.isSpaceBetweenTokens(prevToken, token) - ) { - context.report({ - loc: token.loc.start, - messageId: "expectedBefore", - data: token, - fix(fixer) { - return fixer.insertTextBefore(token, " "); - } - }); - } - } - - /** - * Reports a given token if there are space(s) before the token. - * - * @param {Token} token - A token to report. - * @param {RegExp} pattern - A pattern of the previous token to check. - * @returns {void} - */ - function unexpectSpaceBefore(token, pattern) { - const prevToken = sourceCode.getTokenBefore(token); - - if (prevToken && - (CHECK_TYPE.test(prevToken.type) || pattern.test(prevToken.value)) && - !isOpenParenOfTemplate(prevToken) && - astUtils.isTokenOnSameLine(prevToken, token) && - sourceCode.isSpaceBetweenTokens(prevToken, token) - ) { - context.report({ - loc: token.loc.start, - messageId: "unexpectedBefore", - data: token, - fix(fixer) { - return fixer.removeRange([prevToken.range[1], token.range[0]]); - } - }); - } - } - - /** - * Reports a given token if there are not space(s) after the token. - * - * @param {Token} token - A token to report. - * @param {RegExp} pattern - A pattern of the next token to check. - * @returns {void} - */ - function expectSpaceAfter(token, pattern) { - const nextToken = sourceCode.getTokenAfter(token); - - if (nextToken && - (CHECK_TYPE.test(nextToken.type) || pattern.test(nextToken.value)) && - !isCloseParenOfTemplate(nextToken) && - astUtils.isTokenOnSameLine(token, nextToken) && - !sourceCode.isSpaceBetweenTokens(token, nextToken) - ) { - context.report({ - loc: token.loc.start, - messageId: "expectedAfter", - data: token, - fix(fixer) { - return fixer.insertTextAfter(token, " "); - } - }); - } - } - - /** - * Reports a given token if there are space(s) after the token. - * - * @param {Token} token - A token to report. - * @param {RegExp} pattern - A pattern of the next token to check. - * @returns {void} - */ - function unexpectSpaceAfter(token, pattern) { - const nextToken = sourceCode.getTokenAfter(token); - - if (nextToken && - (CHECK_TYPE.test(nextToken.type) || pattern.test(nextToken.value)) && - !isCloseParenOfTemplate(nextToken) && - astUtils.isTokenOnSameLine(token, nextToken) && - sourceCode.isSpaceBetweenTokens(token, nextToken) - ) { - context.report({ - loc: token.loc.start, - messageId: "unexpectedAfter", - data: token, - fix(fixer) { - return fixer.removeRange([token.range[1], nextToken.range[0]]); - } - }); - } - } - - /** - * Parses the option object and determines check methods for each keyword. - * - * @param {Object|undefined} options - The option object to parse. - * @returns {Object} - Normalized option object. - * Keys are keywords (there are for every keyword). - * Values are instances of `{"before": function, "after": function}`. - */ - function parseOptions(options = {}) { - const before = options.before !== false; - const after = options.after !== false; - const defaultValue = { - before: before ? expectSpaceBefore : unexpectSpaceBefore, - after: after ? expectSpaceAfter : unexpectSpaceAfter - }; - const overrides = (options && options.overrides) || {}; - const retv = Object.create(null); - - for (let i = 0; i < KEYS.length; ++i) { - const key = KEYS[i]; - const override = overrides[key]; - - if (override) { - const thisBefore = ("before" in override) ? override.before : before; - const thisAfter = ("after" in override) ? override.after : after; - - retv[key] = { - before: thisBefore ? expectSpaceBefore : unexpectSpaceBefore, - after: thisAfter ? expectSpaceAfter : unexpectSpaceAfter - }; - } else { - retv[key] = defaultValue; - } - } - - return retv; - } - - const checkMethodMap = parseOptions(context.options[0]); - - /** - * Reports a given token if usage of spacing followed by the token is - * invalid. - * - * @param {Token} token - A token to report. - * @param {RegExp|undefined} pattern - Optional. A pattern of the previous - * token to check. - * @returns {void} - */ - function checkSpacingBefore(token, pattern) { - checkMethodMap[token.value].before(token, pattern || PREV_TOKEN); - } - - /** - * Reports a given token if usage of spacing preceded by the token is - * invalid. - * - * @param {Token} token - A token to report. - * @param {RegExp|undefined} pattern - Optional. A pattern of the next - * token to check. - * @returns {void} - */ - function checkSpacingAfter(token, pattern) { - checkMethodMap[token.value].after(token, pattern || NEXT_TOKEN); - } - - /** - * Reports a given token if usage of spacing around the token is invalid. - * - * @param {Token} token - A token to report. - * @returns {void} - */ - function checkSpacingAround(token) { - checkSpacingBefore(token); - checkSpacingAfter(token); - } - - /** - * Reports the first token of a given node if the first token is a keyword - * and usage of spacing around the token is invalid. - * - * @param {ASTNode|null} node - A node to report. - * @returns {void} - */ - function checkSpacingAroundFirstToken(node) { - const firstToken = node && sourceCode.getFirstToken(node); - - if (firstToken && firstToken.type === "Keyword") { - checkSpacingAround(firstToken); - } - } - - /** - * Reports the first token of a given node if the first token is a keyword - * and usage of spacing followed by the token is invalid. - * - * This is used for unary operators (e.g. `typeof`), `function`, and `super`. - * Other rules are handling usage of spacing preceded by those keywords. - * - * @param {ASTNode|null} node - A node to report. - * @returns {void} - */ - function checkSpacingBeforeFirstToken(node) { - const firstToken = node && sourceCode.getFirstToken(node); - - if (firstToken && firstToken.type === "Keyword") { - checkSpacingBefore(firstToken); - } - } - - /** - * Reports the previous token of a given node if the token is a keyword and - * usage of spacing around the token is invalid. - * - * @param {ASTNode|null} node - A node to report. - * @returns {void} - */ - function checkSpacingAroundTokenBefore(node) { - if (node) { - const token = sourceCode.getTokenBefore(node, astUtils.isKeywordToken); - - checkSpacingAround(token); - } - } - - /** - * Reports `async` or `function` keywords of a given node if usage of - * spacing around those keywords is invalid. - * - * @param {ASTNode} node - A node to report. - * @returns {void} - */ - function checkSpacingForFunction(node) { - const firstToken = node && sourceCode.getFirstToken(node); - - if (firstToken && - ((firstToken.type === "Keyword" && firstToken.value === "function") || - firstToken.value === "async") - ) { - checkSpacingBefore(firstToken); - } - } - - /** - * Reports `class` and `extends` keywords of a given node if usage of - * spacing around those keywords is invalid. - * - * @param {ASTNode} node - A node to report. - * @returns {void} - */ - function checkSpacingForClass(node) { - checkSpacingAroundFirstToken(node); - checkSpacingAroundTokenBefore(node.superClass); - } - - /** - * Reports `if` and `else` keywords of a given node if usage of spacing - * around those keywords is invalid. - * - * @param {ASTNode} node - A node to report. - * @returns {void} - */ - function checkSpacingForIfStatement(node) { - checkSpacingAroundFirstToken(node); - checkSpacingAroundTokenBefore(node.alternate); - } - - /** - * Reports `try`, `catch`, and `finally` keywords of a given node if usage - * of spacing around those keywords is invalid. - * - * @param {ASTNode} node - A node to report. - * @returns {void} - */ - function checkSpacingForTryStatement(node) { - checkSpacingAroundFirstToken(node); - checkSpacingAroundFirstToken(node.handler); - checkSpacingAroundTokenBefore(node.finalizer); - } - - /** - * Reports `do` and `while` keywords of a given node if usage of spacing - * around those keywords is invalid. - * - * @param {ASTNode} node - A node to report. - * @returns {void} - */ - function checkSpacingForDoWhileStatement(node) { - checkSpacingAroundFirstToken(node); - checkSpacingAroundTokenBefore(node.test); - } - - /** - * Reports `for` and `in` keywords of a given node if usage of spacing - * around those keywords is invalid. - * - * @param {ASTNode} node - A node to report. - * @returns {void} - */ - function checkSpacingForForInStatement(node) { - checkSpacingAroundFirstToken(node); - checkSpacingAroundTokenBefore(node.right); - } - - /** - * Reports `for` and `of` keywords of a given node if usage of spacing - * around those keywords is invalid. - * - * @param {ASTNode} node - A node to report. - * @returns {void} - */ - function checkSpacingForForOfStatement(node) { - if (node.await) { - checkSpacingBefore(sourceCode.getFirstToken(node, 0)); - checkSpacingAfter(sourceCode.getFirstToken(node, 1)); - } else { - checkSpacingAroundFirstToken(node); - } - checkSpacingAround(sourceCode.getTokenBefore(node.right, astUtils.isNotOpeningParenToken)); - } - - /** - * Reports `import`, `export`, `as`, and `from` keywords of a given node if - * usage of spacing around those keywords is invalid. - * - * This rule handles the `*` token in module declarations. - * - * import*as A from "./a"; /*error Expected space(s) after "import". - * error Expected space(s) before "as". - * - * @param {ASTNode} node - A node to report. - * @returns {void} - */ - function checkSpacingForModuleDeclaration(node) { - const firstToken = sourceCode.getFirstToken(node); - - checkSpacingBefore(firstToken, PREV_TOKEN_M); - checkSpacingAfter(firstToken, NEXT_TOKEN_M); - - if (node.type === "ExportDefaultDeclaration") { - checkSpacingAround(sourceCode.getTokenAfter(firstToken)); - } - - if (node.source) { - const fromToken = sourceCode.getTokenBefore(node.source); - - checkSpacingBefore(fromToken, PREV_TOKEN_M); - checkSpacingAfter(fromToken, NEXT_TOKEN_M); - } - } - - /** - * Reports `as` keyword of a given node if usage of spacing around this - * keyword is invalid. - * - * @param {ASTNode} node - A node to report. - * @returns {void} - */ - function checkSpacingForImportNamespaceSpecifier(node) { - const asToken = sourceCode.getFirstToken(node, 1); - - checkSpacingBefore(asToken, PREV_TOKEN_M); - } - - /** - * Reports `static`, `get`, and `set` keywords of a given node if usage of - * spacing around those keywords is invalid. - * - * @param {ASTNode} node - A node to report. - * @returns {void} - */ - function checkSpacingForProperty(node) { - if (node.static) { - checkSpacingAroundFirstToken(node); - } - if (node.kind === "get" || - node.kind === "set" || - ( - (node.method || node.type === "MethodDefinition") && - node.value.async - ) - ) { - const token = sourceCode.getTokenBefore( - node.key, - tok => { - switch (tok.value) { - case "get": - case "set": - case "async": - return true; - default: - return false; - } - } - ); - - if (!token) { - throw new Error("Failed to find token get, set, or async beside method name"); - } - - - checkSpacingAround(token); - } - } - - /** - * Reports `await` keyword of a given node if usage of spacing before - * this keyword is invalid. - * - * @param {ASTNode} node - A node to report. - * @returns {void} - */ - function checkSpacingForAwaitExpression(node) { - checkSpacingBefore(sourceCode.getFirstToken(node)); - } - - return { - - // Statements - DebuggerStatement: checkSpacingAroundFirstToken, - WithStatement: checkSpacingAroundFirstToken, - - // Statements - Control flow - BreakStatement: checkSpacingAroundFirstToken, - ContinueStatement: checkSpacingAroundFirstToken, - ReturnStatement: checkSpacingAroundFirstToken, - ThrowStatement: checkSpacingAroundFirstToken, - TryStatement: checkSpacingForTryStatement, - - // Statements - Choice - IfStatement: checkSpacingForIfStatement, - SwitchStatement: checkSpacingAroundFirstToken, - SwitchCase: checkSpacingAroundFirstToken, - - // Statements - Loops - DoWhileStatement: checkSpacingForDoWhileStatement, - ForInStatement: checkSpacingForForInStatement, - ForOfStatement: checkSpacingForForOfStatement, - ForStatement: checkSpacingAroundFirstToken, - WhileStatement: checkSpacingAroundFirstToken, - - // Statements - Declarations - ClassDeclaration: checkSpacingForClass, - ExportNamedDeclaration: checkSpacingForModuleDeclaration, - ExportDefaultDeclaration: checkSpacingForModuleDeclaration, - ExportAllDeclaration: checkSpacingForModuleDeclaration, - FunctionDeclaration: checkSpacingForFunction, - ImportDeclaration: checkSpacingForModuleDeclaration, - VariableDeclaration: checkSpacingAroundFirstToken, - - // Expressions - ArrowFunctionExpression: checkSpacingForFunction, - AwaitExpression: checkSpacingForAwaitExpression, - ClassExpression: checkSpacingForClass, - FunctionExpression: checkSpacingForFunction, - NewExpression: checkSpacingBeforeFirstToken, - Super: checkSpacingBeforeFirstToken, - ThisExpression: checkSpacingBeforeFirstToken, - UnaryExpression: checkSpacingBeforeFirstToken, - YieldExpression: checkSpacingBeforeFirstToken, - - // Others - ImportNamespaceSpecifier: checkSpacingForImportNamespaceSpecifier, - MethodDefinition: checkSpacingForProperty, - Property: checkSpacingForProperty - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/line-comment-position.js b/tools/node_modules/eslint/lib/rules/line-comment-position.js deleted file mode 100644 index 132a8ad875f558..00000000000000 --- a/tools/node_modules/eslint/lib/rules/line-comment-position.js +++ /dev/null @@ -1,125 +0,0 @@ -/** - * @fileoverview Rule to enforce the position of line comments - * @author Alberto Rodríguez - */ -"use strict"; - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce position of line comments", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/line-comment-position" - }, - - schema: [ - { - oneOf: [ - { - enum: ["above", "beside"] - }, - { - type: "object", - properties: { - position: { - enum: ["above", "beside"], - default: "above" - }, - ignorePattern: { - type: "string" - }, - applyDefaultPatterns: { - type: "boolean", - default: true - }, - applyDefaultIgnorePatterns: { - type: "boolean", - default: true - } - }, - additionalProperties: false - } - ] - } - ], - messages: { - above: "Expected comment to be above code.", - beside: "Expected comment to be beside code." - } - }, - - create(context) { - const options = context.options[0]; - - let above, - ignorePattern, - applyDefaultIgnorePatterns = true; - - if (!options || typeof options === "string") { - above = !options || options === "above"; - - } else { - above = !options.position || options.position === "above"; - ignorePattern = options.ignorePattern; - - if (Object.prototype.hasOwnProperty.call(options, "applyDefaultIgnorePatterns")) { - applyDefaultIgnorePatterns = options.applyDefaultIgnorePatterns; - } else { - applyDefaultIgnorePatterns = options.applyDefaultPatterns; - } - } - - const defaultIgnoreRegExp = astUtils.COMMENTS_IGNORE_PATTERN; - const fallThroughRegExp = /^\s*falls?\s?through/; - const customIgnoreRegExp = new RegExp(ignorePattern); - const sourceCode = context.getSourceCode(); - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - Program() { - const comments = sourceCode.getAllComments(); - - comments.filter(token => token.type === "Line").forEach(node => { - if (applyDefaultIgnorePatterns && (defaultIgnoreRegExp.test(node.value) || fallThroughRegExp.test(node.value))) { - return; - } - - if (ignorePattern && customIgnoreRegExp.test(node.value)) { - return; - } - - const previous = sourceCode.getTokenBefore(node, { includeComments: true }); - const isOnSameLine = previous && previous.loc.end.line === node.loc.start.line; - - if (above) { - if (isOnSameLine) { - context.report({ - node, - messageId: "above" - }); - } - } else { - if (!isOnSameLine) { - context.report({ - node, - messageId: "beside" - }); - } - } - }); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/linebreak-style.js b/tools/node_modules/eslint/lib/rules/linebreak-style.js deleted file mode 100644 index 4523d6f58a1871..00000000000000 --- a/tools/node_modules/eslint/lib/rules/linebreak-style.js +++ /dev/null @@ -1,99 +0,0 @@ -/** - * @fileoverview Rule to enforce a single linebreak style. - * @author Erik Mueller - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce consistent linebreak style", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/linebreak-style" - }, - - fixable: "whitespace", - - schema: [ - { - enum: ["unix", "windows"] - } - ], - messages: { - expectedLF: "Expected linebreaks to be 'LF' but found 'CRLF'.", - expectedCRLF: "Expected linebreaks to be 'CRLF' but found 'LF'." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Builds a fix function that replaces text at the specified range in the source text. - * @param {int[]} range The range to replace - * @param {string} text The text to insert. - * @returns {Function} Fixer function - * @private - */ - function createFix(range, text) { - return function(fixer) { - return fixer.replaceTextRange(range, text); - }; - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - Program: function checkForlinebreakStyle(node) { - const linebreakStyle = context.options[0] || "unix", - expectedLF = linebreakStyle === "unix", - expectedLFChars = expectedLF ? "\n" : "\r\n", - source = sourceCode.getText(), - pattern = astUtils.createGlobalLinebreakMatcher(); - let match; - - let i = 0; - - while ((match = pattern.exec(source)) !== null) { - i++; - if (match[0] === expectedLFChars) { - continue; - } - - const index = match.index; - const range = [index, index + match[0].length]; - - context.report({ - node, - loc: { - line: i, - column: sourceCode.lines[i - 1].length - }, - messageId: expectedLF ? "expectedLF" : "expectedCRLF", - fix: createFix(range, expectedLFChars) - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/lines-around-comment.js b/tools/node_modules/eslint/lib/rules/lines-around-comment.js deleted file mode 100644 index 0f9851f7241180..00000000000000 --- a/tools/node_modules/eslint/lib/rules/lines-around-comment.js +++ /dev/null @@ -1,404 +0,0 @@ -/** - * @fileoverview Enforces empty lines around comments. - * @author Jamund Ferguson - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const lodash = require("lodash"), - astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Return an array with with any line numbers that are empty. - * @param {Array} lines An array of each line of the file. - * @returns {Array} An array of line numbers. - */ -function getEmptyLineNums(lines) { - const emptyLines = lines.map((line, i) => ({ - code: line.trim(), - num: i + 1 - })).filter(line => !line.code).map(line => line.num); - - return emptyLines; -} - -/** - * Return an array with with any line numbers that contain comments. - * @param {Array} comments An array of comment tokens. - * @returns {Array} An array of line numbers. - */ -function getCommentLineNums(comments) { - const lines = []; - - comments.forEach(token => { - const start = token.loc.start.line; - const end = token.loc.end.line; - - lines.push(start, end); - }); - return lines; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "require empty lines around comments", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/lines-around-comment" - }, - - fixable: "whitespace", - - schema: [ - { - type: "object", - properties: { - beforeBlockComment: { - type: "boolean", - default: true - }, - afterBlockComment: { - type: "boolean", - default: false - }, - beforeLineComment: { - type: "boolean", - default: false - }, - afterLineComment: { - type: "boolean", - default: false - }, - allowBlockStart: { - type: "boolean", - default: false - }, - allowBlockEnd: { - type: "boolean", - default: false - }, - allowClassStart: { - type: "boolean" - }, - allowClassEnd: { - type: "boolean" - }, - allowObjectStart: { - type: "boolean" - }, - allowObjectEnd: { - type: "boolean" - }, - allowArrayStart: { - type: "boolean" - }, - allowArrayEnd: { - type: "boolean" - }, - ignorePattern: { - type: "string" - }, - applyDefaultIgnorePatterns: { - type: "boolean" - } - }, - additionalProperties: false - } - ], - messages: { - after: "Expected line after comment.", - before: "Expected line before comment." - } - }, - - create(context) { - - const options = Object.assign({}, context.options[0]); - const ignorePattern = options.ignorePattern; - const defaultIgnoreRegExp = astUtils.COMMENTS_IGNORE_PATTERN; - const customIgnoreRegExp = new RegExp(ignorePattern); - const applyDefaultIgnorePatterns = options.applyDefaultIgnorePatterns !== false; - - options.beforeBlockComment = typeof options.beforeBlockComment !== "undefined" ? options.beforeBlockComment : true; - - const sourceCode = context.getSourceCode(); - - const lines = sourceCode.lines, - numLines = lines.length + 1, - comments = sourceCode.getAllComments(), - commentLines = getCommentLineNums(comments), - emptyLines = getEmptyLineNums(lines), - commentAndEmptyLines = commentLines.concat(emptyLines); - - /** - * Returns whether or not comments are on lines starting with or ending with code - * @param {token} token The comment token to check. - * @returns {boolean} True if the comment is not alone. - */ - function codeAroundComment(token) { - let currentToken = token; - - do { - currentToken = sourceCode.getTokenBefore(currentToken, { includeComments: true }); - } while (currentToken && astUtils.isCommentToken(currentToken)); - - if (currentToken && astUtils.isTokenOnSameLine(currentToken, token)) { - return true; - } - - currentToken = token; - do { - currentToken = sourceCode.getTokenAfter(currentToken, { includeComments: true }); - } while (currentToken && astUtils.isCommentToken(currentToken)); - - if (currentToken && astUtils.isTokenOnSameLine(token, currentToken)) { - return true; - } - - return false; - } - - /** - * Returns whether or not comments are inside a node type or not. - * @param {ASTNode} parent The Comment parent node. - * @param {string} nodeType The parent type to check against. - * @returns {boolean} True if the comment is inside nodeType. - */ - function isParentNodeType(parent, nodeType) { - return parent.type === nodeType || - (parent.body && parent.body.type === nodeType) || - (parent.consequent && parent.consequent.type === nodeType); - } - - /** - * Returns the parent node that contains the given token. - * @param {token} token The token to check. - * @returns {ASTNode} The parent node that contains the given token. - */ - function getParentNodeOfToken(token) { - return sourceCode.getNodeByRangeIndex(token.range[0]); - } - - /** - * Returns whether or not comments are at the parent start or not. - * @param {token} token The Comment token. - * @param {string} nodeType The parent type to check against. - * @returns {boolean} True if the comment is at parent start. - */ - function isCommentAtParentStart(token, nodeType) { - const parent = getParentNodeOfToken(token); - - return parent && isParentNodeType(parent, nodeType) && - token.loc.start.line - parent.loc.start.line === 1; - } - - /** - * Returns whether or not comments are at the parent end or not. - * @param {token} token The Comment token. - * @param {string} nodeType The parent type to check against. - * @returns {boolean} True if the comment is at parent end. - */ - function isCommentAtParentEnd(token, nodeType) { - const parent = getParentNodeOfToken(token); - - return parent && isParentNodeType(parent, nodeType) && - parent.loc.end.line - token.loc.end.line === 1; - } - - /** - * Returns whether or not comments are at the block start or not. - * @param {token} token The Comment token. - * @returns {boolean} True if the comment is at block start. - */ - function isCommentAtBlockStart(token) { - return isCommentAtParentStart(token, "ClassBody") || isCommentAtParentStart(token, "BlockStatement") || isCommentAtParentStart(token, "SwitchCase"); - } - - /** - * Returns whether or not comments are at the block end or not. - * @param {token} token The Comment token. - * @returns {boolean} True if the comment is at block end. - */ - function isCommentAtBlockEnd(token) { - return isCommentAtParentEnd(token, "ClassBody") || isCommentAtParentEnd(token, "BlockStatement") || isCommentAtParentEnd(token, "SwitchCase") || isCommentAtParentEnd(token, "SwitchStatement"); - } - - /** - * Returns whether or not comments are at the class start or not. - * @param {token} token The Comment token. - * @returns {boolean} True if the comment is at class start. - */ - function isCommentAtClassStart(token) { - return isCommentAtParentStart(token, "ClassBody"); - } - - /** - * Returns whether or not comments are at the class end or not. - * @param {token} token The Comment token. - * @returns {boolean} True if the comment is at class end. - */ - function isCommentAtClassEnd(token) { - return isCommentAtParentEnd(token, "ClassBody"); - } - - /** - * Returns whether or not comments are at the object start or not. - * @param {token} token The Comment token. - * @returns {boolean} True if the comment is at object start. - */ - function isCommentAtObjectStart(token) { - return isCommentAtParentStart(token, "ObjectExpression") || isCommentAtParentStart(token, "ObjectPattern"); - } - - /** - * Returns whether or not comments are at the object end or not. - * @param {token} token The Comment token. - * @returns {boolean} True if the comment is at object end. - */ - function isCommentAtObjectEnd(token) { - return isCommentAtParentEnd(token, "ObjectExpression") || isCommentAtParentEnd(token, "ObjectPattern"); - } - - /** - * Returns whether or not comments are at the array start or not. - * @param {token} token The Comment token. - * @returns {boolean} True if the comment is at array start. - */ - function isCommentAtArrayStart(token) { - return isCommentAtParentStart(token, "ArrayExpression") || isCommentAtParentStart(token, "ArrayPattern"); - } - - /** - * Returns whether or not comments are at the array end or not. - * @param {token} token The Comment token. - * @returns {boolean} True if the comment is at array end. - */ - function isCommentAtArrayEnd(token) { - return isCommentAtParentEnd(token, "ArrayExpression") || isCommentAtParentEnd(token, "ArrayPattern"); - } - - /** - * Checks if a comment token has lines around it (ignores inline comments) - * @param {token} token The Comment token. - * @param {Object} opts Options to determine the newline. - * @param {boolean} opts.after Should have a newline after this line. - * @param {boolean} opts.before Should have a newline before this line. - * @returns {void} - */ - function checkForEmptyLine(token, opts) { - if (applyDefaultIgnorePatterns && defaultIgnoreRegExp.test(token.value)) { - return; - } - - if (ignorePattern && customIgnoreRegExp.test(token.value)) { - return; - } - - let after = opts.after, - before = opts.before; - - const prevLineNum = token.loc.start.line - 1, - nextLineNum = token.loc.end.line + 1, - commentIsNotAlone = codeAroundComment(token); - - const blockStartAllowed = options.allowBlockStart && - isCommentAtBlockStart(token) && - !(options.allowClassStart === false && - isCommentAtClassStart(token)), - blockEndAllowed = options.allowBlockEnd && isCommentAtBlockEnd(token) && !(options.allowClassEnd === false && isCommentAtClassEnd(token)), - classStartAllowed = options.allowClassStart && isCommentAtClassStart(token), - classEndAllowed = options.allowClassEnd && isCommentAtClassEnd(token), - objectStartAllowed = options.allowObjectStart && isCommentAtObjectStart(token), - objectEndAllowed = options.allowObjectEnd && isCommentAtObjectEnd(token), - arrayStartAllowed = options.allowArrayStart && isCommentAtArrayStart(token), - arrayEndAllowed = options.allowArrayEnd && isCommentAtArrayEnd(token); - - const exceptionStartAllowed = blockStartAllowed || classStartAllowed || objectStartAllowed || arrayStartAllowed; - const exceptionEndAllowed = blockEndAllowed || classEndAllowed || objectEndAllowed || arrayEndAllowed; - - // ignore top of the file and bottom of the file - if (prevLineNum < 1) { - before = false; - } - if (nextLineNum >= numLines) { - after = false; - } - - // we ignore all inline comments - if (commentIsNotAlone) { - return; - } - - const previousTokenOrComment = sourceCode.getTokenBefore(token, { includeComments: true }); - const nextTokenOrComment = sourceCode.getTokenAfter(token, { includeComments: true }); - - // check for newline before - if (!exceptionStartAllowed && before && !lodash.includes(commentAndEmptyLines, prevLineNum) && - !(astUtils.isCommentToken(previousTokenOrComment) && astUtils.isTokenOnSameLine(previousTokenOrComment, token))) { - const lineStart = token.range[0] - token.loc.start.column; - const range = [lineStart, lineStart]; - - context.report({ - node: token, - messageId: "before", - fix(fixer) { - return fixer.insertTextBeforeRange(range, "\n"); - } - }); - } - - // check for newline after - if (!exceptionEndAllowed && after && !lodash.includes(commentAndEmptyLines, nextLineNum) && - !(astUtils.isCommentToken(nextTokenOrComment) && astUtils.isTokenOnSameLine(token, nextTokenOrComment))) { - context.report({ - node: token, - messageId: "after", - fix(fixer) { - return fixer.insertTextAfter(token, "\n"); - } - }); - } - - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - Program() { - comments.forEach(token => { - if (token.type === "Line") { - if (options.beforeLineComment || options.afterLineComment) { - checkForEmptyLine(token, { - after: options.afterLineComment, - before: options.beforeLineComment - }); - } - } else if (token.type === "Block") { - if (options.beforeBlockComment || options.afterBlockComment) { - checkForEmptyLine(token, { - after: options.afterBlockComment, - before: options.beforeBlockComment - }); - } - } - }); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/lines-around-directive.js b/tools/node_modules/eslint/lib/rules/lines-around-directive.js deleted file mode 100644 index c2e5fd75aaa07d..00000000000000 --- a/tools/node_modules/eslint/lib/rules/lines-around-directive.js +++ /dev/null @@ -1,201 +0,0 @@ -/** - * @fileoverview Require or disallow newlines around directives. - * @author Kai Cataldo - * @deprecated - */ - -"use strict"; - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "require or disallow newlines around directives", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/lines-around-directive" - }, - - schema: [{ - oneOf: [ - { - enum: ["always", "never"] - }, - { - type: "object", - properties: { - before: { - enum: ["always", "never"] - }, - after: { - enum: ["always", "never"] - } - }, - additionalProperties: false, - minProperties: 2 - } - ] - }], - - fixable: "whitespace", - messages: { - expected: "Expected newline {{location}} \"{{value}}\" directive.", - unexpected: "Unexpected newline {{location}} \"{{value}}\" directive." - }, - deprecated: true, - replacedBy: ["padding-line-between-statements"] - }, - - create(context) { - const sourceCode = context.getSourceCode(); - const config = context.options[0] || "always"; - const expectLineBefore = typeof config === "string" ? config : config.before; - const expectLineAfter = typeof config === "string" ? config : config.after; - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Check if node is preceded by a blank newline. - * @param {ASTNode} node Node to check. - * @returns {boolean} Whether or not the passed in node is preceded by a blank newline. - */ - function hasNewlineBefore(node) { - const tokenBefore = sourceCode.getTokenBefore(node, { includeComments: true }); - const tokenLineBefore = tokenBefore ? tokenBefore.loc.end.line : 0; - - 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 astUtils.isSemicolonToken(lastToken) && 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 lastToken = getLastTokenOnLine(node); - const tokenAfter = sourceCode.getTokenAfter(lastToken, { includeComments: true }); - - return tokenAfter.loc.start.line - lastToken.loc.end.line >= 2; - } - - /** - * Report errors for newlines around directives. - * @param {ASTNode} node Node to check. - * @param {string} location Whether the error was found before or after the directive. - * @param {boolean} expected Whether or not a newline was expected or unexpected. - * @returns {void} - */ - function reportError(node, location, expected) { - context.report({ - node, - messageId: expected ? "expected" : "unexpected", - data: { - value: node.expression.value, - location - }, - fix(fixer) { - const lastToken = getLastTokenOnLine(node); - - if (expected) { - return location === "before" ? fixer.insertTextBefore(node, "\n") : fixer.insertTextAfter(lastToken, "\n"); - } - return fixer.removeRange(location === "before" ? [node.range[0] - 1, node.range[0]] : [lastToken.range[1], lastToken.range[1] + 1]); - } - }); - } - - /** - * Check lines around directives in node - * @param {ASTNode} node - node to check - * @returns {void} - */ - function checkDirectives(node) { - const directives = astUtils.getDirectivePrologue(node); - - if (!directives.length) { - return; - } - - const firstDirective = directives[0]; - const leadingComments = sourceCode.getCommentsBefore(firstDirective); - - /* - * Only check before the first directive if it is preceded by a comment or if it is at the top of - * the file and expectLineBefore is set to "never". This is to not force a newline at the top of - * the file if there are no comments as well as for compatibility with padded-blocks. - */ - if (leadingComments.length) { - if (expectLineBefore === "always" && !hasNewlineBefore(firstDirective)) { - reportError(firstDirective, "before", true); - } - - if (expectLineBefore === "never" && hasNewlineBefore(firstDirective)) { - reportError(firstDirective, "before", false); - } - } else if ( - node.type === "Program" && - expectLineBefore === "never" && - !leadingComments.length && - hasNewlineBefore(firstDirective) - ) { - reportError(firstDirective, "before", false); - } - - const lastDirective = directives[directives.length - 1]; - const statements = node.type === "Program" ? node.body : node.body.body; - - /* - * Do not check after the last directive if the body only - * contains a directive prologue and isn't followed by a comment to ensure - * this rule behaves well with padded-blocks. - */ - if (lastDirective === statements[statements.length - 1] && !lastDirective.trailingComments) { - return; - } - - if (expectLineAfter === "always" && !hasNewlineAfter(lastDirective)) { - reportError(lastDirective, "after", true); - } - - if (expectLineAfter === "never" && hasNewlineAfter(lastDirective)) { - reportError(lastDirective, "after", false); - } - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - Program: checkDirectives, - FunctionDeclaration: checkDirectives, - FunctionExpression: checkDirectives, - ArrowFunctionExpression: checkDirectives - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/lines-between-class-members.js b/tools/node_modules/eslint/lib/rules/lines-between-class-members.js deleted file mode 100644 index 19ae8a6a292c27..00000000000000 --- a/tools/node_modules/eslint/lib/rules/lines-between-class-members.js +++ /dev/null @@ -1,144 +0,0 @@ -/** - * @fileoverview Rule to check empty newline between class members - * @author 薛定谔的猫 - */ -"use strict"; - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "require or disallow an empty line between class members", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/lines-between-class-members" - }, - - fixable: "whitespace", - - schema: [ - { - enum: ["always", "never"] - }, - { - type: "object", - properties: { - exceptAfterSingleLine: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - messages: { - never: "Unexpected blank line between class members.", - always: "Expected blank line between class members." - } - }, - - create(context) { - - const options = []; - - options[0] = context.options[0] || "always"; - options[1] = context.options[1] || { exceptAfterSingleLine: false }; - - const sourceCode = context.getSourceCode(); - - /** - * Checks if there is padding between two tokens - * @param {Token} first The first token - * @param {Token} second The second token - * @returns {boolean} True if there is at least a line between the tokens - */ - function isPaddingBetweenTokens(first, second) { - const comments = sourceCode.getCommentsBefore(second); - const len = comments.length; - - // If there is no comments - if (len === 0) { - const linesBetweenFstAndSnd = second.loc.start.line - first.loc.end.line - 1; - - return linesBetweenFstAndSnd >= 1; - } - - - // If there are comments - let sumOfCommentLines = 0; // the numbers of lines of comments - let prevCommentLineNum = -1; // line number of the end of the previous comment - - for (let i = 0; i < len; i++) { - const commentLinesOfThisComment = comments[i].loc.end.line - comments[i].loc.start.line + 1; - - sumOfCommentLines += commentLinesOfThisComment; - - /* - * If this comment and the previous comment are in the same line, - * the count of comment lines is duplicated. So decrement sumOfCommentLines. - */ - if (prevCommentLineNum === comments[i].loc.start.line) { - sumOfCommentLines -= 1; - } - - prevCommentLineNum = comments[i].loc.end.line; - } - - /* - * If the first block and the first comment are in the same line, - * the count of comment lines is duplicated. So decrement sumOfCommentLines. - */ - if (first.loc.end.line === comments[0].loc.start.line) { - sumOfCommentLines -= 1; - } - - /* - * If the last comment and the second block are in the same line, - * the count of comment lines is duplicated. So decrement sumOfCommentLines. - */ - if (comments[len - 1].loc.end.line === second.loc.start.line) { - sumOfCommentLines -= 1; - } - - const linesBetweenFstAndSnd = second.loc.start.line - first.loc.end.line - 1; - - return linesBetweenFstAndSnd - sumOfCommentLines >= 1; - } - - return { - ClassBody(node) { - const body = node.body; - - for (let i = 0; i < body.length - 1; i++) { - const curFirst = sourceCode.getFirstToken(body[i]); - const curLast = sourceCode.getLastToken(body[i]); - const nextFirst = sourceCode.getFirstToken(body[i + 1]); - const isPadded = isPaddingBetweenTokens(curLast, nextFirst); - const isMulti = !astUtils.isTokenOnSameLine(curFirst, curLast); - const skip = !isMulti && options[1].exceptAfterSingleLine; - - - if ((options[0] === "always" && !skip && !isPadded) || - (options[0] === "never" && isPadded)) { - context.report({ - node: body[i + 1], - messageId: isPadded ? "never" : "always", - fix(fixer) { - return isPadded - ? fixer.replaceTextRange([curLast.range[1], nextFirst.range[0]], "\n") - : fixer.insertTextAfter(curLast, "\n"); - } - }); - } - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/max-classes-per-file.js b/tools/node_modules/eslint/lib/rules/max-classes-per-file.js deleted file mode 100644 index ae7be904f907f5..00000000000000 --- a/tools/node_modules/eslint/lib/rules/max-classes-per-file.js +++ /dev/null @@ -1,64 +0,0 @@ -/** - * @fileoverview Enforce a maximum number of classes per file - * @author James Garbutt - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce a maximum number of classes per file", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/max-classes-per-file" - }, - - schema: [ - { - type: "integer", - minimum: 1 - } - ], - - messages: { - maximumExceeded: "Number of classes per file must not exceed {{ max }}." - } - }, - create(context) { - - const maxClasses = context.options[0] || 1; - - let classCount = 0; - - return { - Program() { - classCount = 0; - }, - "Program:exit"(node) { - if (classCount > maxClasses) { - context.report({ - node, - messageId: "maximumExceeded", - data: { - max: maxClasses - } - }); - } - }, - "ClassDeclaration, ClassExpression"() { - classCount++; - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/max-depth.js b/tools/node_modules/eslint/lib/rules/max-depth.js deleted file mode 100644 index 3b997e21bc6384..00000000000000 --- a/tools/node_modules/eslint/lib/rules/max-depth.js +++ /dev/null @@ -1,153 +0,0 @@ -/** - * @fileoverview A rule to set the maximum depth block can be nested in a function. - * @author Ian Christian Myers - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce a maximum depth that blocks can be nested", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/max-depth" - }, - - schema: [ - { - oneOf: [ - { - type: "integer", - minimum: 0 - }, - { - type: "object", - properties: { - maximum: { - type: "integer", - minimum: 0, - default: 4 - }, - max: { - type: "integer", - minimum: 0, - default: 4 - } - }, - additionalProperties: false - } - ] - } - ], - messages: { - tooDeeply: "Blocks are nested too deeply ({{depth}})." - } - }, - - create(context) { - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - const functionStack = [], - option = context.options[0]; - let maxDepth = 4; - - if (typeof option === "object") { - maxDepth = option.maximum || option.max; - } - if (typeof option === "number") { - maxDepth = option; - } - - /** - * When parsing a new function, store it in our function stack - * @returns {void} - * @private - */ - function startFunction() { - functionStack.push(0); - } - - /** - * When parsing is done then pop out the reference - * @returns {void} - * @private - */ - function endFunction() { - functionStack.pop(); - } - - /** - * Save the block and Evaluate the node - * @param {ASTNode} node node to evaluate - * @returns {void} - * @private - */ - function pushBlock(node) { - const len = ++functionStack[functionStack.length - 1]; - - if (len > maxDepth) { - context.report({ node, messageId: "tooDeeply", data: { depth: len } }); - } - } - - /** - * Pop the saved block - * @returns {void} - * @private - */ - function popBlock() { - functionStack[functionStack.length - 1]--; - } - - //-------------------------------------------------------------------------- - // Public API - //-------------------------------------------------------------------------- - - return { - Program: startFunction, - FunctionDeclaration: startFunction, - FunctionExpression: startFunction, - ArrowFunctionExpression: startFunction, - - IfStatement(node) { - if (node.parent.type !== "IfStatement") { - pushBlock(node); - } - }, - SwitchStatement: pushBlock, - TryStatement: pushBlock, - DoWhileStatement: pushBlock, - WhileStatement: pushBlock, - WithStatement: pushBlock, - ForStatement: pushBlock, - ForInStatement: pushBlock, - ForOfStatement: pushBlock, - - "IfStatement:exit": popBlock, - "SwitchStatement:exit": popBlock, - "TryStatement:exit": popBlock, - "DoWhileStatement:exit": popBlock, - "WhileStatement:exit": popBlock, - "WithStatement:exit": popBlock, - "ForStatement:exit": popBlock, - "ForInStatement:exit": popBlock, - "ForOfStatement:exit": popBlock, - - "FunctionDeclaration:exit": endFunction, - "FunctionExpression:exit": endFunction, - "ArrowFunctionExpression:exit": endFunction, - "Program:exit": endFunction - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/max-len.js b/tools/node_modules/eslint/lib/rules/max-len.js deleted file mode 100644 index f6f0b6d3ac093d..00000000000000 --- a/tools/node_modules/eslint/lib/rules/max-len.js +++ /dev/null @@ -1,386 +0,0 @@ -/** - * @fileoverview Rule to check for max length on a line. - * @author Matt DuVall - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Constants -//------------------------------------------------------------------------------ - -const OPTIONS_SCHEMA = { - type: "object", - properties: { - code: { - type: "integer", - minimum: 0, - default: 80 - }, - comments: { - type: "integer", - minimum: 0 - }, - tabWidth: { - type: "integer", - minimum: 0, - default: 4 - }, - ignorePattern: { - type: "string" - }, - ignoreComments: { - type: "boolean", - default: false - }, - ignoreStrings: { - type: "boolean", - default: false - }, - ignoreUrls: { - type: "boolean", - default: false - }, - ignoreTemplateLiterals: { - type: "boolean", - default: false - }, - ignoreRegExpLiterals: { - type: "boolean", - default: false - }, - ignoreTrailingComments: { - type: "boolean", - default: false - } - }, - additionalProperties: false -}; - -const OPTIONS_OR_INTEGER_SCHEMA = { - anyOf: [ - OPTIONS_SCHEMA, - { - type: "integer", - minimum: 0 - } - ] -}; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce a maximum line length", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/max-len" - }, - - schema: [ - OPTIONS_OR_INTEGER_SCHEMA, - OPTIONS_OR_INTEGER_SCHEMA, - OPTIONS_SCHEMA - ], - messages: { - max: "Line {{lineNumber}} exceeds the maximum line length of {{maxLength}}.", - maxComment: "Line {{lineNumber}} exceeds the maximum comment line length of {{maxCommentLength}}." - } - }, - - create(context) { - - /* - * Inspired by http://tools.ietf.org/html/rfc3986#appendix-B, however: - * - They're matching an entire string that we know is a URI - * - We're matching part of a string where we think there *might* be a URL - * - We're only concerned about URLs, as picking out any URI would cause - * too many false positives - * - We don't care about matching the entire URL, any small segment is fine - */ - const URL_REGEXP = /[^:/?#]:\/\/[^?#]/; - - const sourceCode = context.getSourceCode(); - - /** - * Computes the length of a line that may contain tabs. The width of each - * tab will be the number of spaces to the next tab stop. - * @param {string} line The line. - * @param {int} tabWidth The width of each tab stop in spaces. - * @returns {int} The computed line length. - * @private - */ - function computeLineLength(line, tabWidth) { - let extraCharacterCount = 0; - - line.replace(/\t/g, (match, offset) => { - const totalOffset = offset + extraCharacterCount, - previousTabStopOffset = tabWidth ? totalOffset % tabWidth : 0, - spaceCount = tabWidth - previousTabStopOffset; - - extraCharacterCount += spaceCount - 1; // -1 for the replaced tab - }); - return Array.from(line).length + extraCharacterCount; - } - - // The options object must be the last option specified… - const options = Object.assign({}, context.options[context.options.length - 1]); - - // …but max code length… - if (typeof context.options[0] === "number") { - options.code = context.options[0]; - } - - // …and tabWidth can be optionally specified directly as integers. - if (typeof context.options[1] === "number") { - options.tabWidth = context.options[1]; - } - - const maxLength = options.code || 80, - tabWidth = options.tabWidth || 4, - 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; - let ignorePattern = options.ignorePattern || null; - - if (ignorePattern) { - ignorePattern = new RegExp(ignorePattern); - } - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Tells if a given comment is trailing: it starts on the current line and - * extends to or past the end of the current line. - * @param {string} line The source line we want to check for a trailing comment on - * @param {number} lineNumber The one-indexed line number for line - * @param {ASTNode} comment The comment to inspect - * @returns {boolean} If the comment is trailing on the given line - */ - function isTrailingComment(line, lineNumber, comment) { - return comment && - (comment.loc.start.line === lineNumber && lineNumber <= comment.loc.end.line) && - (comment.loc.end.line > lineNumber || comment.loc.end.column === line.length); - } - - /** - * Tells if a comment encompasses the entire line. - * @param {string} line The source line with a trailing comment - * @param {number} lineNumber The one-indexed line number this is on - * @param {ASTNode} comment The comment to remove - * @returns {boolean} If the comment covers the entire line - */ - function isFullLineComment(line, lineNumber, comment) { - const start = comment.loc.start, - end = comment.loc.end, - isFirstTokenOnLine = !line.slice(0, comment.loc.start.column).trim(); - - return comment && - (start.line < lineNumber || (start.line === lineNumber && isFirstTokenOnLine)) && - (end.line > lineNumber || (end.line === lineNumber && end.column === line.length)); - } - - /** - * Gets the line after the comment and any remaining trailing whitespace is - * stripped. - * @param {string} line The source line with a trailing comment - * @param {ASTNode} comment The comment to remove - * @returns {string} Line without comment and trailing whitepace - */ - function stripTrailingComment(line, comment) { - - // loc.column is zero-indexed - return line.slice(0, comment.loc.start.column).replace(/\s+$/, ""); - } - - /** - * Ensure that an array exists at [key] on `object`, and add `value` to it. - * - * @param {Object} object the object to mutate - * @param {string} key the object's key - * @param {*} value the value to add - * @returns {void} - * @private - */ - function ensureArrayAndPush(object, key, value) { - if (!Array.isArray(object[key])) { - object[key] = []; - } - object[key].push(value); - } - - /** - * Retrieves an array containing all strings (" or ') in the source code. - * - * @returns {ASTNode[]} An array of string nodes. - */ - function getAllStrings() { - return sourceCode.ast.tokens.filter(token => (token.type === "String" || - (token.type === "JSXText" && sourceCode.getNodeByRangeIndex(token.range[0] - 1).type === "JSXAttribute"))); - } - - /** - * Retrieves an array containing all template literals in the source code. - * - * @returns {ASTNode[]} An array of template literal nodes. - */ - function getAllTemplateLiterals() { - 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"); - } - - - /** - * A reducer to group an AST node by line number, both start and end. - * - * @param {Object} acc the accumulator - * @param {ASTNode} node the AST node in question - * @returns {Object} the modified accumulator - * @private - */ - function groupByLineNumber(acc, node) { - for (let i = node.loc.start.line; i <= node.loc.end.line; ++i) { - ensureArrayAndPush(acc, i, node); - } - return acc; - } - - /** - * Check the program for max length - * @param {ASTNode} node Node to examine - * @returns {void} - * @private - */ - function checkProgramForMaxLength(node) { - - // split (honors line-ending) - const lines = sourceCode.lines, - - // list of comments to ignore - comments = ignoreComments || maxCommentLength || ignoreTrailingComments ? sourceCode.getAllComments() : []; - - // we iterate over comments in parallel with the lines - let commentsIndex = 0; - - const strings = getAllStrings(); - const stringsByLine = strings.reduce(groupByLineNumber, {}); - - const templateLiterals = getAllTemplateLiterals(); - const templateLiteralsByLine = templateLiterals.reduce(groupByLineNumber, {}); - - const regExpLiterals = getAllRegExpLiterals(); - const regExpLiteralsByLine = regExpLiterals.reduce(groupByLineNumber, {}); - - lines.forEach((line, i) => { - - // i is zero-indexed, line numbers are one-indexed - const lineNumber = i + 1; - - /* - * if we're checking comment length; we need to know whether this - * line is a comment - */ - let lineIsComment = false; - let textToMeasure; - - /* - * We can short-circuit the comment checks if we're already out of - * comments to check. - */ - if (commentsIndex < comments.length) { - let comment = null; - - // iterate over comments until we find one past the current line - do { - comment = comments[++commentsIndex]; - } while (comment && comment.loc.start.line <= lineNumber); - - // and step back by one - comment = comments[--commentsIndex]; - - if (isFullLineComment(line, lineNumber, comment)) { - lineIsComment = true; - textToMeasure = line; - } else if (ignoreTrailingComments && isTrailingComment(line, lineNumber, comment)) { - textToMeasure = stripTrailingComment(line, comment); - } else { - textToMeasure = line; - } - } else { - textToMeasure = line; - } - if (ignorePattern && ignorePattern.test(textToMeasure) || - ignoreUrls && URL_REGEXP.test(textToMeasure) || - ignoreStrings && stringsByLine[lineNumber] || - ignoreTemplateLiterals && templateLiteralsByLine[lineNumber] || - ignoreRegExpLiterals && regExpLiteralsByLine[lineNumber] - ) { - - // ignore this line - return; - } - - const lineLength = computeLineLength(textToMeasure, tabWidth); - const commentLengthApplies = lineIsComment && maxCommentLength; - - if (lineIsComment && ignoreComments) { - return; - } - - if (commentLengthApplies) { - if (lineLength > maxCommentLength) { - context.report({ - node, - loc: { line: lineNumber, column: 0 }, - messageId: "maxComment", - data: { - lineNumber: i + 1, - maxCommentLength - } - }); - } - } else if (lineLength > maxLength) { - context.report({ - node, - loc: { line: lineNumber, column: 0 }, - messageId: "max", - data: { - lineNumber: i + 1, - maxLength - } - }); - } - }); - } - - - //-------------------------------------------------------------------------- - // Public API - //-------------------------------------------------------------------------- - - return { - Program: checkProgramForMaxLength - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/max-lines-per-function.js b/tools/node_modules/eslint/lib/rules/max-lines-per-function.js deleted file mode 100644 index 2a0e1a645a375b..00000000000000 --- a/tools/node_modules/eslint/lib/rules/max-lines-per-function.js +++ /dev/null @@ -1,219 +0,0 @@ -/** - * @fileoverview A rule to set the maximum number of line of code in a function. - * @author Pete Ward - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Constants -//------------------------------------------------------------------------------ - -const OPTIONS_SCHEMA = { - type: "object", - properties: { - max: { - type: "integer", - minimum: 0, - default: 50 - }, - skipComments: { - type: "boolean", - default: false - }, - skipBlankLines: { - type: "boolean", - default: false - }, - IIFEs: { - type: "boolean", - default: false - } - }, - additionalProperties: false -}; - -const OPTIONS_OR_INTEGER_SCHEMA = { - oneOf: [ - OPTIONS_SCHEMA, - { - type: "integer", - minimum: 1 - } - ] -}; - -/** - * Given a list of comment nodes, return a map with numeric keys (source code line numbers) and comment token values. - * @param {Array} comments An array of comment nodes. - * @returns {Map.} A map with numeric keys (source code line numbers) and comment token values. - */ -function getCommentLineNumbers(comments) { - const map = new Map(); - - if (!comments) { - return map; - } - comments.forEach(comment => { - for (let i = comment.loc.start.line; i <= comment.loc.end.line; i++) { - map.set(i, comment); - } - }); - return map; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce a maximum number of line of code in a function", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/max-lines-per-function" - }, - - schema: [ - OPTIONS_OR_INTEGER_SCHEMA - ], - messages: { - exceed: "{{name}} has too many lines ({{lineCount}}). Maximum allowed is {{maxLines}}." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - const lines = sourceCode.lines; - - const option = context.options[0]; - let maxLines = 50; - let skipComments = false; - let skipBlankLines = false; - let IIFEs = false; - - if (typeof option === "object") { - maxLines = option.max; - skipComments = option.skipComments; - skipBlankLines = option.skipBlankLines; - IIFEs = option.IIFEs; - } else if (typeof option === "number") { - maxLines = option; - } - - const commentLineNumbers = getCommentLineNumbers(sourceCode.getAllComments()); - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Tells if a comment encompasses the entire line. - * @param {string} line The source line with a trailing comment - * @param {number} lineNumber The one-indexed line number this is on - * @param {ASTNode} comment The comment to remove - * @returns {boolean} If the comment covers the entire line - */ - function isFullLineComment(line, lineNumber, comment) { - const start = comment.loc.start, - end = comment.loc.end, - isFirstTokenOnLine = start.line === lineNumber && !line.slice(0, start.column).trim(), - isLastTokenOnLine = end.line === lineNumber && !line.slice(end.column).trim(); - - return comment && - (start.line < lineNumber || isFirstTokenOnLine) && - (end.line > lineNumber || isLastTokenOnLine); - } - - /** - * Identifies is a node is a FunctionExpression which is part of an IIFE - * @param {ASTNode} node Node to test - * @returns {boolean} True if it's an IIFE - */ - function isIIFE(node) { - return node.type === "FunctionExpression" && node.parent && node.parent.type === "CallExpression" && node.parent.callee === node; - } - - /** - * Identifies is a node is a FunctionExpression which is embedded within a MethodDefinition or Property - * @param {ASTNode} node Node to test - * @returns {boolean} True if it's a FunctionExpression embedded within a MethodDefinition or Property - */ - function isEmbedded(node) { - if (!node.parent) { - return false; - } - if (node !== node.parent.value) { - return false; - } - if (node.parent.type === "MethodDefinition") { - return true; - } - if (node.parent.type === "Property") { - return node.parent.method === true || node.parent.kind === "get" || node.parent.kind === "set"; - } - return false; - } - - /** - * Count the lines in the function - * @param {ASTNode} funcNode Function AST node - * @returns {void} - * @private - */ - function processFunction(funcNode) { - const node = isEmbedded(funcNode) ? funcNode.parent : funcNode; - - if (!IIFEs && isIIFE(node)) { - return; - } - let lineCount = 0; - - for (let i = node.loc.start.line - 1; i < node.loc.end.line; ++i) { - const line = lines[i]; - - if (skipComments) { - if (commentLineNumbers.has(i + 1) && isFullLineComment(line, i + 1, commentLineNumbers.get(i + 1))) { - continue; - } - } - - if (skipBlankLines) { - if (line.match(/^\s*$/)) { - continue; - } - } - - lineCount++; - } - - if (lineCount > maxLines) { - const name = astUtils.getFunctionNameWithKind(funcNode); - - context.report({ - node, - messageId: "exceed", - data: { name, lineCount, maxLines } - }); - } - } - - //-------------------------------------------------------------------------- - // Public API - //-------------------------------------------------------------------------- - - return { - FunctionDeclaration: processFunction, - FunctionExpression: processFunction, - ArrowFunctionExpression: processFunction - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/max-lines.js b/tools/node_modules/eslint/lib/rules/max-lines.js deleted file mode 100644 index 0fae4ec2fa13fa..00000000000000 --- a/tools/node_modules/eslint/lib/rules/max-lines.js +++ /dev/null @@ -1,151 +0,0 @@ -/** - * @fileoverview enforce a maximum file length - * @author Alberto Rodríguez - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const lodash = require("lodash"); -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce a maximum number of lines per file", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/max-lines" - }, - - schema: [ - { - oneOf: [ - { - type: "integer", - minimum: 0 - }, - { - type: "object", - properties: { - max: { - type: "integer", - minimum: 0, - default: 300 - }, - skipComments: { - type: "boolean", - default: false - }, - skipBlankLines: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ] - } - ], - messages: { - exceed: "File must be at most {{max}} lines long. It's {{actual}} lines long." - } - }, - - create(context) { - const option = context.options[0]; - let max = 300; - - if (typeof option === "object") { - max = option.max; - } else if (typeof option === "number") { - max = option; - } - - const skipComments = option && option.skipComments; - const skipBlankLines = option && option.skipBlankLines; - - const sourceCode = context.getSourceCode(); - - /** - * Returns whether or not a token is a comment node type - * @param {Token} token The token to check - * @returns {boolean} True if the token is a comment node - */ - function isCommentNodeType(token) { - return token && (token.type === "Block" || token.type === "Line"); - } - - /** - * Returns the line numbers of a comment that don't have any code on the same line - * @param {Node} comment The comment node to check - * @returns {number[]} The line numbers - */ - function getLinesWithoutCode(comment) { - let start = comment.loc.start.line; - let end = comment.loc.end.line; - - let token; - - token = comment; - do { - token = sourceCode.getTokenBefore(token, { includeComments: true }); - } while (isCommentNodeType(token)); - - if (token && astUtils.isTokenOnSameLine(token, comment)) { - start += 1; - } - - token = comment; - do { - token = sourceCode.getTokenAfter(token, { includeComments: true }); - } while (isCommentNodeType(token)); - - if (token && astUtils.isTokenOnSameLine(comment, token)) { - end -= 1; - } - - if (start <= end) { - return lodash.range(start, end + 1); - } - return []; - } - - return { - "Program:exit"() { - let lines = sourceCode.lines.map((text, i) => ({ lineNumber: i + 1, text })); - - if (skipBlankLines) { - lines = lines.filter(l => l.text.trim() !== ""); - } - - if (skipComments) { - const comments = sourceCode.getAllComments(); - - const commentLines = lodash.flatten(comments.map(comment => getLinesWithoutCode(comment))); - - lines = lines.filter(l => !lodash.includes(commentLines, l.lineNumber)); - } - - if (lines.length > max) { - context.report({ - loc: { line: 1, column: 0 }, - messageId: "exceed", - data: { - max, - actual: lines.length - } - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/max-nested-callbacks.js b/tools/node_modules/eslint/lib/rules/max-nested-callbacks.js deleted file mode 100644 index cbbb0ed6c70d9a..00000000000000 --- a/tools/node_modules/eslint/lib/rules/max-nested-callbacks.js +++ /dev/null @@ -1,116 +0,0 @@ -/** - * @fileoverview Rule to enforce a maximum number of nested callbacks. - * @author Ian Christian Myers - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce a maximum depth that callbacks can be nested", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/max-nested-callbacks" - }, - - schema: [ - { - oneOf: [ - { - type: "integer", - minimum: 0 - }, - { - type: "object", - properties: { - maximum: { - type: "integer", - minimum: 0, - default: 10 - }, - max: { - type: "integer", - minimum: 0, - default: 10 - } - }, - additionalProperties: false - } - ] - } - ], - messages: { - exceed: "Too many nested callbacks ({{num}}). Maximum allowed is {{max}}." - } - }, - - create(context) { - - //-------------------------------------------------------------------------- - // Constants - //-------------------------------------------------------------------------- - const option = context.options[0]; - let THRESHOLD = 10; - - if (typeof option === "object") { - THRESHOLD = option.maximum || option.max; - } else if (typeof option === "number") { - THRESHOLD = option; - } - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - const callbackStack = []; - - /** - * Checks a given function node for too many callbacks. - * @param {ASTNode} node The node to check. - * @returns {void} - * @private - */ - function checkFunction(node) { - const parent = node.parent; - - if (parent.type === "CallExpression") { - callbackStack.push(node); - } - - if (callbackStack.length > THRESHOLD) { - const opts = { num: callbackStack.length, max: THRESHOLD }; - - context.report({ node, messageId: "exceed", data: opts }); - } - } - - /** - * Pops the call stack. - * @returns {void} - * @private - */ - function popStack() { - callbackStack.pop(); - } - - //-------------------------------------------------------------------------- - // Public API - //-------------------------------------------------------------------------- - - return { - ArrowFunctionExpression: checkFunction, - "ArrowFunctionExpression:exit": popStack, - - FunctionExpression: checkFunction, - "FunctionExpression:exit": popStack - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/max-params.js b/tools/node_modules/eslint/lib/rules/max-params.js deleted file mode 100644 index 5e1e558ab53e0b..00000000000000 --- a/tools/node_modules/eslint/lib/rules/max-params.js +++ /dev/null @@ -1,102 +0,0 @@ -/** - * @fileoverview Rule to flag when a function has too many parameters - * @author Ilya Volodin - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const lodash = require("lodash"); - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce a maximum number of parameters in function definitions", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/max-params" - }, - - schema: [ - { - oneOf: [ - { - type: "integer", - minimum: 0 - }, - { - type: "object", - properties: { - maximum: { - type: "integer", - minimum: 0, - default: 3 - }, - max: { - type: "integer", - minimum: 0, - default: 3 - } - }, - additionalProperties: false - } - ] - } - ], - messages: { - exceed: "{{name}} has too many parameters ({{count}}). Maximum allowed is {{max}}." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - const option = context.options[0]; - let numParams = 3; - - if (typeof option === "object") { - numParams = option.maximum || option.max; - } - if (typeof option === "number") { - numParams = option; - } - - /** - * Checks a function to see if it has too many parameters. - * @param {ASTNode} node The node to check. - * @returns {void} - * @private - */ - function checkFunction(node) { - if (node.params.length > numParams) { - context.report({ - loc: astUtils.getFunctionHeadLoc(node, sourceCode), - node, - messageId: "exceed", - data: { - name: lodash.upperFirst(astUtils.getFunctionNameWithKind(node)), - count: node.params.length, - max: numParams - } - }); - } - } - - return { - FunctionDeclaration: checkFunction, - ArrowFunctionExpression: checkFunction, - FunctionExpression: checkFunction - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/max-statements-per-line.js b/tools/node_modules/eslint/lib/rules/max-statements-per-line.js deleted file mode 100644 index 444bdfa21aa1b0..00000000000000 --- a/tools/node_modules/eslint/lib/rules/max-statements-per-line.js +++ /dev/null @@ -1,200 +0,0 @@ -/** - * @fileoverview Specify the maximum number of statements allowed per line. - * @author Kenneth Williams - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce a maximum number of statements allowed per line", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/max-statements-per-line" - }, - - schema: [ - { - type: "object", - properties: { - max: { - type: "integer", - minimum: 1, - default: 1 - } - }, - additionalProperties: false - } - ], - messages: { - exceed: "This line has {{numberOfStatementsOnThisLine}} {{statements}}. Maximum allowed is {{maxStatementsPerLine}}." - } - }, - - create(context) { - - const sourceCode = context.getSourceCode(), - options = context.options[0] || {}, - maxStatementsPerLine = typeof options.max !== "undefined" ? options.max : 1; - - let lastStatementLine = 0, - numberOfStatementsOnThisLine = 0, - firstExtraStatement; - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - const SINGLE_CHILD_ALLOWED = /^(?:(?:DoWhile|For|ForIn|ForOf|If|Labeled|While)Statement|Export(?:Default|Named)Declaration)$/; - - /** - * Reports with the first extra statement, and clears it. - * - * @returns {void} - */ - function reportFirstExtraStatementAndClear() { - if (firstExtraStatement) { - context.report({ - node: firstExtraStatement, - messageId: "exceed", - data: { - numberOfStatementsOnThisLine, - maxStatementsPerLine, - statements: numberOfStatementsOnThisLine === 1 ? "statement" : "statements" - } - }); - } - firstExtraStatement = null; - } - - /** - * Gets the actual last token of a given node. - * - * @param {ASTNode} node - A node to get. This is a node except EmptyStatement. - * @returns {Token} The actual last token. - */ - function getActualLastToken(node) { - return sourceCode.getLastToken(node, astUtils.isNotSemicolonToken); - } - - /** - * Addresses a given node. - * It updates the state of this rule, then reports the node if the node violated this rule. - * - * @param {ASTNode} node - A node to check. - * @returns {void} - */ - function enterStatement(node) { - const line = node.loc.start.line; - - /* - * Skip to allow non-block statements if this is direct child of control statements. - * `if (a) foo();` is counted as 1. - * But `if (a) foo(); else foo();` should be counted as 2. - */ - if (SINGLE_CHILD_ALLOWED.test(node.parent.type) && - node.parent.alternate !== node - ) { - return; - } - - // Update state. - if (line === lastStatementLine) { - numberOfStatementsOnThisLine += 1; - } else { - reportFirstExtraStatementAndClear(); - numberOfStatementsOnThisLine = 1; - lastStatementLine = line; - } - - // Reports if the node violated this rule. - if (numberOfStatementsOnThisLine === maxStatementsPerLine + 1) { - firstExtraStatement = firstExtraStatement || node; - } - } - - /** - * Updates the state of this rule with the end line of leaving node to check with the next statement. - * - * @param {ASTNode} node - A node to check. - * @returns {void} - */ - function leaveStatement(node) { - const line = getActualLastToken(node).loc.end.line; - - // Update state. - if (line !== lastStatementLine) { - reportFirstExtraStatementAndClear(); - numberOfStatementsOnThisLine = 1; - lastStatementLine = line; - } - } - - //-------------------------------------------------------------------------- - // Public API - //-------------------------------------------------------------------------- - - return { - BreakStatement: enterStatement, - ClassDeclaration: enterStatement, - ContinueStatement: enterStatement, - DebuggerStatement: enterStatement, - DoWhileStatement: enterStatement, - ExpressionStatement: enterStatement, - ForInStatement: enterStatement, - ForOfStatement: enterStatement, - ForStatement: enterStatement, - FunctionDeclaration: enterStatement, - IfStatement: enterStatement, - ImportDeclaration: enterStatement, - LabeledStatement: enterStatement, - ReturnStatement: enterStatement, - SwitchStatement: enterStatement, - ThrowStatement: enterStatement, - TryStatement: enterStatement, - VariableDeclaration: enterStatement, - WhileStatement: enterStatement, - WithStatement: enterStatement, - ExportNamedDeclaration: enterStatement, - ExportDefaultDeclaration: enterStatement, - ExportAllDeclaration: enterStatement, - - "BreakStatement:exit": leaveStatement, - "ClassDeclaration:exit": leaveStatement, - "ContinueStatement:exit": leaveStatement, - "DebuggerStatement:exit": leaveStatement, - "DoWhileStatement:exit": leaveStatement, - "ExpressionStatement:exit": leaveStatement, - "ForInStatement:exit": leaveStatement, - "ForOfStatement:exit": leaveStatement, - "ForStatement:exit": leaveStatement, - "FunctionDeclaration:exit": leaveStatement, - "IfStatement:exit": leaveStatement, - "ImportDeclaration:exit": leaveStatement, - "LabeledStatement:exit": leaveStatement, - "ReturnStatement:exit": leaveStatement, - "SwitchStatement:exit": leaveStatement, - "ThrowStatement:exit": leaveStatement, - "TryStatement:exit": leaveStatement, - "VariableDeclaration:exit": leaveStatement, - "WhileStatement:exit": leaveStatement, - "WithStatement:exit": leaveStatement, - "ExportNamedDeclaration:exit": leaveStatement, - "ExportDefaultDeclaration:exit": leaveStatement, - "ExportAllDeclaration:exit": leaveStatement, - "Program:exit": reportFirstExtraStatementAndClear - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/max-statements.js b/tools/node_modules/eslint/lib/rules/max-statements.js deleted file mode 100644 index cd0e50ae399910..00000000000000 --- a/tools/node_modules/eslint/lib/rules/max-statements.js +++ /dev/null @@ -1,174 +0,0 @@ -/** - * @fileoverview A rule to set the maximum number of statements in a function. - * @author Ian Christian Myers - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const lodash = require("lodash"); - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce a maximum number of statements allowed in function blocks", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/max-statements" - }, - - schema: [ - { - oneOf: [ - { - type: "integer", - minimum: 0 - }, - { - type: "object", - properties: { - maximum: { - type: "integer", - minimum: 0, - default: 10 - }, - max: { - type: "integer", - minimum: 0, - default: 10 - } - }, - additionalProperties: false - } - ] - }, - { - type: "object", - properties: { - ignoreTopLevelFunctions: { - type: "boolean" - } - }, - additionalProperties: false - } - ], - messages: { - exceed: "{{name}} has too many statements ({{count}}). Maximum allowed is {{max}}." - } - }, - - create(context) { - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - const functionStack = [], - option = context.options[0], - ignoreTopLevelFunctions = context.options[1] && context.options[1].ignoreTopLevelFunctions || false, - topLevelFunctions = []; - let maxStatements = 10; - - if (typeof option === "object") { - maxStatements = option.maximum || option.max; - } else if (typeof option === "number") { - maxStatements = option; - } - - /** - * Reports a node if it has too many statements - * @param {ASTNode} node node to evaluate - * @param {int} count Number of statements in node - * @param {int} max Maximum number of statements allowed - * @returns {void} - * @private - */ - function reportIfTooManyStatements(node, count, max) { - if (count > max) { - const name = lodash.upperFirst(astUtils.getFunctionNameWithKind(node)); - - context.report({ - node, - messageId: "exceed", - data: { name, count, max } - }); - } - } - - /** - * When parsing a new function, store it in our function stack - * @returns {void} - * @private - */ - function startFunction() { - functionStack.push(0); - } - - /** - * Evaluate the node at the end of function - * @param {ASTNode} node node to evaluate - * @returns {void} - * @private - */ - function endFunction(node) { - const count = functionStack.pop(); - - if (ignoreTopLevelFunctions && functionStack.length === 0) { - topLevelFunctions.push({ node, count }); - } else { - reportIfTooManyStatements(node, count, maxStatements); - } - } - - /** - * Increment the count of the functions - * @param {ASTNode} node node to evaluate - * @returns {void} - * @private - */ - function countStatements(node) { - functionStack[functionStack.length - 1] += node.body.length; - } - - //-------------------------------------------------------------------------- - // Public API - //-------------------------------------------------------------------------- - - return { - FunctionDeclaration: startFunction, - FunctionExpression: startFunction, - ArrowFunctionExpression: startFunction, - - BlockStatement: countStatements, - - "FunctionDeclaration:exit": endFunction, - "FunctionExpression:exit": endFunction, - "ArrowFunctionExpression:exit": endFunction, - - "Program:exit"() { - if (topLevelFunctions.length === 1) { - return; - } - - topLevelFunctions.forEach(element => { - const count = element.count; - const node = element.node; - - reportIfTooManyStatements(node, count, maxStatements); - }); - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/multiline-comment-style.js b/tools/node_modules/eslint/lib/rules/multiline-comment-style.js deleted file mode 100644 index e262c255869cf2..00000000000000 --- a/tools/node_modules/eslint/lib/rules/multiline-comment-style.js +++ /dev/null @@ -1,299 +0,0 @@ -/** - * @fileoverview enforce a particular style for multiline comments - * @author Teddy Katz - */ -"use strict"; - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce a particular style for multiline comments", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/multiline-comment-style" - }, - - fixable: "whitespace", - schema: [{ enum: ["starred-block", "separate-lines", "bare-block"] }], - messages: { - expectedBlock: "Expected a block comment instead of consecutive line comments.", - startNewline: "Expected a linebreak after '/*'.", - endNewline: "Expected a linebreak before '*/'.", - missingStar: "Expected a '*' at the start of this line.", - alignment: "Expected this line to be aligned with the start of the comment.", - expectedLines: "Expected multiple line comments instead of a block comment." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - const option = context.options[0] || "starred-block"; - - //---------------------------------------------------------------------- - // Helpers - //---------------------------------------------------------------------- - - /** - * Gets a list of comment lines in a group - * @param {Token[]} commentGroup A group of comments, containing either multiple line comments or a single block comment - * @returns {string[]} A list of comment lines - */ - function getCommentLines(commentGroup) { - if (commentGroup[0].type === "Line") { - return commentGroup.map(comment => comment.value); - } - return commentGroup[0].value - .split(astUtils.LINEBREAK_MATCHER) - .map(line => line.replace(/^\s*\*?/, "")); - } - - /** - * Converts a comment into starred-block form - * @param {Token} firstComment The first comment of the group being converted - * @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment - * @returns {string} A representation of the comment value in starred-block form, excluding start and end markers - */ - function convertToStarredBlock(firstComment, commentLinesList) { - const initialOffset = sourceCode.text.slice(firstComment.range[0] - firstComment.loc.start.column, firstComment.range[0]); - const starredLines = commentLinesList.map(line => `${initialOffset} *${line}`); - - return `\n${starredLines.join("\n")}\n${initialOffset} `; - } - - /** - * Converts a comment into separate-line form - * @param {Token} firstComment The first comment of the group being converted - * @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment - * @returns {string} A representation of the comment value in separate-line form - */ - function convertToSeparateLines(firstComment, commentLinesList) { - const initialOffset = sourceCode.text.slice(firstComment.range[0] - firstComment.loc.start.column, firstComment.range[0]); - const separateLines = commentLinesList.map(line => `// ${line.trim()}`); - - return separateLines.join(`\n${initialOffset}`); - } - - /** - * Converts a comment into bare-block form - * @param {Token} firstComment The first comment of the group being converted - * @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment - * @returns {string} A representation of the comment value in bare-block form - */ - function convertToBlock(firstComment, commentLinesList) { - const initialOffset = sourceCode.text.slice(firstComment.range[0] - firstComment.loc.start.column, firstComment.range[0]); - const blockLines = commentLinesList.map(line => line.trim()); - - return `/* ${blockLines.join(`\n${initialOffset} `)} */`; - } - - /** - * Check a comment is JSDoc form - * @param {Token[]} commentGroup A group of comments, containing either multiple line comments or a single block comment - * @returns {boolean} if commentGroup is JSDoc form, return true - */ - function isJSDoc(commentGroup) { - const lines = commentGroup[0].value.split(astUtils.LINEBREAK_MATCHER); - - return commentGroup[0].type === "Block" && - /^\*\s*$/.test(lines[0]) && - lines.slice(1, -1).every(line => /^\s* /.test(line)) && - /^\s*$/.test(lines[lines.length - 1]); - } - - /** - * Each method checks a group of comments to see if it's valid according to the given option. - * @param {Token[]} commentGroup A list of comments that appear together. This will either contain a single - * block comment or multiple line comments. - * @returns {void} - */ - const commentGroupCheckers = { - "starred-block"(commentGroup) { - const commentLines = getCommentLines(commentGroup); - - if (commentLines.some(value => value.includes("*/"))) { - return; - } - - if (commentGroup.length > 1) { - context.report({ - loc: { - start: commentGroup[0].loc.start, - end: commentGroup[commentGroup.length - 1].loc.end - }, - messageId: "expectedBlock", - fix(fixer) { - const range = [commentGroup[0].range[0], commentGroup[commentGroup.length - 1].range[1]]; - const starredBlock = `/*${convertToStarredBlock(commentGroup[0], commentLines)}*/`; - - return commentLines.some(value => value.startsWith("/")) - ? null - : fixer.replaceTextRange(range, starredBlock); - } - }); - } else { - const block = commentGroup[0]; - const lines = block.value.split(astUtils.LINEBREAK_MATCHER); - const expectedLinePrefix = `${sourceCode.text.slice(block.range[0] - block.loc.start.column, block.range[0])} *`; - - if (!/^\*?\s*$/.test(lines[0])) { - const start = block.value.startsWith("*") ? block.range[0] + 1 : block.range[0]; - - context.report({ - loc: { - start: block.loc.start, - end: { line: block.loc.start.line, column: block.loc.start.column + 2 } - }, - messageId: "startNewline", - fix: fixer => fixer.insertTextAfterRange([start, start + 2], `\n${expectedLinePrefix}`) - }); - } - - if (!/^\s*$/.test(lines[lines.length - 1])) { - context.report({ - loc: { - start: { line: block.loc.end.line, column: block.loc.end.column - 2 }, - end: block.loc.end - }, - messageId: "endNewline", - fix: fixer => fixer.replaceTextRange([block.range[1] - 2, block.range[1]], `\n${expectedLinePrefix}/`) - }); - } - - for (let lineNumber = block.loc.start.line + 1; lineNumber <= block.loc.end.line; lineNumber++) { - const lineText = sourceCode.lines[lineNumber - 1]; - - if (!lineText.startsWith(expectedLinePrefix)) { - context.report({ - loc: { - start: { line: lineNumber, column: 0 }, - end: { line: lineNumber, column: sourceCode.lines[lineNumber - 1].length } - }, - messageId: /^\s*\*/.test(lineText) - ? "alignment" - : "missingStar", - fix(fixer) { - const lineStartIndex = sourceCode.getIndexFromLoc({ line: lineNumber, column: 0 }); - const linePrefixLength = lineText.match(/^\s*\*? ?/)[0].length; - const commentStartIndex = lineStartIndex + linePrefixLength; - - const replacementText = lineNumber === block.loc.end.line || lineText.length === linePrefixLength - ? expectedLinePrefix - : `${expectedLinePrefix} `; - - return fixer.replaceTextRange([lineStartIndex, commentStartIndex], replacementText); - } - }); - } - } - } - }, - "separate-lines"(commentGroup) { - if (!isJSDoc(commentGroup) && commentGroup[0].type === "Block") { - const commentLines = getCommentLines(commentGroup); - const block = commentGroup[0]; - const tokenAfter = sourceCode.getTokenAfter(block, { includeComments: true }); - - if (tokenAfter && block.loc.end.line === tokenAfter.loc.start.line) { - return; - } - - context.report({ - loc: { - start: block.loc.start, - end: { line: block.loc.start.line, column: block.loc.start.column + 2 } - }, - messageId: "expectedLines", - fix(fixer) { - return fixer.replaceText(block, convertToSeparateLines(block, commentLines.filter(line => line))); - } - }); - } - }, - "bare-block"(commentGroup) { - if (!isJSDoc(commentGroup)) { - const commentLines = getCommentLines(commentGroup); - - // disallows consecutive line comments in favor of using a block comment. - if (commentGroup[0].type === "Line" && commentLines.length > 1 && - !commentLines.some(value => value.includes("*/"))) { - context.report({ - loc: { - start: commentGroup[0].loc.start, - end: commentGroup[commentGroup.length - 1].loc.end - }, - messageId: "expectedBlock", - fix(fixer) { - const range = [commentGroup[0].range[0], commentGroup[commentGroup.length - 1].range[1]]; - const block = convertToBlock(commentGroup[0], commentLines.filter(line => line)); - - return fixer.replaceTextRange(range, block); - } - }); - } - - // prohibits block comments from having a * at the beginning of each line. - if (commentGroup[0].type === "Block") { - const block = commentGroup[0]; - const lines = block.value.split(astUtils.LINEBREAK_MATCHER).filter(line => line.trim()); - - if (lines.length > 0 && lines.every(line => /^\s*\*/.test(line))) { - context.report({ - loc: { - start: block.loc.start, - end: { line: block.loc.start.line, column: block.loc.start.column + 2 } - }, - messageId: "expectedBlock", - fix(fixer) { - return fixer.replaceText(block, convertToBlock(block, commentLines.filter(line => line))); - } - }); - } - } - } - } - }; - - //---------------------------------------------------------------------- - // Public - //---------------------------------------------------------------------- - - return { - Program() { - return sourceCode.getAllComments() - .filter(comment => comment.type !== "Shebang") - .filter(comment => !astUtils.COMMENTS_IGNORE_PATTERN.test(comment.value)) - .filter(comment => { - const tokenBefore = sourceCode.getTokenBefore(comment, { includeComments: true }); - - return !tokenBefore || tokenBefore.loc.end.line < comment.loc.start.line; - }) - .reduce((commentGroups, comment, index, commentList) => { - const tokenBefore = sourceCode.getTokenBefore(comment, { includeComments: true }); - - if ( - comment.type === "Line" && - index && commentList[index - 1].type === "Line" && - tokenBefore && tokenBefore.loc.end.line === comment.loc.start.line - 1 && - tokenBefore === commentList[index - 1] - ) { - commentGroups[commentGroups.length - 1].push(comment); - } else { - commentGroups.push([comment]); - } - - return commentGroups; - }, []) - .filter(commentGroup => !(commentGroup.length === 1 && commentGroup[0].loc.start.line === commentGroup[0].loc.end.line)) - .forEach(commentGroupCheckers[option]); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/multiline-ternary.js b/tools/node_modules/eslint/lib/rules/multiline-ternary.js deleted file mode 100644 index 83378dcd86e3e5..00000000000000 --- a/tools/node_modules/eslint/lib/rules/multiline-ternary.js +++ /dev/null @@ -1,95 +0,0 @@ -/** - * @fileoverview Enforce newlines between operands of ternary expressions - * @author Kai Cataldo - */ - -"use strict"; - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce newlines between operands of ternary expressions", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/multiline-ternary" - }, - - schema: [ - { - enum: ["always", "always-multiline", "never"] - } - ], - messages: { - expectedTestCons: "Expected newline between test and consequent of ternary expression.", - expectedConsAlt: "Expected newline between consequent and alternate of ternary expression.", - unexpectedTestCons: "Unexpected newline between test and consequent of ternary expression.", - unexpectedConsAlt: "Unexpected newline between consequent and alternate of ternary expression." - } - }, - - create(context) { - const option = context.options[0]; - const multiline = option !== "never"; - const allowSingleLine = option === "always-multiline"; - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Tests whether node is preceded by supplied tokens - * @param {ASTNode} node - node to check - * @param {ASTNode} parentNode - parent of node to report - * @param {boolean} expected - whether newline was expected or not - * @returns {void} - * @private - */ - function reportError(node, parentNode, expected) { - context.report({ - node, - messageId: `${expected ? "expected" : "unexpected"}${node === parentNode.test ? "TestCons" : "ConsAlt"}` - }); - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - ConditionalExpression(node) { - const areTestAndConsequentOnSameLine = astUtils.isTokenOnSameLine(node.test, node.consequent); - const areConsequentAndAlternateOnSameLine = astUtils.isTokenOnSameLine(node.consequent, node.alternate); - - if (!multiline) { - if (!areTestAndConsequentOnSameLine) { - reportError(node.test, node, false); - } - - if (!areConsequentAndAlternateOnSameLine) { - reportError(node.consequent, node, false); - } - } else { - if (allowSingleLine && node.loc.start.line === node.loc.end.line) { - return; - } - - if (areTestAndConsequentOnSameLine) { - reportError(node.test, node, true); - } - - if (areConsequentAndAlternateOnSameLine) { - reportError(node.consequent, node, true); - } - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/new-cap.js b/tools/node_modules/eslint/lib/rules/new-cap.js deleted file mode 100644 index ab70fcfadd5e13..00000000000000 --- a/tools/node_modules/eslint/lib/rules/new-cap.js +++ /dev/null @@ -1,282 +0,0 @@ -/** - * @fileoverview Rule to flag use of constructors without capital letters - * @author Nicholas C. Zakas - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const CAPS_ALLOWED = [ - "Array", - "Boolean", - "Date", - "Error", - "Function", - "Number", - "Object", - "RegExp", - "String", - "Symbol" -]; - -/** - * Ensure that if the key is provided, it must be an array. - * @param {Object} obj Object to check with `key`. - * @param {string} key Object key to check on `obj`. - * @param {*} fallback If obj[key] is not present, this will be returned. - * @returns {string[]} Returns obj[key] if it's an Array, otherwise `fallback` - */ -function checkArray(obj, key, fallback) { - - /* istanbul ignore if */ - if (Object.prototype.hasOwnProperty.call(obj, key) && !Array.isArray(obj[key])) { - throw new TypeError(`${key}, if provided, must be an Array`); - } - return obj[key] || fallback; -} - -/** - * A reducer function to invert an array to an Object mapping the string form of the key, to `true`. - * @param {Object} map Accumulator object for the reduce. - * @param {string} key Object key to set to `true`. - * @returns {Object} Returns the updated Object for further reduction. - */ -function invert(map, key) { - map[key] = true; - return map; -} - -/** - * Creates an object with the cap is new exceptions as its keys and true as their values. - * @param {Object} config Rule configuration - * @returns {Object} Object with cap is new exceptions. - */ -function calculateCapIsNewExceptions(config) { - let capIsNewExceptions = checkArray(config, "capIsNewExceptions", CAPS_ALLOWED); - - if (capIsNewExceptions !== CAPS_ALLOWED) { - capIsNewExceptions = capIsNewExceptions.concat(CAPS_ALLOWED); - } - - return capIsNewExceptions.reduce(invert, {}); -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require constructor names to begin with a capital letter", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/new-cap" - }, - - schema: [ - { - type: "object", - properties: { - newIsCap: { - type: "boolean", - default: true - }, - capIsNew: { - type: "boolean", - default: true - }, - newIsCapExceptions: { - type: "array", - items: { - type: "string" - } - }, - newIsCapExceptionPattern: { - type: "string" - }, - capIsNewExceptions: { - type: "array", - items: { - type: "string" - } - }, - capIsNewExceptionPattern: { - type: "string" - }, - properties: { - type: "boolean", - default: true - } - }, - additionalProperties: false - } - ], - messages: { - upper: "A function with a name starting with an uppercase letter should only be used as a constructor.", - lower: "A constructor name should not start with a lowercase letter." - } - }, - - create(context) { - - const config = Object.assign({}, context.options[0]); - - config.newIsCap = config.newIsCap !== false; - config.capIsNew = config.capIsNew !== false; - const skipProperties = config.properties === false; - - const newIsCapExceptions = checkArray(config, "newIsCapExceptions", []).reduce(invert, {}); - const newIsCapExceptionPattern = config.newIsCapExceptionPattern ? new RegExp(config.newIsCapExceptionPattern) : null; - - const capIsNewExceptions = calculateCapIsNewExceptions(config); - const capIsNewExceptionPattern = config.capIsNewExceptionPattern ? new RegExp(config.capIsNewExceptionPattern) : null; - - const listeners = {}; - - const sourceCode = context.getSourceCode(); - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Get exact callee name from expression - * @param {ASTNode} node CallExpression or NewExpression node - * @returns {string} name - */ - function extractNameFromExpression(node) { - - let name = ""; - - if (node.callee.type === "MemberExpression") { - const property = node.callee.property; - - if (property.type === "Literal" && (typeof property.value === "string")) { - name = property.value; - } else if (property.type === "Identifier" && !node.callee.computed) { - name = property.name; - } - } else { - name = node.callee.name; - } - return name; - } - - /** - * Returns the capitalization state of the string - - * Whether the first character is uppercase, lowercase, or non-alphabetic - * @param {string} str String - * @returns {string} capitalization state: "non-alpha", "lower", or "upper" - */ - function getCap(str) { - const firstChar = str.charAt(0); - - const firstCharLower = firstChar.toLowerCase(); - const firstCharUpper = firstChar.toUpperCase(); - - if (firstCharLower === firstCharUpper) { - - // char has no uppercase variant, so it's non-alphabetic - return "non-alpha"; - } - if (firstChar === firstCharLower) { - return "lower"; - } - return "upper"; - - } - - /** - * Check if capitalization is allowed for a CallExpression - * @param {Object} allowedMap Object mapping calleeName to a Boolean - * @param {ASTNode} node CallExpression node - * @param {string} calleeName Capitalized callee name from a CallExpression - * @param {Object} pattern RegExp object from options pattern - * @returns {boolean} Returns true if the callee may be capitalized - */ - function isCapAllowed(allowedMap, node, calleeName, pattern) { - const sourceText = sourceCode.getText(node.callee); - - if (allowedMap[calleeName] || allowedMap[sourceText]) { - return true; - } - - if (pattern && pattern.test(sourceText)) { - return true; - } - - if (calleeName === "UTC" && node.callee.type === "MemberExpression") { - - // allow if callee is Date.UTC - return node.callee.object.type === "Identifier" && - node.callee.object.name === "Date"; - } - - return skipProperties && node.callee.type === "MemberExpression"; - } - - /** - * Reports the given messageId for the given node. The location will be the start of the property or the callee. - * @param {ASTNode} node CallExpression or NewExpression node. - * @param {string} messageId The messageId to report. - * @returns {void} - */ - function report(node, messageId) { - let callee = node.callee; - - if (callee.type === "MemberExpression") { - callee = callee.property; - } - - context.report({ node, loc: callee.loc.start, messageId }); - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - if (config.newIsCap) { - listeners.NewExpression = function(node) { - - const constructorName = extractNameFromExpression(node); - - if (constructorName) { - const capitalization = getCap(constructorName); - const isAllowed = capitalization !== "lower" || isCapAllowed(newIsCapExceptions, node, constructorName, newIsCapExceptionPattern); - - if (!isAllowed) { - report(node, "lower"); - } - } - }; - } - - if (config.capIsNew) { - listeners.CallExpression = function(node) { - - const calleeName = extractNameFromExpression(node); - - if (calleeName) { - const capitalization = getCap(calleeName); - const isAllowed = capitalization !== "upper" || isCapAllowed(capIsNewExceptions, node, calleeName, capIsNewExceptionPattern); - - if (!isAllowed) { - report(node, "upper"); - } - } - }; - } - - return listeners; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/new-parens.js b/tools/node_modules/eslint/lib/rules/new-parens.js deleted file mode 100644 index edd3c1e1c2ef47..00000000000000 --- a/tools/node_modules/eslint/lib/rules/new-parens.js +++ /dev/null @@ -1,63 +0,0 @@ -/** - * @fileoverview Rule to flag when using constructor without parentheses - * @author Ilya Volodin - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "require parentheses when invoking a constructor with no arguments", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/new-parens" - }, - - fixable: "code", - schema: [], - messages: { - missing: "Missing '()' invoking a constructor." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - return { - NewExpression(node) { - if (node.arguments.length !== 0) { - return; // shortcut: if there are arguments, there have to be parens - } - - const lastToken = sourceCode.getLastToken(node); - const hasLastParen = lastToken && astUtils.isClosingParenToken(lastToken); - const hasParens = hasLastParen && astUtils.isOpeningParenToken(sourceCode.getTokenBefore(lastToken)); - - if (!hasParens) { - context.report({ - node, - messageId: "missing", - fix: fixer => fixer.insertTextAfter(node, "()") - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/newline-after-var.js b/tools/node_modules/eslint/lib/rules/newline-after-var.js deleted file mode 100644 index 036cefc22cab25..00000000000000 --- a/tools/node_modules/eslint/lib/rules/newline-after-var.js +++ /dev/null @@ -1,256 +0,0 @@ -/** - * @fileoverview Rule to check empty newline after "var" statement - * @author Gopal Venkatesan - * @deprecated - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "require or disallow an empty line after variable declarations", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/newline-after-var" - }, - schema: [ - { - enum: ["never", "always"] - } - ], - fixable: "whitespace", - messages: { - expected: "Expected blank line after variable declarations.", - unexpected: "Unexpected blank line after variable declarations." - }, - - deprecated: true, - - replacedBy: ["padding-line-between-statements"] - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - // Default `mode` to "always". - const mode = context.options[0] === "never" ? "never" : "always"; - - // Cache starting and ending line numbers of comments for faster lookup - const commentEndLine = sourceCode.getAllComments().reduce((result, token) => { - result[token.loc.start.line] = token.loc.end.line; - return result; - }, {}); - - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Gets a token from the given node to compare line to the next statement. - * - * In general, the token is the last token of the node. However, the token is the second last token if the following conditions satisfy. - * - * - The last token is semicolon. - * - The semicolon is on a different line from the previous token of the semicolon. - * - * This behavior would address semicolon-less style code. e.g.: - * - * var foo = 1 - * - * ;(a || b).doSomething() - * - * @param {ASTNode} node - The node to get. - * @returns {Token} The token to compare line to the next statement. - */ - function getLastToken(node) { - const lastToken = sourceCode.getLastToken(node); - - if (lastToken.type === "Punctuator" && lastToken.value === ";") { - const prevToken = sourceCode.getTokenBefore(lastToken); - - if (prevToken.loc.end.line !== lastToken.loc.start.line) { - return prevToken; - } - } - - return lastToken; - } - - /** - * Determine if provided keyword is a variable declaration - * @private - * @param {string} keyword - keyword to test - * @returns {boolean} True if `keyword` is a type of var - */ - function isVar(keyword) { - return keyword === "var" || keyword === "let" || keyword === "const"; - } - - /** - * Determine if provided keyword is a variant of for specifiers - * @private - * @param {string} keyword - keyword to test - * @returns {boolean} True if `keyword` is a variant of for specifier - */ - function isForTypeSpecifier(keyword) { - return keyword === "ForStatement" || keyword === "ForInStatement" || keyword === "ForOfStatement"; - } - - /** - * Determine if provided keyword is an export specifiers - * @private - * @param {string} nodeType - nodeType to test - * @returns {boolean} True if `nodeType` is an export specifier - */ - function isExportSpecifier(nodeType) { - return nodeType === "ExportNamedDeclaration" || nodeType === "ExportSpecifier" || - nodeType === "ExportDefaultDeclaration" || nodeType === "ExportAllDeclaration"; - } - - /** - * Determine if provided node is the last of their parent block. - * @private - * @param {ASTNode} node - node to test - * @returns {boolean} True if `node` is last of their parent block. - */ - function isLastNode(node) { - const token = sourceCode.getTokenAfter(node); - - 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 - * @param {integer} commentStartLine The line number on which the comment starts - * @returns {boolean} True if `token` does not start immediately after a comment - */ - function hasBlankLineAfterComment(token, commentStartLine) { - return token.loc.start.line > getLastCommentLineOfBlock(commentStartLine) + 1; - } - - /** - * Checks that a blank line exists after a variable declaration when mode is - * set to "always", or checks that there is no blank line when mode is set - * to "never" - * @private - * @param {ASTNode} node - `VariableDeclaration` node to test - * @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), - - /* - * 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 - if (!nextToken) { - return; - } - - // Ignore if parent of node is a for variant - if (isForTypeSpecifier(node.parent.type)) { - return; - } - - // Ignore if parent of node is an export specifier - if (isExportSpecifier(node.parent.type)) { - return; - } - - /* - * Some coding styles use multiple `var` statements, so do nothing if - * the next token is a `var` statement. - */ - if (nextToken.type === "Keyword" && isVar(nextToken.value)) { - return; - } - - // Ignore if it is last statement in a block - if (isLastNode(node)) { - return; - } - - // Next statement is not a `var`... - const noNextLineToken = nextToken.loc.start.line > nextLineNum; - const hasNextLineComment = (typeof commentEndLine[nextLineNum] !== "undefined"); - - if (mode === "never" && noNextLineToken && !hasNextLineComment) { - context.report({ - node, - messageId: "unexpected", - data: { identifier: node.name }, - fix(fixer) { - const linesBetween = sourceCode.getText().slice(lastToken.range[1], nextToken.range[0]).split(astUtils.LINEBREAK_MATCHER); - - 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 - if ( - mode === "always" && ( - !noNextLineToken || - hasNextLineComment && !hasBlankLineAfterComment(nextToken, nextLineNum) - ) - ) { - context.report({ - node, - messageId: "expected", - 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"); - } - }); - } - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - VariableDeclaration: checkForBlankLine - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/newline-before-return.js b/tools/node_modules/eslint/lib/rules/newline-before-return.js deleted file mode 100644 index 816ddba72b2c5a..00000000000000 --- a/tools/node_modules/eslint/lib/rules/newline-before-return.js +++ /dev/null @@ -1,218 +0,0 @@ -/** - * @fileoverview Rule to require newlines before `return` statement - * @author Kai Cataldo - * @deprecated - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "require an empty line before `return` statements", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/newline-before-return" - }, - - fixable: "whitespace", - schema: [], - messages: { - expected: "Expected newline before return statement." - }, - - deprecated: true, - replacedBy: ["padding-line-between-statements"] - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Tests whether node is preceded by supplied tokens - * @param {ASTNode} node - node to check - * @param {Array} testTokens - array of tokens to test against - * @returns {boolean} Whether or not the node is preceded by one of the supplied tokens - * @private - */ - function isPrecededByTokens(node, testTokens) { - const tokenBefore = sourceCode.getTokenBefore(node); - - return testTokens.some(token => tokenBefore.value === token); - } - - /** - * Checks whether node is the first node after statement or in block - * @param {ASTNode} node - node to check - * @returns {boolean} Whether or not the node is the first node after statement or in block - * @private - */ - function isFirstNode(node) { - const parentType = node.parent.type; - - if (node.parent.body) { - return Array.isArray(node.parent.body) - ? node.parent.body[0] === node - : node.parent.body === node; - } - - if (parentType === "IfStatement") { - return isPrecededByTokens(node, ["else", ")"]); - } - if (parentType === "DoWhileStatement") { - return isPrecededByTokens(node, ["do"]); - } - if (parentType === "SwitchCase") { - return isPrecededByTokens(node, [":"]); - } - return isPrecededByTokens(node, [")"]); - - } - - /** - * Returns the number of lines of comments that precede the node - * @param {ASTNode} node - node to check for overlapping comments - * @param {number} lineNumTokenBefore - line number of previous token, to check for overlapping comments - * @returns {number} Number of lines of comments that precede the node - * @private - */ - function calcCommentLines(node, lineNumTokenBefore) { - const comments = sourceCode.getCommentsBefore(node); - let numLinesComments = 0; - - if (!comments.length) { - return numLinesComments; - } - - comments.forEach(comment => { - numLinesComments++; - - if (comment.type === "Block") { - numLinesComments += comment.loc.end.line - comment.loc.start.line; - } - - // avoid counting lines with inline comments twice - if (comment.loc.start.line === lineNumTokenBefore) { - numLinesComments--; - } - - if (comment.loc.end.line === node.loc.start.line) { - numLinesComments--; - } - }); - - return numLinesComments; - } - - /** - * Returns the line number of the token before the node that is passed in as an argument - * @param {ASTNode} node - The node to use as the start of the calculation - * @returns {number} Line number of the token before `node` - * @private - */ - function getLineNumberOfTokenBefore(node) { - const tokenBefore = sourceCode.getTokenBefore(node); - let lineNumTokenBefore; - - /** - * Global return (at the beginning of a script) is a special case. - * If there is no token before `return`, then we expect no line - * break before the return. Comments are allowed to occupy lines - * before the global return, just no blank lines. - * Setting lineNumTokenBefore to zero in that case results in the - * desired behavior. - */ - if (tokenBefore) { - lineNumTokenBefore = tokenBefore.loc.end.line; - } else { - lineNumTokenBefore = 0; // global return at beginning of script - } - - return lineNumTokenBefore; - } - - /** - * Checks whether node is preceded by a newline - * @param {ASTNode} node - node to check - * @returns {boolean} Whether or not the node is preceded by a newline - * @private - */ - function hasNewlineBefore(node) { - const lineNumNode = node.loc.start.line; - const lineNumTokenBefore = getLineNumberOfTokenBefore(node); - const commentLines = calcCommentLines(node, lineNumTokenBefore); - - return (lineNumNode - lineNumTokenBefore - commentLines) > 1; - } - - /** - * Checks whether it is safe to apply a fix to a given return statement. - * - * The fix is not considered safe if the given return statement has leading comments, - * as we cannot safely determine if the newline should be added before or after the comments. - * For more information, see: https://github.com/eslint/eslint/issues/5958#issuecomment-222767211 - * - * @param {ASTNode} node - The return statement node to check. - * @returns {boolean} `true` if it can fix the node. - * @private - */ - function canFix(node) { - const leadingComments = sourceCode.getCommentsBefore(node); - const lastLeadingComment = leadingComments[leadingComments.length - 1]; - const tokenBefore = sourceCode.getTokenBefore(node); - - if (leadingComments.length === 0) { - return true; - } - - /* - * if the last leading comment ends in the same line as the previous token and - * does not share a line with the `return` node, we can consider it safe to fix. - * Example: - * function a() { - * var b; //comment - * return; - * } - */ - if (lastLeadingComment.loc.end.line === tokenBefore.loc.end.line && - lastLeadingComment.loc.end.line !== node.loc.start.line) { - return true; - } - - return false; - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - ReturnStatement(node) { - if (!isFirstNode(node) && !hasNewlineBefore(node)) { - context.report({ - node, - messageId: "expected", - fix(fixer) { - if (canFix(node)) { - const tokenBefore = sourceCode.getTokenBefore(node); - const newlines = node.loc.start.line === tokenBefore.loc.end.line ? "\n\n" : "\n"; - - return fixer.insertTextBefore(node, newlines); - } - return null; - } - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/newline-per-chained-call.js b/tools/node_modules/eslint/lib/rules/newline-per-chained-call.js deleted file mode 100644 index 90b540c484d495..00000000000000 --- a/tools/node_modules/eslint/lib/rules/newline-per-chained-call.js +++ /dev/null @@ -1,112 +0,0 @@ -/** - * @fileoverview Rule to ensure newline per method call when chaining calls - * @author Rajendra Patil - * @author Burak Yigit Kaya - */ - -"use strict"; - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "require a newline after each call in a method chain", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/newline-per-chained-call" - }, - - fixable: "whitespace", - - schema: [{ - type: "object", - properties: { - ignoreChainWithDepth: { - type: "integer", - minimum: 1, - maximum: 10, - default: 2 - } - }, - additionalProperties: false - }], - messages: { - expected: "Expected line break before `{{callee}}`." - } - }, - - create(context) { - - const options = context.options[0] || {}, - ignoreChainWithDepth = options.ignoreChainWithDepth || 2; - - const sourceCode = context.getSourceCode(); - - /** - * Get the prefix of a given MemberExpression node. - * If the MemberExpression node is a computed value it returns a - * left bracket. If not it returns a period. - * - * @param {ASTNode} node - A MemberExpression node to get - * @returns {string} The prefix of the node. - */ - function getPrefix(node) { - return node.computed ? "[" : "."; - } - - /** - * Gets the property text of a given MemberExpression node. - * If the text is multiline, this returns only the first line. - * - * @param {ASTNode} node - A MemberExpression node to get. - * @returns {string} The property text of the node. - */ - function getPropertyText(node) { - const prefix = getPrefix(node); - const lines = sourceCode.getText(node.property).split(astUtils.LINEBREAK_MATCHER); - const suffix = node.computed && lines.length === 1 ? "]" : ""; - - return prefix + lines[0] + suffix; - } - - return { - "CallExpression:exit"(node) { - if (!node.callee || node.callee.type !== "MemberExpression") { - return; - } - - const callee = node.callee; - let parent = callee.object; - let depth = 1; - - while (parent && parent.callee) { - depth += 1; - parent = parent.callee.object; - } - - if (depth > ignoreChainWithDepth && astUtils.isTokenOnSameLine(callee.object, callee.property)) { - context.report({ - node: callee.property, - loc: callee.property.loc.start, - messageId: "expected", - data: { - callee: getPropertyText(callee) - }, - fix(fixer) { - const firstTokenAfterObject = sourceCode.getTokenAfter(callee.object, astUtils.isNotClosingParenToken); - - return fixer.insertTextBefore(firstTokenAfterObject, "\n"); - } - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-alert.js b/tools/node_modules/eslint/lib/rules/no-alert.js deleted file mode 100644 index 21f10b3c399397..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-alert.js +++ /dev/null @@ -1,127 +0,0 @@ -/** - * @fileoverview Rule to flag use of alert, confirm, prompt - * @author Nicholas C. Zakas - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const getPropertyName = require("../util/ast-utils").getStaticPropertyName; - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks if the given name is a prohibited identifier. - * @param {string} name The name to check - * @returns {boolean} Whether or not the name is prohibited. - */ -function isProhibitedIdentifier(name) { - return /^(alert|confirm|prompt)$/.test(name); -} - -/** - * Finds the eslint-scope reference in the given scope. - * @param {Object} scope The scope to search. - * @param {ASTNode} node The identifier node. - * @returns {Reference|null} Returns the found reference or null if none were found. - */ -function findReference(scope, node) { - 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]; - } - return null; -} - -/** - * Checks if the given identifier node is shadowed in the given scope. - * @param {Object} scope The current scope. - * @param {string} node The identifier node to check - * @returns {boolean} Whether or not the name is shadowed. - */ -function isShadowed(scope, node) { - const reference = findReference(scope, node); - - return reference && reference.resolved && reference.resolved.defs.length > 0; -} - -/** - * Checks if the given identifier node is a ThisExpression in the global scope or the global window property. - * @param {Object} scope The current scope. - * @param {string} node The identifier node to check - * @returns {boolean} Whether or not the node is a reference to the global object. - */ -function isGlobalThisReferenceOrGlobalWindow(scope, node) { - if (scope.type === "global" && node.type === "ThisExpression") { - return true; - } - if (node.name === "window") { - return !isShadowed(scope, node); - } - - return false; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow the use of `alert`, `confirm`, and `prompt`", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-alert" - }, - - schema: [], - - messages: { - unexpected: "Unexpected {{name}}." - } - }, - - create(context) { - return { - CallExpression(node) { - const callee = node.callee, - currentScope = context.getScope(); - - // without window. - if (callee.type === "Identifier") { - const name = callee.name; - - if (!isShadowed(currentScope, callee) && isProhibitedIdentifier(callee.name)) { - context.report({ - node, - messageId: "unexpected", - data: { name } - }); - } - - } else if (callee.type === "MemberExpression" && isGlobalThisReferenceOrGlobalWindow(currentScope, callee.object)) { - const name = getPropertyName(callee); - - if (isProhibitedIdentifier(name)) { - context.report({ - node, - messageId: "unexpected", - data: { name } - }); - } - } - - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-array-constructor.js b/tools/node_modules/eslint/lib/rules/no-array-constructor.js deleted file mode 100644 index 90c6d6bbd59281..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-array-constructor.js +++ /dev/null @@ -1,54 +0,0 @@ -/** - * @fileoverview Disallow construction of dense arrays using the Array constructor - * @author Matt DuVall - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow `Array` constructors", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/no-array-constructor" - }, - - schema: [], - - messages: { - preferLiteral: "The array literal notation [] is preferable." - } - }, - - create(context) { - - /** - * Disallow construction of dense arrays using the Array constructor - * @param {ASTNode} node node to evaluate - * @returns {void} - * @private - */ - function check(node) { - if ( - node.arguments.length !== 1 && - node.callee.type === "Identifier" && - node.callee.name === "Array" - ) { - context.report({ node, messageId: "preferLiteral" }); - } - } - - return { - CallExpression: check, - NewExpression: check - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-async-promise-executor.js b/tools/node_modules/eslint/lib/rules/no-async-promise-executor.js deleted file mode 100644 index af15509ed4d394..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-async-promise-executor.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * @fileoverview disallow using an async function as a Promise executor - * @author Teddy Katz - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow using an async function as a Promise executor", - category: "Possible Errors", - recommended: false, - url: "https://eslint.org/docs/rules/no-async-promise-executor" - }, - - fixable: null, - schema: [], - messages: { - async: "Promise executor functions should not be async." - } - }, - - create(context) { - return { - "NewExpression[callee.name='Promise'][arguments.0.async=true]"(node) { - context.report({ - node: context.getSourceCode().getFirstToken(node.arguments[0], token => token.value === "async"), - messageId: "async" - }); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-await-in-loop.js b/tools/node_modules/eslint/lib/rules/no-await-in-loop.js deleted file mode 100644 index 9ca89866a6e114..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-await-in-loop.js +++ /dev/null @@ -1,106 +0,0 @@ -/** - * @fileoverview Rule to disallow uses of await inside of loops. - * @author Nat Mote (nmote) - */ -"use strict"; - -/** - * Check whether it should stop traversing ancestors at the given node. - * @param {ASTNode} node A node to check. - * @returns {boolean} `true` if it should stop traversing. - */ -function isBoundary(node) { - const t = node.type; - - return ( - t === "FunctionDeclaration" || - t === "FunctionExpression" || - t === "ArrowFunctionExpression" || - - /* - * Don't report the await expressions on for-await-of loop since it's - * asynchronous iteration intentionally. - */ - (t === "ForOfStatement" && node.await === true) - ); -} - -/** - * Check whether the given node is in loop. - * @param {ASTNode} node A node to check. - * @param {ASTNode} parent A parent node to check. - * @returns {boolean} `true` if the node is in loop. - */ -function isLooped(node, parent) { - switch (parent.type) { - case "ForStatement": - return ( - node === parent.test || - node === parent.update || - node === parent.body - ); - - case "ForOfStatement": - case "ForInStatement": - return node === parent.body; - - case "WhileStatement": - case "DoWhileStatement": - return node === parent.test || node === parent.body; - - default: - return false; - } -} - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow `await` inside of loops", - category: "Possible Errors", - recommended: false, - url: "https://eslint.org/docs/rules/no-await-in-loop" - }, - - schema: [], - - messages: { - unexpectedAwait: "Unexpected `await` inside a loop." - } - }, - create(context) { - - /** - * Validate an await expression. - * @param {ASTNode} awaitNode An AwaitExpression or ForOfStatement node to validate. - * @returns {void} - */ - function validate(awaitNode) { - if (awaitNode.type === "ForOfStatement" && !awaitNode.await) { - return; - } - - let node = awaitNode; - let parent = node.parent; - - while (parent && !isBoundary(parent)) { - if (isLooped(node, parent)) { - context.report({ - node: awaitNode, - messageId: "unexpectedAwait" - }); - return; - } - node = parent; - parent = parent.parent; - } - } - - return { - AwaitExpression: validate, - ForOfStatement: validate - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-bitwise.js b/tools/node_modules/eslint/lib/rules/no-bitwise.js deleted file mode 100644 index a9c3360a7c5b42..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-bitwise.js +++ /dev/null @@ -1,119 +0,0 @@ -/** - * @fileoverview Rule to flag bitwise identifiers - * @author Nicholas C. Zakas - */ - -"use strict"; - -/* - * - * Set of bitwise operators. - * - */ -const BITWISE_OPERATORS = [ - "^", "|", "&", "<<", ">>", ">>>", - "^=", "|=", "&=", "<<=", ">>=", ">>>=", - "~" -]; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow bitwise operators", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/no-bitwise" - }, - - schema: [ - { - type: "object", - properties: { - allow: { - type: "array", - items: { - enum: BITWISE_OPERATORS - }, - uniqueItems: true - }, - int32Hint: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - - messages: { - unexpected: "Unexpected use of '{{operator}}'." - } - }, - - create(context) { - const options = context.options[0] || {}; - const allowed = options.allow || []; - const int32Hint = options.int32Hint === true; - - /** - * Reports an unexpected use of a bitwise operator. - * @param {ASTNode} node Node which contains the bitwise operator. - * @returns {void} - */ - function report(node) { - context.report({ node, messageId: "unexpected", data: { operator: node.operator } }); - } - - /** - * Checks if the given node has a bitwise operator. - * @param {ASTNode} node The node to check. - * @returns {boolean} Whether or not the node has a bitwise operator. - */ - function hasBitwiseOperator(node) { - return BITWISE_OPERATORS.indexOf(node.operator) !== -1; - } - - /** - * Checks if exceptions were provided, e.g. `{ allow: ['~', '|'] }`. - * @param {ASTNode} node The node to check. - * @returns {boolean} Whether or not the node has a bitwise operator. - */ - function allowedOperator(node) { - return allowed.indexOf(node.operator) !== -1; - } - - /** - * Checks if the given bitwise operator is used for integer typecasting, i.e. "|0" - * @param {ASTNode} node The node to check. - * @returns {boolean} whether the node is used in integer typecasting. - */ - function isInt32Hint(node) { - return int32Hint && node.operator === "|" && node.right && - node.right.type === "Literal" && node.right.value === 0; - } - - /** - * Report if the given node contains a bitwise operator. - * @param {ASTNode} node The node to check. - * @returns {void} - */ - function checkNodeForBitwiseOperator(node) { - if (hasBitwiseOperator(node) && !allowedOperator(node) && !isInt32Hint(node)) { - report(node); - } - } - - return { - AssignmentExpression: checkNodeForBitwiseOperator, - BinaryExpression: checkNodeForBitwiseOperator, - UnaryExpression: checkNodeForBitwiseOperator - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-buffer-constructor.js b/tools/node_modules/eslint/lib/rules/no-buffer-constructor.js deleted file mode 100644 index bf4c8891ad1adf..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-buffer-constructor.js +++ /dev/null @@ -1,45 +0,0 @@ -/** - * @fileoverview disallow use of the Buffer() constructor - * @author Teddy Katz - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow use of the `Buffer()` constructor", - category: "Node.js and CommonJS", - recommended: false, - url: "https://eslint.org/docs/rules/no-buffer-constructor" - }, - - schema: [], - - messages: { - deprecated: "{{expr}} is deprecated. Use Buffer.from(), Buffer.alloc(), or Buffer.allocUnsafe() instead." - } - }, - - create(context) { - - //---------------------------------------------------------------------- - // Public - //---------------------------------------------------------------------- - - return { - "CallExpression[callee.name='Buffer'], NewExpression[callee.name='Buffer']"(node) { - context.report({ - node, - messageId: "deprecated", - data: { expr: node.type === "CallExpression" ? "Buffer()" : "new Buffer()" } - }); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-caller.js b/tools/node_modules/eslint/lib/rules/no-caller.js deleted file mode 100644 index 1703ad867dc0a6..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-caller.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * @fileoverview Rule to flag use of arguments.callee and arguments.caller. - * @author Nicholas C. Zakas - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow the use of `arguments.caller` or `arguments.callee`", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-caller" - }, - - schema: [], - - messages: { - unexpected: "Avoid arguments.{{prop}}." - } - }, - - create(context) { - - return { - - MemberExpression(node) { - const objectName = node.object.name, - propertyName = node.property.name; - - if (objectName === "arguments" && !node.computed && propertyName && propertyName.match(/^calle[er]$/)) { - context.report({ node, messageId: "unexpected", data: { prop: propertyName } }); - } - - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-case-declarations.js b/tools/node_modules/eslint/lib/rules/no-case-declarations.js deleted file mode 100644 index 1d54e221625e70..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-case-declarations.js +++ /dev/null @@ -1,64 +0,0 @@ -/** - * @fileoverview Rule to flag use of an lexical declarations inside a case clause - * @author Erik Arvidsson - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow lexical declarations in case clauses", - category: "Best Practices", - recommended: true, - url: "https://eslint.org/docs/rules/no-case-declarations" - }, - - schema: [], - - messages: { - unexpected: "Unexpected lexical declaration in case block." - } - }, - - create(context) { - - /** - * Checks whether or not a node is a lexical declaration. - * @param {ASTNode} node A direct child statement of a switch case. - * @returns {boolean} Whether or not the node is a lexical declaration. - */ - function isLexicalDeclaration(node) { - switch (node.type) { - case "FunctionDeclaration": - case "ClassDeclaration": - return true; - case "VariableDeclaration": - return node.kind !== "var"; - default: - return false; - } - } - - return { - SwitchCase(node) { - for (let i = 0; i < node.consequent.length; i++) { - const statement = node.consequent[i]; - - if (isLexicalDeclaration(statement)) { - context.report({ - node: statement, - messageId: "unexpected" - }); - } - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-catch-shadow.js b/tools/node_modules/eslint/lib/rules/no-catch-shadow.js deleted file mode 100644 index 60a0493b3431a8..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-catch-shadow.js +++ /dev/null @@ -1,80 +0,0 @@ -/** - * @fileoverview Rule to flag variable leak in CatchClauses in IE 8 and earlier - * @author Ian Christian Myers - * @deprecated in ESLint v5.1.0 - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow `catch` clause parameters from shadowing variables in the outer scope", - category: "Variables", - recommended: false, - url: "https://eslint.org/docs/rules/no-catch-shadow" - }, - - replacedBy: ["no-shadow"], - - deprecated: true, - schema: [], - - messages: { - mutable: "Value of '{{name}}' may be overwritten in IE 8 and earlier." - } - }, - - create(context) { - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Check if the parameters are been shadowed - * @param {Object} scope current scope - * @param {string} name parameter name - * @returns {boolean} True is its been shadowed - */ - function paramIsShadowing(scope, name) { - return astUtils.getVariableByName(scope, name) !== null; - } - - //-------------------------------------------------------------------------- - // Public API - //-------------------------------------------------------------------------- - - return { - - "CatchClause[param!=null]"(node) { - let scope = context.getScope(); - - /* - * When ecmaVersion >= 6, CatchClause creates its own scope - * so start from one upper scope to exclude the current node - */ - if (scope.block === node) { - scope = scope.upper; - } - - if (paramIsShadowing(scope, node.param.name)) { - context.report({ node, messageId: "mutable", data: { name: node.param.name } }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-class-assign.js b/tools/node_modules/eslint/lib/rules/no-class-assign.js deleted file mode 100644 index 7bc65df1ba6004..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-class-assign.js +++ /dev/null @@ -1,61 +0,0 @@ -/** - * @fileoverview A rule to disallow modifying variables of class declarations - * @author Toru Nagashima - */ - -"use strict"; - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow reassigning class members", - category: "ECMAScript 6", - recommended: true, - url: "https://eslint.org/docs/rules/no-class-assign" - }, - - schema: [], - - messages: { - class: "'{{name}}' is a class." - } - }, - - create(context) { - - /** - * Finds and reports references that are non initializer and writable. - * @param {Variable} variable - A variable to check. - * @returns {void} - */ - function checkVariable(variable) { - astUtils.getModifyingReferences(variable.references).forEach(reference => { - context.report({ node: reference.identifier, messageId: "class", data: { name: reference.identifier.name } }); - - }); - } - - /** - * Finds and reports references that are non initializer and writable. - * @param {ASTNode} node - A ClassDeclaration/ClassExpression node to check. - * @returns {void} - */ - function checkForClass(node) { - context.getDeclaredVariables(node).forEach(checkVariable); - } - - return { - ClassDeclaration: checkForClass, - ClassExpression: checkForClass - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-compare-neg-zero.js b/tools/node_modules/eslint/lib/rules/no-compare-neg-zero.js deleted file mode 100644 index f5c8d5f417b20a..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-compare-neg-zero.js +++ /dev/null @@ -1,61 +0,0 @@ -/** - * @fileoverview The rule should warn against code that tries to compare against -0. - * @author Aladdin-ADD - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow comparing against -0", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-compare-neg-zero" - }, - - fixable: null, - schema: [], - - messages: { - unexpected: "Do not use the '{{operator}}' operator to compare against -0." - } - }, - - create(context) { - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Checks a given node is -0 - * - * @param {ASTNode} node - A node to check. - * @returns {boolean} `true` if the node is -0. - */ - function isNegZero(node) { - return node.type === "UnaryExpression" && node.operator === "-" && node.argument.type === "Literal" && node.argument.value === 0; - } - const OPERATORS_TO_CHECK = new Set([">", ">=", "<", "<=", "==", "===", "!=", "!=="]); - - return { - BinaryExpression(node) { - if (OPERATORS_TO_CHECK.has(node.operator)) { - if (isNegZero(node.left) || isNegZero(node.right)) { - context.report({ - node, - messageId: "unexpected", - data: { operator: node.operator } - }); - } - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-cond-assign.js b/tools/node_modules/eslint/lib/rules/no-cond-assign.js deleted file mode 100644 index aed3e4a7a9b642..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-cond-assign.js +++ /dev/null @@ -1,149 +0,0 @@ -/** - * @fileoverview Rule to flag assignment in a conditional statement's test expression - * @author Stephen Murray - */ -"use strict"; - -const astUtils = require("../util/ast-utils"); - -const NODE_DESCRIPTIONS = { - DoWhileStatement: "a 'do...while' statement", - ForStatement: "a 'for' statement", - IfStatement: "an 'if' statement", - WhileStatement: "a 'while' statement" -}; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow assignment operators in conditional expressions", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-cond-assign" - }, - - schema: [ - { - enum: ["except-parens", "always"] - } - ], - - messages: { - unexpected: "Unexpected assignment within {{type}}.", - - // must match JSHint's error message - missing: "Expected a conditional expression and instead saw an assignment." - } - }, - - create(context) { - - const prohibitAssign = (context.options[0] || "except-parens"); - - const sourceCode = context.getSourceCode(); - - /** - * Check whether an AST node is the test expression for a conditional statement. - * @param {!Object} node The node to test. - * @returns {boolean} `true` if the node is the text expression for a conditional statement; otherwise, `false`. - */ - function isConditionalTestExpression(node) { - return node.parent && - node.parent.test && - node === node.parent.test; - } - - /** - * Given an AST node, perform a bottom-up search for the first ancestor that represents a conditional statement. - * @param {!Object} node The node to use at the start of the search. - * @returns {?Object} The closest ancestor node that represents a conditional statement. - */ - function findConditionalAncestor(node) { - let currentAncestor = node; - - do { - if (isConditionalTestExpression(currentAncestor)) { - return currentAncestor.parent; - } - } while ((currentAncestor = currentAncestor.parent) && !astUtils.isFunction(currentAncestor)); - - return null; - } - - /** - * Check whether the code represented by an AST node is enclosed in two sets of parentheses. - * @param {!Object} node The node to test. - * @returns {boolean} `true` if the code is enclosed in two sets of parentheses; otherwise, `false`. - */ - function isParenthesisedTwice(node) { - const previousToken = sourceCode.getTokenBefore(node, 1), - nextToken = sourceCode.getTokenAfter(node, 1); - - return astUtils.isParenthesised(sourceCode, node) && - astUtils.isOpeningParenToken(previousToken) && previousToken.range[1] <= node.range[0] && - astUtils.isClosingParenToken(nextToken) && nextToken.range[0] >= node.range[1]; - } - - /** - * Check a conditional statement's test expression for top-level assignments that are not enclosed in parentheses. - * @param {!Object} node The node for the conditional statement. - * @returns {void} - */ - function testForAssign(node) { - if (node.test && - (node.test.type === "AssignmentExpression") && - (node.type === "ForStatement" - ? !astUtils.isParenthesised(sourceCode, node.test) - : !isParenthesisedTwice(node.test) - ) - ) { - - context.report({ - node, - loc: node.test.loc.start, - messageId: "missing" - }); - } - } - - /** - * Check whether an assignment expression is descended from a conditional statement's test expression. - * @param {!Object} node The node for the assignment expression. - * @returns {void} - */ - function testForConditionalAncestor(node) { - const ancestor = findConditionalAncestor(node); - - if (ancestor) { - context.report({ - node: ancestor, - messageId: "unexpected", - data: { - type: NODE_DESCRIPTIONS[ancestor.type] || ancestor.type - } - }); - } - } - - if (prohibitAssign === "always") { - return { - AssignmentExpression: testForConditionalAncestor - }; - } - - return { - DoWhileStatement: testForAssign, - ForStatement: testForAssign, - IfStatement: testForAssign, - WhileStatement: testForAssign, - ConditionalExpression: testForAssign - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-confusing-arrow.js b/tools/node_modules/eslint/lib/rules/no-confusing-arrow.js deleted file mode 100644 index 79df9a5138759a..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-confusing-arrow.js +++ /dev/null @@ -1,83 +0,0 @@ -/** - * @fileoverview A rule to warn against using arrow functions when they could be - * confused with comparisions - * @author Jxck - */ - -"use strict"; - -const astUtils = require("../util/ast-utils.js"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks whether or not a node is a conditional expression. - * @param {ASTNode} node - node to test - * @returns {boolean} `true` if the node is a conditional expression. - */ -function isConditional(node) { - return node && node.type === "ConditionalExpression"; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow arrow functions where they could be confused with comparisons", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/no-confusing-arrow" - }, - - fixable: "code", - - schema: [{ - type: "object", - properties: { - allowParens: { type: "boolean", default: false } - }, - additionalProperties: false - }], - - messages: { - confusing: "Arrow function used ambiguously with a conditional expression." - } - }, - - create(context) { - const config = context.options[0] || {}; - const sourceCode = context.getSourceCode(); - - /** - * Reports if an arrow function contains an ambiguous conditional. - * @param {ASTNode} node - A node to check and report. - * @returns {void} - */ - function checkArrowFunc(node) { - const body = node.body; - - if (isConditional(body) && !(config.allowParens && astUtils.isParenthesised(sourceCode, body))) { - context.report({ - node, - messageId: "confusing", - fix(fixer) { - - // if `allowParens` is not set to true dont bother wrapping in parens - return config.allowParens && fixer.replaceText(node.body, `(${sourceCode.getText(node.body)})`); - } - }); - } - } - - return { - ArrowFunctionExpression: checkArrowFunc - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-console.js b/tools/node_modules/eslint/lib/rules/no-console.js deleted file mode 100644 index d3a2e34475168f..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-console.js +++ /dev/null @@ -1,138 +0,0 @@ -/** - * @fileoverview Rule to flag use of console object - * @author Nicholas C. Zakas - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow the use of `console`", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-console" - }, - - schema: [ - { - type: "object", - properties: { - allow: { - type: "array", - items: { - type: "string" - }, - minItems: 1, - uniqueItems: true - } - }, - additionalProperties: false - } - ], - - messages: { - unexpected: "Unexpected console statement." - } - }, - - create(context) { - const options = context.options[0] || {}; - const allowed = options.allow || []; - - /** - * Checks whether the given reference is 'console' or not. - * - * @param {eslint-scope.Reference} reference - The reference to check. - * @returns {boolean} `true` if the reference is 'console'. - */ - function isConsole(reference) { - const id = reference.identifier; - - return id && id.name === "console"; - } - - /** - * Checks whether the property name of the given MemberExpression node - * is allowed by options or not. - * - * @param {ASTNode} node - The MemberExpression node to check. - * @returns {boolean} `true` if the property name of the node is allowed. - */ - function isAllowed(node) { - const propertyName = astUtils.getStaticPropertyName(node); - - return propertyName && allowed.indexOf(propertyName) !== -1; - } - - /** - * Checks whether the given reference is a member access which is not - * allowed by options or not. - * - * @param {eslint-scope.Reference} reference - The reference to check. - * @returns {boolean} `true` if the reference is a member access which - * is not allowed by options. - */ - function isMemberAccessExceptAllowed(reference) { - const node = reference.identifier; - const parent = node.parent; - - return ( - parent.type === "MemberExpression" && - parent.object === node && - !isAllowed(parent) - ); - } - - /** - * Reports the given reference as a violation. - * - * @param {eslint-scope.Reference} reference - The reference to report. - * @returns {void} - */ - function report(reference) { - const node = reference.identifier.parent; - - context.report({ - node, - loc: node.loc, - messageId: "unexpected" - }); - } - - return { - "Program:exit"() { - const scope = context.getScope(); - const consoleVar = astUtils.getVariableByName(scope, "console"); - const shadowed = consoleVar && consoleVar.defs.length > 0; - - /* - * 'scope.through' includes all references to undefined - * variables. If the variable 'console' is not defined, it uses - * 'scope.through'. - */ - const references = consoleVar - ? consoleVar.references - : scope.through.filter(isConsole); - - if (!shadowed) { - references - .filter(isMemberAccessExceptAllowed) - .forEach(report); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-const-assign.js b/tools/node_modules/eslint/lib/rules/no-const-assign.js deleted file mode 100644 index 32f8154cc23eae..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-const-assign.js +++ /dev/null @@ -1,54 +0,0 @@ -/** - * @fileoverview A rule to disallow modifying variables that are declared using `const` - * @author Toru Nagashima - */ - -"use strict"; - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow reassigning `const` variables", - category: "ECMAScript 6", - recommended: true, - url: "https://eslint.org/docs/rules/no-const-assign" - }, - - schema: [], - - messages: { - const: "'{{name}}' is constant." - } - }, - - create(context) { - - /** - * Finds and reports references that are non initializer and writable. - * @param {Variable} variable - A variable to check. - * @returns {void} - */ - function checkVariable(variable) { - astUtils.getModifyingReferences(variable.references).forEach(reference => { - context.report({ node: reference.identifier, messageId: "const", data: { name: reference.identifier.name } }); - }); - } - - return { - VariableDeclaration(node) { - if (node.kind === "const") { - context.getDeclaredVariables(node).forEach(checkVariable); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-constant-condition.js b/tools/node_modules/eslint/lib/rules/no-constant-condition.js deleted file mode 100644 index d6d04174298cff..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-constant-condition.js +++ /dev/null @@ -1,239 +0,0 @@ -/** - * @fileoverview Rule to flag use constant conditions - * @author Christian Schulz - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const EQUALITY_OPERATORS = ["===", "!==", "==", "!="]; -const RELATIONAL_OPERATORS = [">", "<", ">=", "<=", "in", "instanceof"]; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow constant expressions in conditions", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-constant-condition" - }, - - schema: [ - { - type: "object", - properties: { - checkLoops: { - type: "boolean", - default: true - } - }, - additionalProperties: false - } - ], - - messages: { - unexpected: "Unexpected constant condition." - } - }, - - create(context) { - const options = context.options[0] || {}, - checkLoops = options.checkLoops !== false, - loopSetStack = []; - - let loopsInCurrentScope = new Set(); - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - - /** - * Checks if a branch node of LogicalExpression short circuits the whole condition - * @param {ASTNode} node The branch of main condition which needs to be checked - * @param {string} operator The operator of the main LogicalExpression. - * @returns {boolean} true when condition short circuits whole condition - */ - function isLogicalIdentity(node, operator) { - switch (node.type) { - case "Literal": - return (operator === "||" && node.value === true) || - (operator === "&&" && node.value === false); - - case "UnaryExpression": - return (operator === "&&" && node.operator === "void"); - - case "LogicalExpression": - return isLogicalIdentity(node.left, node.operator) || - isLogicalIdentity(node.right, node.operator); - - // no default - } - return false; - } - - /** - * Checks if a node has a constant truthiness value. - * @param {ASTNode} node The AST node to check. - * @param {boolean} inBooleanPosition `false` if checking branch of a condition. - * `true` in all other cases - * @returns {Bool} true when node's truthiness is constant - * @private - */ - function isConstant(node, inBooleanPosition) { - switch (node.type) { - case "Literal": - case "ArrowFunctionExpression": - case "FunctionExpression": - case "ObjectExpression": - case "ArrayExpression": - return true; - - case "UnaryExpression": - if (node.operator === "void") { - return true; - } - - return (node.operator === "typeof" && inBooleanPosition) || - isConstant(node.argument, true); - - case "BinaryExpression": - return isConstant(node.left, false) && - isConstant(node.right, false) && - node.operator !== "in"; - - case "LogicalExpression": { - const isLeftConstant = isConstant(node.left, inBooleanPosition); - const isRightConstant = isConstant(node.right, inBooleanPosition); - const isLeftShortCircuit = (isLeftConstant && isLogicalIdentity(node.left, node.operator)); - const isRightShortCircuit = (isRightConstant && isLogicalIdentity(node.right, node.operator)); - - return (isLeftConstant && isRightConstant) || - ( - - // in the case of an "OR", we need to know if the right constant value is truthy - node.operator === "||" && - isRightConstant && - node.right.value && - ( - !node.parent || - node.parent.type !== "BinaryExpression" || - !(EQUALITY_OPERATORS.includes(node.parent.operator) || RELATIONAL_OPERATORS.includes(node.parent.operator)) - ) - ) || - isLeftShortCircuit || - isRightShortCircuit; - } - - case "AssignmentExpression": - return (node.operator === "=") && isConstant(node.right, inBooleanPosition); - - case "SequenceExpression": - return isConstant(node.expressions[node.expressions.length - 1], inBooleanPosition); - - // no default - } - return false; - } - - /** - * Tracks when the given node contains a constant condition. - * @param {ASTNode} node The AST node to check. - * @returns {void} - * @private - */ - function trackConstantConditionLoop(node) { - if (node.test && isConstant(node.test, true)) { - loopsInCurrentScope.add(node); - } - } - - /** - * Reports when the set contains the given constant condition node - * @param {ASTNode} node The AST node to check. - * @returns {void} - * @private - */ - function checkConstantConditionLoopInSet(node) { - if (loopsInCurrentScope.has(node)) { - loopsInCurrentScope.delete(node); - context.report({ node: node.test, messageId: "unexpected" }); - } - } - - /** - * Reports when the given node contains a constant condition. - * @param {ASTNode} node The AST node to check. - * @returns {void} - * @private - */ - function reportIfConstant(node) { - if (node.test && isConstant(node.test, true)) { - context.report({ node: node.test, messageId: "unexpected" }); - } - } - - /** - * Stores current set of constant loops in loopSetStack temporarily - * and uses a new set to track constant loops - * @returns {void} - * @private - */ - function enterFunction() { - loopSetStack.push(loopsInCurrentScope); - loopsInCurrentScope = new Set(); - } - - /** - * Reports when the set still contains stored constant conditions - * @returns {void} - * @private - */ - function exitFunction() { - loopsInCurrentScope = loopSetStack.pop(); - } - - /** - * Checks node when checkLoops option is enabled - * @param {ASTNode} node The AST node to check. - * @returns {void} - * @private - */ - function checkLoop(node) { - if (checkLoops) { - trackConstantConditionLoop(node); - } - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - ConditionalExpression: reportIfConstant, - IfStatement: reportIfConstant, - WhileStatement: checkLoop, - "WhileStatement:exit": checkConstantConditionLoopInSet, - DoWhileStatement: checkLoop, - "DoWhileStatement:exit": checkConstantConditionLoopInSet, - ForStatement: checkLoop, - "ForStatement > .test": node => checkLoop(node.parent), - "ForStatement:exit": checkConstantConditionLoopInSet, - FunctionDeclaration: enterFunction, - "FunctionDeclaration:exit": exitFunction, - FunctionExpression: enterFunction, - "FunctionExpression:exit": exitFunction, - YieldExpression: () => loopsInCurrentScope.clear() - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-continue.js b/tools/node_modules/eslint/lib/rules/no-continue.js deleted file mode 100644 index 96718d17a3db4b..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-continue.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * @fileoverview Rule to flag use of continue statement - * @author Borislav Zhivkov - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow `continue` statements", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/no-continue" - }, - - schema: [], - - messages: { - unexpected: "Unexpected use of continue statement." - } - }, - - create(context) { - - return { - ContinueStatement(node) { - context.report({ node, messageId: "unexpected" }); - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-control-regex.js b/tools/node_modules/eslint/lib/rules/no-control-regex.js deleted file mode 100644 index 24e6b197be0b44..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-control-regex.js +++ /dev/null @@ -1,113 +0,0 @@ -/** - * @fileoverview Rule to forbid control charactes from regular expressions. - * @author Nicholas C. Zakas - */ - -"use strict"; - -const RegExpValidator = require("regexpp").RegExpValidator; -const collector = new (class { - constructor() { - this.ecmaVersion = 2018; - this._source = ""; - this._controlChars = []; - this._validator = new RegExpValidator(this); - } - - onPatternEnter() { - this._controlChars = []; - } - - onCharacter(start, end, cp) { - if (cp >= 0x00 && - cp <= 0x1F && - ( - this._source.codePointAt(start) === cp || - this._source.slice(start, end).startsWith("\\x") || - this._source.slice(start, end).startsWith("\\u") - ) - ) { - this._controlChars.push(`\\x${`0${cp.toString(16)}`.slice(-2)}`); - } - } - - collectControlChars(regexpStr) { - try { - this._source = regexpStr; - this._validator.validatePattern(regexpStr); // Call onCharacter hook - } catch (err) { - - // Ignore syntax errors in RegExp. - } - return this._controlChars; - } -})(); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow control characters in regular expressions", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-control-regex" - }, - - schema: [], - - messages: { - unexpected: "Unexpected control character(s) in regular expression: {{controlChars}}." - } - }, - - create(context) { - - /** - * Get the regex expression - * @param {ASTNode} node node to evaluate - * @returns {RegExp|null} Regex if found else null - * @private - */ - function getRegExpPattern(node) { - if (node.regex) { - return node.regex.pattern; - } - if (typeof node.value === "string" && - (node.parent.type === "NewExpression" || node.parent.type === "CallExpression") && - node.parent.callee.type === "Identifier" && - node.parent.callee.name === "RegExp" && - node.parent.arguments[0] === node - ) { - return node.value; - } - - return null; - } - - return { - Literal(node) { - const pattern = getRegExpPattern(node); - - if (pattern) { - const controlCharacters = collector.collectControlChars(pattern); - - if (controlCharacters.length > 0) { - context.report({ - node, - messageId: "unexpected", - data: { - controlChars: controlCharacters.join(", ") - } - }); - } - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-debugger.js b/tools/node_modules/eslint/lib/rules/no-debugger.js deleted file mode 100644 index 95a28a862151be..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-debugger.js +++ /dev/null @@ -1,43 +0,0 @@ -/** - * @fileoverview Rule to flag use of a debugger statement - * @author Nicholas C. Zakas - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow the use of `debugger`", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-debugger" - }, - - fixable: null, - schema: [], - - messages: { - unexpected: "Unexpected 'debugger' statement." - } - }, - - create(context) { - - return { - DebuggerStatement(node) { - context.report({ - node, - messageId: "unexpected" - }); - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-delete-var.js b/tools/node_modules/eslint/lib/rules/no-delete-var.js deleted file mode 100644 index aeab951d75ff82..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-delete-var.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * @fileoverview Rule to flag when deleting variables - * @author Ilya Volodin - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow deleting variables", - category: "Variables", - recommended: true, - url: "https://eslint.org/docs/rules/no-delete-var" - }, - - schema: [], - - messages: { - unexpected: "Variables should not be deleted." - } - }, - - create(context) { - - return { - - UnaryExpression(node) { - if (node.operator === "delete" && node.argument.type === "Identifier") { - context.report({ node, messageId: "unexpected" }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-div-regex.js b/tools/node_modules/eslint/lib/rules/no-div-regex.js deleted file mode 100644 index 408e006528b584..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-div-regex.js +++ /dev/null @@ -1,45 +0,0 @@ -/** - * @fileoverview Rule to check for ambiguous div operator in regexes - * @author Matt DuVall - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow division operators explicitly at the beginning of regular expressions", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-div-regex" - }, - - schema: [], - - messages: { - unexpected: "A regular expression literal can be confused with '/='." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - return { - - Literal(node) { - const token = sourceCode.getFirstToken(node); - - if (token.type === "RegularExpression" && token.value[1] === "=") { - context.report({ node, messageId: "unexpected" }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-dupe-args.js b/tools/node_modules/eslint/lib/rules/no-dupe-args.js deleted file mode 100644 index 4e42336ae3dc34..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-dupe-args.js +++ /dev/null @@ -1,80 +0,0 @@ -/** - * @fileoverview Rule to flag duplicate arguments - * @author Jamund Ferguson - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow duplicate arguments in `function` definitions", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-dupe-args" - }, - - schema: [], - - messages: { - unexpected: "Duplicate param '{{name}}'." - } - }, - - create(context) { - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Checks whether or not a given definition is a parameter's. - * @param {eslint-scope.DefEntry} def - A definition to check. - * @returns {boolean} `true` if the definition is a parameter's. - */ - function isParameter(def) { - return def.type === "Parameter"; - } - - /** - * Determines if a given node has duplicate parameters. - * @param {ASTNode} node The node to check. - * @returns {void} - * @private - */ - function checkParams(node) { - const variables = context.getDeclaredVariables(node); - - for (let i = 0; i < variables.length; ++i) { - const variable = variables[i]; - - // Checks and reports duplications. - const defs = variable.defs.filter(isParameter); - - if (defs.length >= 2) { - context.report({ - node, - messageId: "unexpected", - data: { name: variable.name } - }); - } - } - } - - //-------------------------------------------------------------------------- - // Public API - //-------------------------------------------------------------------------- - - return { - FunctionDeclaration: checkParams, - FunctionExpression: checkParams - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-dupe-class-members.js b/tools/node_modules/eslint/lib/rules/no-dupe-class-members.js deleted file mode 100644 index 97f63a2896282b..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-dupe-class-members.js +++ /dev/null @@ -1,116 +0,0 @@ -/** - * @fileoverview A rule to disallow duplicate name in class members. - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow duplicate class members", - category: "ECMAScript 6", - recommended: true, - url: "https://eslint.org/docs/rules/no-dupe-class-members" - }, - - schema: [], - - messages: { - unexpected: "Duplicate name '{{name}}'." - } - }, - - create(context) { - let stack = []; - - /** - * Gets state of a given member name. - * @param {string} name - A name of a member. - * @param {boolean} isStatic - A flag which specifies that is a static member. - * @returns {Object} A state of a given member name. - * - retv.init {boolean} A flag which shows the name is declared as normal member. - * - retv.get {boolean} A flag which shows the name is declared as getter. - * - retv.set {boolean} A flag which shows the name is declared as setter. - */ - function getState(name, isStatic) { - const stateMap = stack[stack.length - 1]; - const key = `$${name}`; // to avoid "__proto__". - - if (!stateMap[key]) { - stateMap[key] = { - nonStatic: { init: false, get: false, set: false }, - static: { init: false, get: false, set: false } - }; - } - - return stateMap[key][isStatic ? "static" : "nonStatic"]; - } - - /** - * Gets the name text of a given node. - * - * @param {ASTNode} node - A node to get the name. - * @returns {string} The name text of the node. - */ - function getName(node) { - switch (node.type) { - case "Identifier": return node.name; - case "Literal": return String(node.value); - - /* istanbul ignore next: syntax error */ - default: return ""; - } - } - - return { - - // Initializes the stack of state of member declarations. - Program() { - stack = []; - }, - - // Initializes state of member declarations for the class. - ClassBody() { - stack.push(Object.create(null)); - }, - - // Disposes the state for the class. - "ClassBody:exit"() { - stack.pop(); - }, - - // Reports the node if its name has been declared already. - MethodDefinition(node) { - if (node.computed) { - return; - } - - const name = getName(node.key); - const state = getState(name, node.static); - let isDuplicate = false; - - if (node.kind === "get") { - isDuplicate = (state.init || state.get); - state.get = true; - } else if (node.kind === "set") { - isDuplicate = (state.init || state.set); - state.set = true; - } else { - isDuplicate = (state.init || state.get || state.set); - state.init = true; - } - - if (isDuplicate) { - context.report({ node, messageId: "unexpected", data: { name } }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-dupe-keys.js b/tools/node_modules/eslint/lib/rules/no-dupe-keys.js deleted file mode 100644 index 9b9c02f5efc9a1..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-dupe-keys.js +++ /dev/null @@ -1,142 +0,0 @@ -/** - * @fileoverview Rule to flag use of duplicate keys in an object. - * @author Ian Christian Myers - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const GET_KIND = /^(?:init|get)$/; -const SET_KIND = /^(?:init|set)$/; - -/** - * The class which stores properties' information of an object. - */ -class ObjectInfo { - - /** - * @param {ObjectInfo|null} upper - The information of the outer object. - * @param {ASTNode} node - The ObjectExpression node of this information. - */ - constructor(upper, node) { - this.upper = upper; - this.node = node; - this.properties = new Map(); - } - - /** - * Gets the information of the given Property node. - * @param {ASTNode} node - The Property node to get. - * @returns {{get: boolean, set: boolean}} The information of the property. - */ - getPropertyInfo(node) { - const name = astUtils.getStaticPropertyName(node); - - if (!this.properties.has(name)) { - this.properties.set(name, { get: false, set: false }); - } - return this.properties.get(name); - } - - /** - * Checks whether the given property has been defined already or not. - * @param {ASTNode} node - The Property node to check. - * @returns {boolean} `true` if the property has been defined. - */ - isPropertyDefined(node) { - const entry = this.getPropertyInfo(node); - - return ( - (GET_KIND.test(node.kind) && entry.get) || - (SET_KIND.test(node.kind) && entry.set) - ); - } - - /** - * Defines the given property. - * @param {ASTNode} node - The Property node to define. - * @returns {void} - */ - defineProperty(node) { - const entry = this.getPropertyInfo(node); - - if (GET_KIND.test(node.kind)) { - entry.get = true; - } - if (SET_KIND.test(node.kind)) { - entry.set = true; - } - } -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow duplicate keys in object literals", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-dupe-keys" - }, - - schema: [], - - messages: { - unexpected: "Duplicate key '{{name}}'." - } - }, - - create(context) { - let info = null; - - return { - ObjectExpression(node) { - info = new ObjectInfo(info, node); - }, - "ObjectExpression:exit"() { - info = info.upper; - }, - - Property(node) { - const name = astUtils.getStaticPropertyName(node); - - // Skip destructuring. - if (node.parent.type !== "ObjectExpression") { - return; - } - - // Skip if the name is not static. - if (!name) { - return; - } - - // Reports if the name is defined already. - if (info.isPropertyDefined(node)) { - context.report({ - node: info.node, - loc: node.key.loc, - messageId: "unexpected", - data: { name } - }); - } - - // Update info. - info.defineProperty(node); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-duplicate-case.js b/tools/node_modules/eslint/lib/rules/no-duplicate-case.js deleted file mode 100644 index 93c8548f91ad75..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-duplicate-case.js +++ /dev/null @@ -1,50 +0,0 @@ -/** - * @fileoverview Rule to disallow a duplicate case label. - * @author Dieter Oberkofler - * @author Burak Yigit Kaya - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow duplicate case labels", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-duplicate-case" - }, - - schema: [], - - messages: { - unexpected: "Duplicate case label." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - return { - SwitchStatement(node) { - const mapping = {}; - - node.cases.forEach(switchCase => { - const key = sourceCode.getText(switchCase.test); - - if (mapping[key]) { - context.report({ node: switchCase, messageId: "unexpected" }); - } else { - mapping[key] = switchCase; - } - }); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-duplicate-imports.js b/tools/node_modules/eslint/lib/rules/no-duplicate-imports.js deleted file mode 100644 index 03b5e2c12393ae..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-duplicate-imports.js +++ /dev/null @@ -1,146 +0,0 @@ -/** - * @fileoverview Restrict usage of duplicate imports. - * @author Simen Bekkhus - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -/** - * Returns the name of the module imported or re-exported. - * - * @param {ASTNode} node - A node to get. - * @returns {string} the name of the module, or empty string if no name. - */ -function getValue(node) { - if (node && node.source && node.source.value) { - return node.source.value.trim(); - } - - return ""; -} - -/** - * Checks if the name of the import or export exists in the given array, and reports if so. - * - * @param {RuleContext} context - The ESLint rule context object. - * @param {ASTNode} node - A node to get. - * @param {string} value - The name of the imported or exported module. - * @param {string[]} array - The array containing other imports or exports in the file. - * @param {string} messageId - A messageId to be reported after the name of the module - * - * @returns {void} No return value - */ -function checkAndReport(context, node, value, array, messageId) { - if (array.indexOf(value) !== -1) { - context.report({ - node, - messageId, - data: { - module: value - } - }); - } -} - -/** - * @callback nodeCallback - * @param {ASTNode} node - A node to handle. - */ - -/** - * Returns a function handling the imports of a given file - * - * @param {RuleContext} context - The ESLint rule context object. - * @param {boolean} includeExports - Whether or not to check for exports in addition to imports. - * @param {string[]} importsInFile - The array containing other imports in the file. - * @param {string[]} exportsInFile - The array containing other exports in the file. - * - * @returns {nodeCallback} A function passed to ESLint to handle the statement. - */ -function handleImports(context, includeExports, importsInFile, exportsInFile) { - return function(node) { - const value = getValue(node); - - if (value) { - checkAndReport(context, node, value, importsInFile, "import"); - - if (includeExports) { - checkAndReport(context, node, value, exportsInFile, "importAs"); - } - - importsInFile.push(value); - } - }; -} - -/** - * Returns a function handling the exports of a given file - * - * @param {RuleContext} context - The ESLint rule context object. - * @param {string[]} importsInFile - The array containing other imports in the file. - * @param {string[]} exportsInFile - The array containing other exports in the file. - * - * @returns {nodeCallback} A function passed to ESLint to handle the statement. - */ -function handleExports(context, importsInFile, exportsInFile) { - return function(node) { - const value = getValue(node); - - if (value) { - checkAndReport(context, node, value, exportsInFile, "export"); - checkAndReport(context, node, value, importsInFile, "exportAs"); - - exportsInFile.push(value); - } - }; -} - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow duplicate module imports", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/no-duplicate-imports" - }, - - schema: [{ - type: "object", - properties: { - includeExports: { - type: "boolean", - default: false - } - }, - additionalProperties: false - }], - messages: { - import: "'{{module}}' import is duplicated.", - importAs: "'{{module}}' import is duplicated as export.", - export: "'{{module}}' export is duplicated.", - exportAs: "'{{module}}' export is duplicated as import." - } - }, - - create(context) { - const includeExports = (context.options[0] || {}).includeExports, - importsInFile = [], - exportsInFile = []; - - const handlers = { - ImportDeclaration: handleImports(context, includeExports, importsInFile, exportsInFile) - }; - - if (includeExports) { - handlers.ExportNamedDeclaration = handleExports(context, importsInFile, exportsInFile); - handlers.ExportAllDeclaration = handleExports(context, importsInFile, exportsInFile); - } - - return handlers; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-else-return.js b/tools/node_modules/eslint/lib/rules/no-else-return.js deleted file mode 100644 index 5c21fb1b3fc21e..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-else-return.js +++ /dev/null @@ -1,285 +0,0 @@ -/** - * @fileoverview Rule to flag `else` after a `return` in `if` - * @author Ian Christian Myers - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); -const FixTracker = require("../util/fix-tracker"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow `else` blocks after `return` statements in `if` statements", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-else-return" - }, - - schema: [{ - type: "object", - properties: { - allowElseIf: { - type: "boolean", - default: true - } - }, - additionalProperties: false - }], - - fixable: "code", - - messages: { - unexpected: "Unnecessary 'else' after 'return'." - } - }, - - create(context) { - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Display the context report if rule is violated - * - * @param {Node} node The 'else' node - * @returns {void} - */ - function displayReport(node) { - context.report({ - node, - messageId: "unexpected", - fix: fixer => { - const sourceCode = context.getSourceCode(); - const startToken = sourceCode.getFirstToken(node); - const elseToken = sourceCode.getTokenBefore(startToken); - const source = sourceCode.getText(node); - const lastIfToken = sourceCode.getTokenBefore(elseToken); - let fixedSource, firstTokenOfElseBlock; - - if (startToken.type === "Punctuator" && startToken.value === "{") { - firstTokenOfElseBlock = sourceCode.getTokenAfter(startToken); - } else { - firstTokenOfElseBlock = startToken; - } - - /* - * If the if block does not have curly braces and does not end in a semicolon - * and the else block starts with (, [, /, +, ` or -, then it is not - * safe to remove the else keyword, because ASI will not add a semicolon - * after the if block - */ - const ifBlockMaybeUnsafe = node.parent.consequent.type !== "BlockStatement" && lastIfToken.value !== ";"; - const elseBlockUnsafe = /^[([/+`-]/.test(firstTokenOfElseBlock.value); - - if (ifBlockMaybeUnsafe && elseBlockUnsafe) { - return null; - } - - const endToken = sourceCode.getLastToken(node); - const lastTokenOfElseBlock = sourceCode.getTokenBefore(endToken); - - if (lastTokenOfElseBlock.value !== ";") { - const nextToken = sourceCode.getTokenAfter(endToken); - - const nextTokenUnsafe = nextToken && /^[([/+`-]/.test(nextToken.value); - const nextTokenOnSameLine = nextToken && nextToken.loc.start.line === lastTokenOfElseBlock.loc.start.line; - - /* - * If the else block contents does not end in a semicolon, - * and the else block starts with (, [, /, +, ` or -, then it is not - * safe to remove the else block, because ASI will not add a semicolon - * after the remaining else block contents - */ - if (nextTokenUnsafe || (nextTokenOnSameLine && nextToken.value !== "}")) { - return null; - } - } - - if (startToken.type === "Punctuator" && startToken.value === "{") { - fixedSource = source.slice(1, -1); - } else { - fixedSource = source; - } - - /* - * Extend the replacement range to include the entire - * function to avoid conflicting with no-useless-return. - * https://github.com/eslint/eslint/issues/8026 - */ - return new FixTracker(fixer, sourceCode) - .retainEnclosingFunction(node) - .replaceTextRange([elseToken.range[0], node.range[1]], fixedSource); - } - }); - } - - /** - * Check to see if the node is a ReturnStatement - * - * @param {Node} node The node being evaluated - * @returns {boolean} True if node is a return - */ - function checkForReturn(node) { - return node.type === "ReturnStatement"; - } - - /** - * Naive return checking, does not iterate through the whole - * BlockStatement because we make the assumption that the ReturnStatement - * will be the last node in the body of the BlockStatement. - * - * @param {Node} node The consequent/alternate node - * @returns {boolean} True if it has a return - */ - function naiveHasReturn(node) { - if (node.type === "BlockStatement") { - const body = node.body, - lastChildNode = body[body.length - 1]; - - return lastChildNode && checkForReturn(lastChildNode); - } - return checkForReturn(node); - } - - /** - * Check to see if the node is valid for evaluation, - * meaning it has an else. - * - * @param {Node} node The node being evaluated - * @returns {boolean} True if the node is valid - */ - function hasElse(node) { - return node.alternate && node.consequent; - } - - /** - * If the consequent is an IfStatement, check to see if it has an else - * and both its consequent and alternate path return, meaning this is - * a nested case of rule violation. If-Else not considered currently. - * - * @param {Node} node The consequent node - * @returns {boolean} True if this is a nested rule violation - */ - function checkForIf(node) { - return node.type === "IfStatement" && hasElse(node) && - naiveHasReturn(node.alternate) && naiveHasReturn(node.consequent); - } - - /** - * Check the consequent/body node to make sure it is not - * a ReturnStatement or an IfStatement that returns on both - * code paths. - * - * @param {Node} node The consequent or body node - * @returns {boolean} `true` if it is a Return/If node that always returns. - */ - function checkForReturnOrIf(node) { - return checkForReturn(node) || checkForIf(node); - } - - - /** - * Check whether a node returns in every codepath. - * @param {Node} node The node to be checked - * @returns {boolean} `true` if it returns on every codepath. - */ - function alwaysReturns(node) { - if (node.type === "BlockStatement") { - - // If we have a BlockStatement, check each consequent body node. - return node.body.some(checkForReturnOrIf); - } - - /* - * If not a block statement, make sure the consequent isn't a - * ReturnStatement or an IfStatement with returns on both paths. - */ - return checkForReturnOrIf(node); - } - - - /** - * Check the if statement, but don't catch else-if blocks. - * @returns {void} - * @param {Node} node The node for the if statement to check - * @private - */ - function checkIfWithoutElse(node) { - const parent = node.parent; - - /* - * Fixing this would require splitting one statement into two, so no error should - * be reported if this node is in a position where only one statement is allowed. - */ - if (!astUtils.STATEMENT_LIST_PARENTS.has(parent.type)) { - return; - } - - const consequents = []; - let alternate; - - for (let currentNode = node; currentNode.type === "IfStatement"; currentNode = currentNode.alternate) { - if (!currentNode.alternate) { - return; - } - consequents.push(currentNode.consequent); - alternate = currentNode.alternate; - } - - if (consequents.every(alwaysReturns)) { - displayReport(alternate); - } - } - - /** - * Check the if statement - * @returns {void} - * @param {Node} node The node for the if statement to check - * @private - */ - function checkIfWithElse(node) { - const parent = node.parent; - - - /* - * Fixing this would require splitting one statement into two, so no error should - * be reported if this node is in a position where only one statement is allowed. - */ - if (!astUtils.STATEMENT_LIST_PARENTS.has(parent.type)) { - return; - } - - const alternate = node.alternate; - - if (alternate && alwaysReturns(node.consequent)) { - displayReport(alternate); - } - } - - const allowElseIf = !(context.options[0] && context.options[0].allowElseIf === false); - - //-------------------------------------------------------------------------- - // Public API - //-------------------------------------------------------------------------- - - return { - - "IfStatement:exit": allowElseIf ? checkIfWithoutElse : checkIfWithElse - - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-empty-character-class.js b/tools/node_modules/eslint/lib/rules/no-empty-character-class.js deleted file mode 100644 index 6d2fb3c50186b2..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-empty-character-class.js +++ /dev/null @@ -1,64 +0,0 @@ -/** - * @fileoverview Rule to flag the use of empty character classes in regular expressions - * @author Ian Christian Myers - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/* - * plain-English description of the following regexp: - * 0. `^` fix the match at the beginning of the string - * 1. `\/`: the `/` that begins the regexp - * 2. `([^\\[]|\\.|\[([^\\\]]|\\.)+\])*`: regexp contents; 0 or more of the following - * 2.0. `[^\\[]`: any character that's not a `\` or a `[` (anything but escape sequences and character classes) - * 2.1. `\\.`: an escape sequence - * 2.2. `\[([^\\\]]|\\.)+\]`: a character class that isn't empty - * 3. `\/` the `/` that ends the regexp - * 4. `[gimuy]*`: optional regexp flags - * 5. `$`: fix the match at the end of the string - */ -const regex = /^\/([^\\[]|\\.|\[([^\\\]]|\\.)+])*\/[gimuys]*$/; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow empty character classes in regular expressions", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-empty-character-class" - }, - - schema: [], - - messages: { - unexpected: "Empty class." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - return { - - Literal(node) { - const token = sourceCode.getFirstToken(node); - - if (token.type === "RegularExpression" && !regex.test(token.value)) { - context.report({ node, messageId: "unexpected" }); - } - } - - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-empty-function.js b/tools/node_modules/eslint/lib/rules/no-empty-function.js deleted file mode 100644 index a443796e4e2861..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-empty-function.js +++ /dev/null @@ -1,167 +0,0 @@ -/** - * @fileoverview Rule to disallow empty functions. - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const ALLOW_OPTIONS = Object.freeze([ - "functions", - "arrowFunctions", - "generatorFunctions", - "methods", - "generatorMethods", - "getters", - "setters", - "constructors" -]); - -/** - * Gets the kind of a given function node. - * - * @param {ASTNode} node - A function node to get. This is one of - * an ArrowFunctionExpression, a FunctionDeclaration, or a - * FunctionExpression. - * @returns {string} The kind of the function. This is one of "functions", - * "arrowFunctions", "generatorFunctions", "asyncFunctions", "methods", - * "generatorMethods", "asyncMethods", "getters", "setters", and - * "constructors". - */ -function getKind(node) { - const parent = node.parent; - let kind = ""; - - if (node.type === "ArrowFunctionExpression") { - return "arrowFunctions"; - } - - // Detects main kind. - if (parent.type === "Property") { - if (parent.kind === "get") { - return "getters"; - } - if (parent.kind === "set") { - return "setters"; - } - kind = parent.method ? "methods" : "functions"; - - } else if (parent.type === "MethodDefinition") { - if (parent.kind === "get") { - return "getters"; - } - if (parent.kind === "set") { - return "setters"; - } - if (parent.kind === "constructor") { - return "constructors"; - } - kind = "methods"; - - } else { - kind = "functions"; - } - - // Detects prefix. - let prefix = ""; - - if (node.generator) { - prefix = "generator"; - } else if (node.async) { - prefix = "async"; - } else { - return kind; - } - return prefix + kind[0].toUpperCase() + kind.slice(1); -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow empty functions", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-empty-function" - }, - - schema: [ - { - type: "object", - properties: { - allow: { - type: "array", - items: { enum: ALLOW_OPTIONS }, - uniqueItems: true - } - }, - additionalProperties: false - } - ], - - messages: { - unexpected: "Unexpected empty {{name}}." - } - }, - - create(context) { - const options = context.options[0] || {}; - const allowed = options.allow || []; - - const sourceCode = context.getSourceCode(); - - /** - * Reports a given function node if the node matches the following patterns. - * - * - Not allowed by options. - * - The body is empty. - * - The body doesn't have any comments. - * - * @param {ASTNode} node - A function node to report. This is one of - * an ArrowFunctionExpression, a FunctionDeclaration, or a - * FunctionExpression. - * @returns {void} - */ - function reportIfEmpty(node) { - const kind = getKind(node); - const name = astUtils.getFunctionNameWithKind(node); - const innerComments = sourceCode.getTokens(node.body, { - includeComments: true, - filter: astUtils.isCommentToken - }); - - if (allowed.indexOf(kind) === -1 && - node.body.type === "BlockStatement" && - node.body.body.length === 0 && - innerComments.length === 0 - ) { - context.report({ - node, - loc: node.body.loc.start, - messageId: "unexpected", - data: { name } - }); - } - } - - return { - ArrowFunctionExpression: reportIfEmpty, - FunctionDeclaration: reportIfEmpty, - FunctionExpression: reportIfEmpty - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-empty-pattern.js b/tools/node_modules/eslint/lib/rules/no-empty-pattern.js deleted file mode 100644 index 9f34bfde92e2e9..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-empty-pattern.js +++ /dev/null @@ -1,43 +0,0 @@ -/** - * @fileoverview Rule to disallow an empty pattern - * @author Alberto Rodríguez - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow empty destructuring patterns", - category: "Best Practices", - recommended: true, - url: "https://eslint.org/docs/rules/no-empty-pattern" - }, - - schema: [], - - messages: { - unexpected: "Unexpected empty {{type}} pattern." - } - }, - - create(context) { - return { - ObjectPattern(node) { - if (node.properties.length === 0) { - context.report({ node, messageId: "unexpected", data: { type: "object" } }); - } - }, - ArrayPattern(node) { - if (node.elements.length === 0) { - context.report({ node, messageId: "unexpected", data: { type: "array" } }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-empty.js b/tools/node_modules/eslint/lib/rules/no-empty.js deleted file mode 100644 index 2d55dee66596a3..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-empty.js +++ /dev/null @@ -1,86 +0,0 @@ -/** - * @fileoverview Rule to flag use of an empty block statement - * @author Nicholas C. Zakas - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow empty block statements", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-empty" - }, - - schema: [ - { - type: "object", - properties: { - allowEmptyCatch: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - - messages: { - unexpected: "Empty {{type}} statement." - } - }, - - create(context) { - const options = context.options[0] || {}, - allowEmptyCatch = options.allowEmptyCatch || false; - - const sourceCode = context.getSourceCode(); - - return { - BlockStatement(node) { - - // if the body is not empty, we can just return immediately - if (node.body.length !== 0) { - return; - } - - // a function is generally allowed to be empty - if (astUtils.isFunction(node.parent)) { - return; - } - - if (allowEmptyCatch && node.parent.type === "CatchClause") { - return; - } - - // any other block is only allowed to be empty, if it contains a comment - if (sourceCode.getCommentsInside(node).length > 0) { - return; - } - - context.report({ node, messageId: "unexpected", data: { type: "block" } }); - }, - - SwitchStatement(node) { - - if (typeof node.cases === "undefined" || node.cases.length === 0) { - context.report({ node, messageId: "unexpected", data: { type: "switch" } }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-eq-null.js b/tools/node_modules/eslint/lib/rules/no-eq-null.js deleted file mode 100644 index b8dead96d2514c..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-eq-null.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * @fileoverview Rule to flag comparisons to null without a type-checking - * operator. - * @author Ian Christian Myers - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow `null` comparisons without type-checking operators", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-eq-null" - }, - - schema: [], - - messages: { - unexpected: "Use '===' to compare with null." - } - }, - - create(context) { - - return { - - BinaryExpression(node) { - const badOperator = node.operator === "==" || node.operator === "!="; - - if (node.right.type === "Literal" && node.right.raw === "null" && badOperator || - node.left.type === "Literal" && node.left.raw === "null" && badOperator) { - context.report({ node, messageId: "unexpected" }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-eval.js b/tools/node_modules/eslint/lib/rules/no-eval.js deleted file mode 100644 index d4b79468f194a4..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-eval.js +++ /dev/null @@ -1,314 +0,0 @@ -/** - * @fileoverview Rule to flag use of eval() statement - * @author Nicholas C. Zakas - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const candidatesOfGlobalObject = Object.freeze([ - "global", - "window" -]); - -/** - * Checks a given node is a Identifier node of the specified name. - * - * @param {ASTNode} node - A node to check. - * @param {string} name - A name to check. - * @returns {boolean} `true` if the node is a Identifier node of the name. - */ -function isIdentifier(node, name) { - return node.type === "Identifier" && node.name === name; -} - -/** - * Checks a given node is a Literal node of the specified string value. - * - * @param {ASTNode} node - A node to check. - * @param {string} name - A name to check. - * @returns {boolean} `true` if the node is a Literal node of the name. - */ -function isConstant(node, name) { - switch (node.type) { - case "Literal": - return node.value === name; - - case "TemplateLiteral": - return ( - node.expressions.length === 0 && - node.quasis[0].value.cooked === name - ); - - default: - return false; - } -} - -/** - * Checks a given node is a MemberExpression node which has the specified name's - * property. - * - * @param {ASTNode} node - A node to check. - * @param {string} name - A name to check. - * @returns {boolean} `true` if the node is a MemberExpression node which has - * the specified name's property - */ -function isMember(node, name) { - return ( - node.type === "MemberExpression" && - (node.computed ? isConstant : isIdentifier)(node.property, name) - ); -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow the use of `eval()`", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-eval" - }, - - schema: [ - { - type: "object", - properties: { - allowIndirect: { type: "boolean", default: false } - }, - additionalProperties: false - } - ], - - messages: { - unexpected: "eval can be harmful." - } - }, - - create(context) { - const allowIndirect = Boolean( - context.options[0] && - context.options[0].allowIndirect - ); - const sourceCode = context.getSourceCode(); - let funcInfo = null; - - /** - * Pushs a variable scope (Program or Function) information to the stack. - * - * This is used in order to check whether or not `this` binding is a - * reference to the global object. - * - * @param {ASTNode} node - A node of the scope. This is one of Program, - * FunctionDeclaration, FunctionExpression, and ArrowFunctionExpression. - * @returns {void} - */ - function enterVarScope(node) { - const strict = context.getScope().isStrict; - - funcInfo = { - upper: funcInfo, - node, - strict, - defaultThis: false, - initialized: strict - }; - } - - /** - * Pops a variable scope from the stack. - * - * @returns {void} - */ - function exitVarScope() { - funcInfo = funcInfo.upper; - } - - /** - * Reports a given node. - * - * `node` is `Identifier` or `MemberExpression`. - * The parent of `node` might be `CallExpression`. - * - * The location of the report is always `eval` `Identifier` (or possibly - * `Literal`). The type of the report is `CallExpression` if the parent is - * `CallExpression`. Otherwise, it's the given node type. - * - * @param {ASTNode} node - A node to report. - * @returns {void} - */ - function report(node) { - const parent = node.parent; - const locationNode = node.type === "MemberExpression" - ? node.property - : node; - - const reportNode = parent.type === "CallExpression" && parent.callee === node - ? parent - : node; - - context.report({ - node: reportNode, - loc: locationNode.loc.start, - messageId: "unexpected" - }); - } - - /** - * Reports accesses of `eval` via the global object. - * - * @param {eslint-scope.Scope} globalScope - The global scope. - * @returns {void} - */ - function reportAccessingEvalViaGlobalObject(globalScope) { - for (let i = 0; i < candidatesOfGlobalObject.length; ++i) { - const name = candidatesOfGlobalObject[i]; - const variable = astUtils.getVariableByName(globalScope, name); - - if (!variable) { - continue; - } - - const references = variable.references; - - for (let j = 0; j < references.length; ++j) { - const identifier = references[j].identifier; - let node = identifier.parent; - - // To detect code like `window.window.eval`. - while (isMember(node, name)) { - node = node.parent; - } - - // Reports. - if (isMember(node, "eval")) { - report(node); - } - } - } - } - - /** - * Reports all accesses of `eval` (excludes direct calls to eval). - * - * @param {eslint-scope.Scope} globalScope - The global scope. - * @returns {void} - */ - function reportAccessingEval(globalScope) { - const variable = astUtils.getVariableByName(globalScope, "eval"); - - if (!variable) { - return; - } - - const references = variable.references; - - for (let i = 0; i < references.length; ++i) { - const reference = references[i]; - const id = reference.identifier; - - if (id.name === "eval" && !astUtils.isCallee(id)) { - - // Is accessing to eval (excludes direct calls to eval) - report(id); - } - } - } - - if (allowIndirect) { - - // Checks only direct calls to eval. It's simple! - return { - "CallExpression:exit"(node) { - const callee = node.callee; - - if (isIdentifier(callee, "eval")) { - report(callee); - } - } - }; - } - - return { - "CallExpression:exit"(node) { - const callee = node.callee; - - if (isIdentifier(callee, "eval")) { - report(callee); - } - }, - - Program(node) { - const scope = context.getScope(), - features = context.parserOptions.ecmaFeatures || {}, - strict = - scope.isStrict || - node.sourceType === "module" || - (features.globalReturn && scope.childScopes[0].isStrict); - - funcInfo = { - upper: null, - node, - strict, - defaultThis: true, - initialized: true - }; - }, - - "Program:exit"() { - const globalScope = context.getScope(); - - exitVarScope(); - reportAccessingEval(globalScope); - reportAccessingEvalViaGlobalObject(globalScope); - }, - - FunctionDeclaration: enterVarScope, - "FunctionDeclaration:exit": exitVarScope, - FunctionExpression: enterVarScope, - "FunctionExpression:exit": exitVarScope, - ArrowFunctionExpression: enterVarScope, - "ArrowFunctionExpression:exit": exitVarScope, - - ThisExpression(node) { - if (!isMember(node.parent, "eval")) { - return; - } - - /* - * `this.eval` is found. - * Checks whether or not the value of `this` is the global object. - */ - if (!funcInfo.initialized) { - funcInfo.initialized = true; - funcInfo.defaultThis = astUtils.isDefaultThisBinding( - funcInfo.node, - sourceCode - ); - } - - if (!funcInfo.strict && funcInfo.defaultThis) { - - // `this.eval` is possible built-in `eval`. - report(node.parent); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-ex-assign.js b/tools/node_modules/eslint/lib/rules/no-ex-assign.js deleted file mode 100644 index 4cc179a6e8f00f..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-ex-assign.js +++ /dev/null @@ -1,52 +0,0 @@ -/** - * @fileoverview Rule to flag assignment of the exception parameter - * @author Stephen Murray - */ - -"use strict"; - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow reassigning exceptions in `catch` clauses", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-ex-assign" - }, - - schema: [], - - messages: { - unexpected: "Do not assign to the exception parameter." - } - }, - - create(context) { - - /** - * Finds and reports references that are non initializer and writable. - * @param {Variable} variable - A variable to check. - * @returns {void} - */ - function checkVariable(variable) { - astUtils.getModifyingReferences(variable.references).forEach(reference => { - context.report({ node: reference.identifier, messageId: "unexpected" }); - }); - } - - return { - CatchClause(node) { - context.getDeclaredVariables(node).forEach(checkVariable); - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-extend-native.js b/tools/node_modules/eslint/lib/rules/no-extend-native.js deleted file mode 100644 index 13895f0d06bb1b..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-extend-native.js +++ /dev/null @@ -1,181 +0,0 @@ -/** - * @fileoverview Rule to flag adding properties to native object's prototypes. - * @author David Nelson - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); -const globals = require("globals"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const propertyDefinitionMethods = new Set(["defineProperty", "defineProperties"]); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow extending native types", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-extend-native" - }, - - schema: [ - { - type: "object", - properties: { - exceptions: { - type: "array", - items: { - type: "string" - }, - uniqueItems: true - } - }, - additionalProperties: false - } - ], - - messages: { - unexpected: "{{builtin}} prototype is read only, properties should not be added." - } - }, - - create(context) { - - const config = context.options[0] || {}; - const exceptions = new Set(config.exceptions || []); - const modifiedBuiltins = new Set( - Object.keys(globals.builtin) - .filter(builtin => builtin[0].toUpperCase() === builtin[0]) - .filter(builtin => !exceptions.has(builtin)) - ); - - /** - * Reports a lint error for the given node. - * @param {ASTNode} node The node to report. - * @param {string} builtin The name of the native builtin being extended. - * @returns {void} - */ - function reportNode(node, builtin) { - context.report({ - node, - messageId: "unexpected", - data: { - builtin - } - }); - } - - /** - * Check to see if the `prototype` property of the given object - * identifier node is being accessed. - * @param {ASTNode} identifierNode The Identifier representing the object - * to check. - * @returns {boolean} True if the identifier is the object of a - * MemberExpression and its `prototype` property is being accessed, - * false otherwise. - */ - function isPrototypePropertyAccessed(identifierNode) { - return Boolean( - identifierNode && - identifierNode.parent && - identifierNode.parent.type === "MemberExpression" && - identifierNode.parent.object === identifierNode && - astUtils.getStaticPropertyName(identifierNode.parent) === "prototype" - ); - } - - /** - * Checks that an identifier is an object of a prototype whose member - * is being assigned in an AssignmentExpression. - * Example: Object.prototype.foo = "bar" - * @param {ASTNode} identifierNode The identifier to check. - * @returns {boolean} True if the identifier's prototype is modified. - */ - function isInPrototypePropertyAssignment(identifierNode) { - return Boolean( - isPrototypePropertyAccessed(identifierNode) && - identifierNode.parent.parent.type === "MemberExpression" && - identifierNode.parent.parent.parent.type === "AssignmentExpression" && - identifierNode.parent.parent.parent.left === identifierNode.parent.parent - ); - } - - /** - * Checks that an identifier is an object of a prototype whose member - * is being extended via the Object.defineProperty() or - * Object.defineProperties() methods. - * Example: Object.defineProperty(Array.prototype, "foo", ...) - * Example: Object.defineProperties(Array.prototype, ...) - * @param {ASTNode} identifierNode The identifier to check. - * @returns {boolean} True if the identifier's prototype is modified. - */ - function isInDefinePropertyCall(identifierNode) { - return Boolean( - isPrototypePropertyAccessed(identifierNode) && - identifierNode.parent.parent.type === "CallExpression" && - identifierNode.parent.parent.arguments[0] === identifierNode.parent && - identifierNode.parent.parent.callee.type === "MemberExpression" && - identifierNode.parent.parent.callee.object.type === "Identifier" && - identifierNode.parent.parent.callee.object.name === "Object" && - identifierNode.parent.parent.callee.property.type === "Identifier" && - propertyDefinitionMethods.has(identifierNode.parent.parent.callee.property.name) - ); - } - - /** - * Check to see if object prototype access is part of a prototype - * extension. There are three ways a prototype can be extended: - * 1. Assignment to prototype property (Object.prototype.foo = 1) - * 2. Object.defineProperty()/Object.defineProperties() on a prototype - * If prototype extension is detected, report the AssignmentExpression - * or CallExpression node. - * @param {ASTNode} identifierNode The Identifier representing the object - * which prototype is being accessed and possibly extended. - * @returns {void} - */ - function checkAndReportPrototypeExtension(identifierNode) { - if (isInPrototypePropertyAssignment(identifierNode)) { - - // Identifier --> MemberExpression --> MemberExpression --> AssignmentExpression - reportNode(identifierNode.parent.parent.parent, identifierNode.name); - } else if (isInDefinePropertyCall(identifierNode)) { - - // Identifier --> MemberExpression --> CallExpression - reportNode(identifierNode.parent.parent, identifierNode.name); - } - } - - return { - - "Program:exit"() { - const globalScope = context.getScope(); - - modifiedBuiltins.forEach(builtin => { - const builtinVar = globalScope.set.get(builtin); - - if (builtinVar && builtinVar.references) { - builtinVar.references - .map(ref => ref.identifier) - .forEach(checkAndReportPrototypeExtension); - } - }); - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-extra-bind.js b/tools/node_modules/eslint/lib/rules/no-extra-bind.js deleted file mode 100644 index abbe1868e89837..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-extra-bind.js +++ /dev/null @@ -1,173 +0,0 @@ -/** - * @fileoverview Rule to flag unnecessary bind calls - * @author Bence Dányi - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const SIDE_EFFECT_FREE_NODE_TYPES = new Set(["Literal", "Identifier", "ThisExpression", "FunctionExpression"]); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow unnecessary calls to `.bind()`", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-extra-bind" - }, - - schema: [], - fixable: "code", - - messages: { - unexpected: "The function binding is unnecessary." - } - }, - - create(context) { - let scopeInfo = null; - - /** - * Checks if a node is free of side effects. - * - * This check is stricter than it needs to be, in order to keep the implementation simple. - * - * @param {ASTNode} node A node to check. - * @returns {boolean} True if the node is known to be side-effect free, false otherwise. - */ - function isSideEffectFree(node) { - return SIDE_EFFECT_FREE_NODE_TYPES.has(node.type); - } - - /** - * Reports a given function node. - * - * @param {ASTNode} node - A node to report. This is a FunctionExpression or - * an ArrowFunctionExpression. - * @returns {void} - */ - function report(node) { - context.report({ - node: node.parent.parent, - messageId: "unexpected", - loc: node.parent.property.loc.start, - fix(fixer) { - if (node.parent.parent.arguments.length && !isSideEffectFree(node.parent.parent.arguments[0])) { - return null; - } - - const firstTokenToRemove = context.getSourceCode() - .getFirstTokenBetween(node.parent.object, node.parent.property, astUtils.isNotClosingParenToken); - - return fixer.removeRange([firstTokenToRemove.range[0], node.parent.parent.range[1]]); - } - }); - } - - /** - * Checks whether or not a given function node is the callee of `.bind()` - * method. - * - * e.g. `(function() {}.bind(foo))` - * - * @param {ASTNode} node - A node to report. This is a FunctionExpression or - * an ArrowFunctionExpression. - * @returns {boolean} `true` if the node is the callee of `.bind()` method. - */ - function isCalleeOfBindMethod(node) { - const parent = node.parent; - const grandparent = parent.parent; - - return ( - grandparent && - grandparent.type === "CallExpression" && - grandparent.callee === parent && - grandparent.arguments.length === 1 && - parent.type === "MemberExpression" && - parent.object === node && - astUtils.getStaticPropertyName(parent) === "bind" - ); - } - - /** - * Adds a scope information object to the stack. - * - * @param {ASTNode} node - A node to add. This node is a FunctionExpression - * or a FunctionDeclaration node. - * @returns {void} - */ - function enterFunction(node) { - scopeInfo = { - isBound: isCalleeOfBindMethod(node), - thisFound: false, - upper: scopeInfo - }; - } - - /** - * Removes the scope information object from the top of the stack. - * At the same time, this reports the function node if the function has - * `.bind()` and the `this` keywords found. - * - * @param {ASTNode} node - A node to remove. This node is a - * FunctionExpression or a FunctionDeclaration node. - * @returns {void} - */ - function exitFunction(node) { - if (scopeInfo.isBound && !scopeInfo.thisFound) { - report(node); - } - - scopeInfo = scopeInfo.upper; - } - - /** - * Reports a given arrow function if the function is callee of `.bind()` - * method. - * - * @param {ASTNode} node - A node to report. This node is an - * ArrowFunctionExpression. - * @returns {void} - */ - function exitArrowFunction(node) { - if (isCalleeOfBindMethod(node)) { - report(node); - } - } - - /** - * Set the mark as the `this` keyword was found in this scope. - * - * @returns {void} - */ - function markAsThisFound() { - if (scopeInfo) { - scopeInfo.thisFound = true; - } - } - - return { - "ArrowFunctionExpression:exit": exitArrowFunction, - FunctionDeclaration: enterFunction, - "FunctionDeclaration:exit": exitFunction, - FunctionExpression: enterFunction, - "FunctionExpression:exit": exitFunction, - ThisExpression: markAsThisFound - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-extra-boolean-cast.js b/tools/node_modules/eslint/lib/rules/no-extra-boolean-cast.js deleted file mode 100644 index 615603177a5a76..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-extra-boolean-cast.js +++ /dev/null @@ -1,129 +0,0 @@ -/** - * @fileoverview Rule to flag unnecessary double negation in Boolean contexts - * @author Brandon Mills - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow unnecessary boolean casts", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-extra-boolean-cast" - }, - - schema: [], - fixable: "code", - - messages: { - unexpectedCall: "Redundant Boolean call.", - unexpectedNegation: "Redundant double negation." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - // Node types which have a test which will coerce values to booleans. - const BOOLEAN_NODE_TYPES = [ - "IfStatement", - "DoWhileStatement", - "WhileStatement", - "ConditionalExpression", - "ForStatement" - ]; - - /** - * Check if a node is in a context where its value would be coerced to a boolean at runtime. - * - * @param {Object} node The node - * @param {Object} parent Its parent - * @returns {boolean} If it is in a boolean context - */ - function isInBooleanContext(node, parent) { - return ( - (BOOLEAN_NODE_TYPES.indexOf(parent.type) !== -1 && - node === parent.test) || - - // ! - (parent.type === "UnaryExpression" && - parent.operator === "!") - ); - } - - - return { - UnaryExpression(node) { - const ancestors = context.getAncestors(), - parent = ancestors.pop(), - grandparent = ancestors.pop(); - - // Exit early if it's guaranteed not to match - if (node.operator !== "!" || - parent.type !== "UnaryExpression" || - parent.operator !== "!") { - return; - } - - if (isInBooleanContext(parent, grandparent) || - - // Boolean() and new Boolean() - ((grandparent.type === "CallExpression" || grandparent.type === "NewExpression") && - grandparent.callee.type === "Identifier" && - grandparent.callee.name === "Boolean") - ) { - context.report({ - node, - messageId: "unexpectedNegation", - fix: fixer => fixer.replaceText(parent, sourceCode.getText(node.argument)) - }); - } - }, - CallExpression(node) { - const parent = node.parent; - - if (node.callee.type !== "Identifier" || node.callee.name !== "Boolean") { - return; - } - - if (isInBooleanContext(node, parent)) { - context.report({ - node, - messageId: "unexpectedCall", - fix: fixer => { - if (!node.arguments.length) { - return fixer.replaceText(parent, "true"); - } - - if (node.arguments.length > 1 || node.arguments[0].type === "SpreadElement") { - return null; - } - - const argument = node.arguments[0]; - - if (astUtils.getPrecedence(argument) < astUtils.getPrecedence(node.parent)) { - return fixer.replaceText(node, `(${sourceCode.getText(argument)})`); - } - return fixer.replaceText(node, sourceCode.getText(argument)); - } - }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-extra-label.js b/tools/node_modules/eslint/lib/rules/no-extra-label.js deleted file mode 100644 index f8acf7b2834fde..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-extra-label.js +++ /dev/null @@ -1,146 +0,0 @@ -/** - * @fileoverview Rule to disallow unnecessary labels - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow unnecessary labels", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-extra-label" - }, - - schema: [], - fixable: "code", - - messages: { - unexpected: "This label '{{name}}' is unnecessary." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - let scopeInfo = null; - - /** - * Creates a new scope with a breakable statement. - * - * @param {ASTNode} node - A node to create. This is a BreakableStatement. - * @returns {void} - */ - function enterBreakableStatement(node) { - scopeInfo = { - label: node.parent.type === "LabeledStatement" ? node.parent.label : null, - breakable: true, - upper: scopeInfo - }; - } - - /** - * Removes the top scope of the stack. - * - * @returns {void} - */ - function exitBreakableStatement() { - scopeInfo = scopeInfo.upper; - } - - /** - * Creates a new scope with a labeled statement. - * - * This ignores it if the body is a breakable statement. - * In this case it's handled in the `enterBreakableStatement` function. - * - * @param {ASTNode} node - A node to create. This is a LabeledStatement. - * @returns {void} - */ - function enterLabeledStatement(node) { - if (!astUtils.isBreakableStatement(node.body)) { - scopeInfo = { - label: node.label, - breakable: false, - upper: scopeInfo - }; - } - } - - /** - * Removes the top scope of the stack. - * - * This ignores it if the body is a breakable statement. - * In this case it's handled in the `exitBreakableStatement` function. - * - * @param {ASTNode} node - A node. This is a LabeledStatement. - * @returns {void} - */ - function exitLabeledStatement(node) { - if (!astUtils.isBreakableStatement(node.body)) { - scopeInfo = scopeInfo.upper; - } - } - - /** - * Reports a given control node if it's unnecessary. - * - * @param {ASTNode} node - A node. This is a BreakStatement or a - * ContinueStatement. - * @returns {void} - */ - function reportIfUnnecessary(node) { - if (!node.label) { - return; - } - - const labelNode = node.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, - messageId: "unexpected", - data: labelNode, - fix: fixer => fixer.removeRange([sourceCode.getFirstToken(node).range[1], labelNode.range[1]]) - }); - } - return; - } - } - } - - return { - WhileStatement: enterBreakableStatement, - "WhileStatement:exit": exitBreakableStatement, - DoWhileStatement: enterBreakableStatement, - "DoWhileStatement:exit": exitBreakableStatement, - ForStatement: enterBreakableStatement, - "ForStatement:exit": exitBreakableStatement, - ForInStatement: enterBreakableStatement, - "ForInStatement:exit": exitBreakableStatement, - ForOfStatement: enterBreakableStatement, - "ForOfStatement:exit": exitBreakableStatement, - SwitchStatement: enterBreakableStatement, - "SwitchStatement:exit": exitBreakableStatement, - LabeledStatement: enterLabeledStatement, - "LabeledStatement:exit": exitLabeledStatement, - BreakStatement: reportIfUnnecessary, - ContinueStatement: reportIfUnnecessary - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-extra-parens.js b/tools/node_modules/eslint/lib/rules/no-extra-parens.js deleted file mode 100644 index 9f16e0e6ccc622..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-extra-parens.js +++ /dev/null @@ -1,750 +0,0 @@ -/** - * @fileoverview Disallow parenthesising higher precedence subexpressions. - * @author Michael Ficarra - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils.js"); - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "disallow unnecessary parentheses", - category: "Possible Errors", - recommended: false, - url: "https://eslint.org/docs/rules/no-extra-parens" - }, - - fixable: "code", - - schema: { - anyOf: [ - { - type: "array", - items: [ - { - enum: ["functions"] - } - ], - minItems: 0, - maxItems: 1 - }, - { - type: "array", - items: [ - { - enum: ["all"] - }, - { - type: "object", - properties: { - conditionalAssign: { type: "boolean", default: true }, - nestedBinaryExpressions: { type: "boolean", default: true }, - returnAssign: { type: "boolean", default: true }, - ignoreJSX: { enum: ["none", "all", "single-line", "multi-line"] }, - enforceForArrowConditionals: { type: "boolean", default: true } - }, - additionalProperties: false - } - ], - minItems: 0, - maxItems: 2 - } - ] - }, - - messages: { - unexpected: "Unnecessary parentheses around expression." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - const tokensToIgnore = new WeakSet(); - const isParenthesised = astUtils.isParenthesised.bind(astUtils, sourceCode); - const precedence = astUtils.getPrecedence; - const ALL_NODES = context.options[0] !== "functions"; - const EXCEPT_COND_ASSIGN = ALL_NODES && context.options[1] && context.options[1].conditionalAssign === false; - const NESTED_BINARY = ALL_NODES && context.options[1] && context.options[1].nestedBinaryExpressions === false; - const EXCEPT_RETURN_ASSIGN = ALL_NODES && context.options[1] && context.options[1].returnAssign === false; - const IGNORE_JSX = ALL_NODES && context.options[1] && context.options[1].ignoreJSX; - const IGNORE_ARROW_CONDITIONALS = ALL_NODES && context.options[1] && - context.options[1].enforceForArrowConditionals === false; - - const PRECEDENCE_OF_ASSIGNMENT_EXPR = precedence({ type: "AssignmentExpression" }); - const PRECEDENCE_OF_UPDATE_EXPR = precedence({ type: "UpdateExpression" }); - - /** - * Determines if this rule should be enforced for a node given the current configuration. - * @param {ASTNode} node - The node to be checked. - * @returns {boolean} True if the rule should be enforced for this node. - * @private - */ - function ruleApplies(node) { - if (node.type === "JSXElement" || node.type === "JSXFragment") { - const isSingleLine = node.loc.start.line === node.loc.end.line; - - switch (IGNORE_JSX) { - - // Exclude this JSX element from linting - case "all": - return false; - - // Exclude this JSX element if it is multi-line element - case "multi-line": - return isSingleLine; - - // Exclude this JSX element if it is single-line element - case "single-line": - return !isSingleLine; - - // Nothing special to be done for JSX elements - case "none": - break; - - // no default - } - } - - return ALL_NODES || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression"; - } - - /** - * Determines if a node is surrounded by parentheses twice. - * @param {ASTNode} node - The node to be checked. - * @returns {boolean} True if the node is doubly parenthesised. - * @private - */ - function isParenthesisedTwice(node) { - const previousToken = sourceCode.getTokenBefore(node, 1), - nextToken = sourceCode.getTokenAfter(node, 1); - - return isParenthesised(node) && previousToken && nextToken && - astUtils.isOpeningParenToken(previousToken) && previousToken.range[1] <= node.range[0] && - astUtils.isClosingParenToken(nextToken) && nextToken.range[0] >= node.range[1]; - } - - /** - * Determines if a node is surrounded by (potentially) invalid parentheses. - * @param {ASTNode} node - The node to be checked. - * @returns {boolean} True if the node is incorrectly parenthesised. - * @private - */ - function hasExcessParens(node) { - return ruleApplies(node) && isParenthesised(node); - } - - /** - * Determines if a node that is expected to be parenthesised is surrounded by - * (potentially) invalid extra parentheses. - * @param {ASTNode} node - The node to be checked. - * @returns {boolean} True if the node is has an unexpected extra pair of parentheses. - * @private - */ - function hasDoubleExcessParens(node) { - return ruleApplies(node) && isParenthesisedTwice(node); - } - - /** - * Determines if a node test expression is allowed to have a parenthesised assignment - * @param {ASTNode} node - The node to be checked. - * @returns {boolean} True if the assignment can be parenthesised. - * @private - */ - function isCondAssignException(node) { - return EXCEPT_COND_ASSIGN && node.test.type === "AssignmentExpression"; - } - - /** - * Determines if a node is in a return statement - * @param {ASTNode} node - The node to be checked. - * @returns {boolean} True if the node is in a return statement. - * @private - */ - function isInReturnStatement(node) { - for (let currentNode = node; currentNode; currentNode = currentNode.parent) { - if ( - currentNode.type === "ReturnStatement" || - (currentNode.type === "ArrowFunctionExpression" && currentNode.body.type !== "BlockStatement") - ) { - return true; - } - } - - return false; - } - - /** - * Determines if a constructor function is newed-up with parens - * @param {ASTNode} newExpression - The NewExpression node to be checked. - * @returns {boolean} True if the constructor is called with parens. - * @private - */ - function isNewExpressionWithParens(newExpression) { - const lastToken = sourceCode.getLastToken(newExpression); - const penultimateToken = sourceCode.getTokenBefore(lastToken); - - return newExpression.arguments.length > 0 || astUtils.isOpeningParenToken(penultimateToken) && astUtils.isClosingParenToken(lastToken); - } - - /** - * Determines if a node is or contains an assignment expression - * @param {ASTNode} node - The node to be checked. - * @returns {boolean} True if the node is or contains an assignment expression. - * @private - */ - function containsAssignment(node) { - if (node.type === "AssignmentExpression") { - return true; - } - if (node.type === "ConditionalExpression" && - (node.consequent.type === "AssignmentExpression" || node.alternate.type === "AssignmentExpression")) { - return true; - } - if ((node.left && node.left.type === "AssignmentExpression") || - (node.right && node.right.type === "AssignmentExpression")) { - return true; - } - - return false; - } - - /** - * Determines if a node is contained by or is itself a return statement and is allowed to have a parenthesised assignment - * @param {ASTNode} node - The node to be checked. - * @returns {boolean} True if the assignment can be parenthesised. - * @private - */ - function isReturnAssignException(node) { - if (!EXCEPT_RETURN_ASSIGN || !isInReturnStatement(node)) { - return false; - } - - if (node.type === "ReturnStatement") { - return node.argument && containsAssignment(node.argument); - } - if (node.type === "ArrowFunctionExpression" && node.body.type !== "BlockStatement") { - return containsAssignment(node.body); - } - return containsAssignment(node); - - } - - /** - * Determines if a node following a [no LineTerminator here] restriction is - * surrounded by (potentially) invalid extra parentheses. - * @param {Token} token - The token preceding the [no LineTerminator here] restriction. - * @param {ASTNode} node - The node to be checked. - * @returns {boolean} True if the node is incorrectly parenthesised. - * @private - */ - function hasExcessParensNoLineTerminator(token, node) { - if (token.loc.end.line === node.loc.start.line) { - return hasExcessParens(node); - } - - return hasDoubleExcessParens(node); - } - - /** - * Determines whether a node should be preceded by an additional space when removing parens - * @param {ASTNode} node node to evaluate; must be surrounded by parentheses - * @returns {boolean} `true` if a space should be inserted before the node - * @private - */ - function requiresLeadingSpace(node) { - const leftParenToken = sourceCode.getTokenBefore(node); - const tokenBeforeLeftParen = sourceCode.getTokenBefore(node, 1); - const firstToken = sourceCode.getFirstToken(node); - - return tokenBeforeLeftParen && - tokenBeforeLeftParen.range[1] === leftParenToken.range[0] && - leftParenToken.range[1] === firstToken.range[0] && - !astUtils.canTokensBeAdjacent(tokenBeforeLeftParen, firstToken); - } - - /** - * Determines whether a node should be followed by an additional space when removing parens - * @param {ASTNode} node node to evaluate; must be surrounded by parentheses - * @returns {boolean} `true` if a space should be inserted after the node - * @private - */ - function requiresTrailingSpace(node) { - const nextTwoTokens = sourceCode.getTokensAfter(node, { count: 2 }); - const rightParenToken = nextTwoTokens[0]; - const tokenAfterRightParen = nextTwoTokens[1]; - const tokenBeforeRightParen = sourceCode.getLastToken(node); - - return rightParenToken && tokenAfterRightParen && - !sourceCode.isSpaceBetweenTokens(rightParenToken, tokenAfterRightParen) && - !astUtils.canTokensBeAdjacent(tokenBeforeRightParen, tokenAfterRightParen); - } - - /** - * Determines if a given expression node is an IIFE - * @param {ASTNode} node The node to check - * @returns {boolean} `true` if the given node is an IIFE - */ - function isIIFE(node) { - return node.type === "CallExpression" && node.callee.type === "FunctionExpression"; - } - - /** - * Report the node - * @param {ASTNode} node node to evaluate - * @returns {void} - * @private - */ - function report(node) { - const leftParenToken = sourceCode.getTokenBefore(node); - const rightParenToken = sourceCode.getTokenAfter(node); - - if (!isParenthesisedTwice(node)) { - if (tokensToIgnore.has(sourceCode.getFirstToken(node))) { - return; - } - - if (isIIFE(node) && !isParenthesised(node.callee)) { - return; - } - } - - context.report({ - node, - loc: leftParenToken.loc.start, - messageId: "unexpected", - fix(fixer) { - const parenthesizedSource = sourceCode.text.slice(leftParenToken.range[1], rightParenToken.range[0]); - - return fixer.replaceTextRange([ - leftParenToken.range[0], - rightParenToken.range[1] - ], (requiresLeadingSpace(node) ? " " : "") + parenthesizedSource + (requiresTrailingSpace(node) ? " " : "")); - } - }); - } - - /** - * Evaluate Unary update - * @param {ASTNode} node node to evaluate - * @returns {void} - * @private - */ - function checkUnaryUpdate(node) { - if (node.type === "UnaryExpression" && node.argument.type === "BinaryExpression" && node.argument.operator === "**") { - return; - } - - if (hasExcessParens(node.argument) && precedence(node.argument) >= precedence(node)) { - report(node.argument); - } - } - - /** - * Check if a member expression contains a call expression - * @param {ASTNode} node MemberExpression node to evaluate - * @returns {boolean} true if found, false if not - */ - function doesMemberExpressionContainCallExpression(node) { - let currentNode = node.object; - let currentNodeType = node.object.type; - - while (currentNodeType === "MemberExpression") { - currentNode = currentNode.object; - currentNodeType = currentNode.type; - } - - return currentNodeType === "CallExpression"; - } - - /** - * Evaluate a new call - * @param {ASTNode} node node to evaluate - * @returns {void} - * @private - */ - function checkCallNew(node) { - const callee = node.callee; - - if (hasExcessParens(callee) && precedence(callee) >= precedence(node)) { - const hasNewParensException = callee.type === "NewExpression" && !isNewExpressionWithParens(callee); - - if ( - hasDoubleExcessParens(callee) || - !isIIFE(node) && !hasNewParensException && !( - - /* - * Allow extra parens around a new expression if - * there are intervening parentheses. - */ - (callee.type === "MemberExpression" && doesMemberExpressionContainCallExpression(callee)) - ) - ) { - report(node.callee); - } - } - if (node.arguments.length === 1) { - if (hasDoubleExcessParens(node.arguments[0]) && precedence(node.arguments[0]) >= PRECEDENCE_OF_ASSIGNMENT_EXPR) { - report(node.arguments[0]); - } - } else { - node.arguments - .filter(arg => hasExcessParens(arg) && precedence(arg) >= PRECEDENCE_OF_ASSIGNMENT_EXPR) - .forEach(report); - } - } - - /** - * Evaluate binary logicals - * @param {ASTNode} node node to evaluate - * @returns {void} - * @private - */ - function checkBinaryLogical(node) { - const prec = precedence(node); - const leftPrecedence = precedence(node.left); - const rightPrecedence = precedence(node.right); - const isExponentiation = node.operator === "**"; - const shouldSkipLeft = (NESTED_BINARY && (node.left.type === "BinaryExpression" || node.left.type === "LogicalExpression")) || - node.left.type === "UnaryExpression" && isExponentiation; - const shouldSkipRight = NESTED_BINARY && (node.right.type === "BinaryExpression" || node.right.type === "LogicalExpression"); - - if (!shouldSkipLeft && hasExcessParens(node.left) && (leftPrecedence > prec || (leftPrecedence === prec && !isExponentiation))) { - report(node.left); - } - if (!shouldSkipRight && hasExcessParens(node.right) && (rightPrecedence > prec || (rightPrecedence === prec && isExponentiation))) { - report(node.right); - } - } - - /** - * Check the parentheses around the super class of the given class definition. - * @param {ASTNode} node The node of class declarations to check. - * @returns {void} - */ - function checkClass(node) { - if (!node.superClass) { - return; - } - - /* - * If `node.superClass` is a LeftHandSideExpression, parentheses are extra. - * Otherwise, parentheses are needed. - */ - const hasExtraParens = precedence(node.superClass) > PRECEDENCE_OF_UPDATE_EXPR - ? hasExcessParens(node.superClass) - : hasDoubleExcessParens(node.superClass); - - if (hasExtraParens) { - report(node.superClass); - } - } - - /** - * Check the parentheses around the argument of the given spread operator. - * @param {ASTNode} node The node of spread elements/properties to check. - * @returns {void} - */ - function checkSpreadOperator(node) { - const hasExtraParens = precedence(node.argument) >= PRECEDENCE_OF_ASSIGNMENT_EXPR - ? hasExcessParens(node.argument) - : hasDoubleExcessParens(node.argument); - - if (hasExtraParens) { - report(node.argument); - } - } - - /** - * Checks the parentheses for an ExpressionStatement or ExportDefaultDeclaration - * @param {ASTNode} node The ExpressionStatement.expression or ExportDefaultDeclaration.declaration node - * @returns {void} - */ - function checkExpressionOrExportStatement(node) { - const firstToken = isParenthesised(node) ? sourceCode.getTokenBefore(node) : sourceCode.getFirstToken(node); - const secondToken = sourceCode.getTokenAfter(firstToken, astUtils.isNotOpeningParenToken); - const thirdToken = secondToken ? sourceCode.getTokenAfter(secondToken) : null; - - if ( - astUtils.isOpeningParenToken(firstToken) && - ( - astUtils.isOpeningBraceToken(secondToken) || - secondToken.type === "Keyword" && ( - secondToken.value === "function" || - secondToken.value === "class" || - secondToken.value === "let" && astUtils.isOpeningBracketToken(sourceCode.getTokenAfter(secondToken, astUtils.isNotClosingParenToken)) - ) || - secondToken && secondToken.type === "Identifier" && secondToken.value === "async" && thirdToken && thirdToken.type === "Keyword" && thirdToken.value === "function" - ) - ) { - tokensToIgnore.add(secondToken); - } - - if (hasExcessParens(node)) { - report(node); - } - } - - return { - ArrayExpression(node) { - node.elements - .filter(e => e && hasExcessParens(e) && precedence(e) >= PRECEDENCE_OF_ASSIGNMENT_EXPR) - .forEach(report); - }, - - ArrowFunctionExpression(node) { - if (isReturnAssignException(node)) { - return; - } - - if (node.body.type === "ConditionalExpression" && - IGNORE_ARROW_CONDITIONALS && - !isParenthesisedTwice(node.body) - ) { - return; - } - - if (node.body.type !== "BlockStatement") { - const firstBodyToken = sourceCode.getFirstToken(node.body, astUtils.isNotOpeningParenToken); - const tokenBeforeFirst = sourceCode.getTokenBefore(firstBodyToken); - - if (astUtils.isOpeningParenToken(tokenBeforeFirst) && astUtils.isOpeningBraceToken(firstBodyToken)) { - tokensToIgnore.add(firstBodyToken); - } - if (hasExcessParens(node.body) && precedence(node.body) >= PRECEDENCE_OF_ASSIGNMENT_EXPR) { - report(node.body); - } - } - }, - - AssignmentExpression(node) { - if (isReturnAssignException(node)) { - return; - } - - if (hasExcessParens(node.right) && precedence(node.right) >= precedence(node)) { - report(node.right); - } - }, - - BinaryExpression: checkBinaryLogical, - CallExpression: checkCallNew, - - ConditionalExpression(node) { - if (isReturnAssignException(node)) { - return; - } - - if (hasExcessParens(node.test) && precedence(node.test) >= precedence({ type: "LogicalExpression", operator: "||" })) { - report(node.test); - } - - if (hasExcessParens(node.consequent) && precedence(node.consequent) >= PRECEDENCE_OF_ASSIGNMENT_EXPR) { - report(node.consequent); - } - - if (hasExcessParens(node.alternate) && precedence(node.alternate) >= PRECEDENCE_OF_ASSIGNMENT_EXPR) { - report(node.alternate); - } - }, - - DoWhileStatement(node) { - if (hasDoubleExcessParens(node.test) && !isCondAssignException(node)) { - report(node.test); - } - }, - - ExportDefaultDeclaration: node => checkExpressionOrExportStatement(node.declaration), - ExpressionStatement: node => checkExpressionOrExportStatement(node.expression), - - "ForInStatement, ForOfStatement"(node) { - if (node.left.type !== "VariableDeclarator") { - const firstLeftToken = sourceCode.getFirstToken(node.left, astUtils.isNotOpeningParenToken); - - if ( - firstLeftToken.value === "let" && ( - - /* - * If `let` is the only thing on the left side of the loop, it's the loop variable: `for ((let) of foo);` - * Removing it will cause a syntax error, because it will be parsed as the start of a VariableDeclarator. - */ - (firstLeftToken.range[1] === node.left.range[1] || /* - * If `let` is followed by a `[` token, it's a property access on the `let` value: `for ((let[foo]) of bar);` - * Removing it will cause the property access to be parsed as a destructuring declaration of `foo` instead. - */ - astUtils.isOpeningBracketToken( - sourceCode.getTokenAfter(firstLeftToken, astUtils.isNotClosingParenToken) - )) - ) - ) { - tokensToIgnore.add(firstLeftToken); - } - } - if (!(node.type === "ForOfStatement" && node.right.type === "SequenceExpression") && hasExcessParens(node.right)) { - report(node.right); - } - if (hasExcessParens(node.left)) { - report(node.left); - } - }, - - ForStatement(node) { - if (node.init && hasExcessParens(node.init)) { - report(node.init); - } - - if (node.test && hasExcessParens(node.test) && !isCondAssignException(node)) { - report(node.test); - } - - if (node.update && hasExcessParens(node.update)) { - report(node.update); - } - }, - - IfStatement(node) { - if (hasDoubleExcessParens(node.test) && !isCondAssignException(node)) { - report(node.test); - } - }, - - LogicalExpression: checkBinaryLogical, - - MemberExpression(node) { - const nodeObjHasExcessParens = hasExcessParens(node.object); - - if ( - nodeObjHasExcessParens && - precedence(node.object) >= precedence(node) && - ( - node.computed || - !( - astUtils.isDecimalInteger(node.object) || - - // RegExp literal is allowed to have parens (#1589) - (node.object.type === "Literal" && node.object.regex) - ) - ) - ) { - report(node.object); - } - - if (nodeObjHasExcessParens && - node.object.type === "CallExpression" && - node.parent.type !== "NewExpression") { - report(node.object); - } - - if (node.computed && hasExcessParens(node.property)) { - report(node.property); - } - }, - - NewExpression: checkCallNew, - - ObjectExpression(node) { - node.properties - .filter(property => { - const value = property.value; - - return value && hasExcessParens(value) && precedence(value) >= PRECEDENCE_OF_ASSIGNMENT_EXPR; - }).forEach(property => report(property.value)); - }, - - ReturnStatement(node) { - const returnToken = sourceCode.getFirstToken(node); - - if (isReturnAssignException(node)) { - return; - } - - if (node.argument && - hasExcessParensNoLineTerminator(returnToken, node.argument) && - - // RegExp literal is allowed to have parens (#1589) - !(node.argument.type === "Literal" && node.argument.regex)) { - report(node.argument); - } - }, - - SequenceExpression(node) { - node.expressions - .filter(e => hasExcessParens(e) && precedence(e) >= precedence(node)) - .forEach(report); - }, - - SwitchCase(node) { - if (node.test && hasExcessParens(node.test)) { - report(node.test); - } - }, - - SwitchStatement(node) { - if (hasDoubleExcessParens(node.discriminant)) { - report(node.discriminant); - } - }, - - ThrowStatement(node) { - const throwToken = sourceCode.getFirstToken(node); - - if (hasExcessParensNoLineTerminator(throwToken, node.argument)) { - report(node.argument); - } - }, - - UnaryExpression: checkUnaryUpdate, - UpdateExpression: checkUnaryUpdate, - AwaitExpression: checkUnaryUpdate, - - VariableDeclarator(node) { - if (node.init && hasExcessParens(node.init) && - precedence(node.init) >= PRECEDENCE_OF_ASSIGNMENT_EXPR && - - // RegExp literal is allowed to have parens (#1589) - !(node.init.type === "Literal" && node.init.regex)) { - report(node.init); - } - }, - - WhileStatement(node) { - if (hasDoubleExcessParens(node.test) && !isCondAssignException(node)) { - report(node.test); - } - }, - - WithStatement(node) { - if (hasDoubleExcessParens(node.object)) { - report(node.object); - } - }, - - YieldExpression(node) { - if (node.argument) { - const yieldToken = sourceCode.getFirstToken(node); - - if ((precedence(node.argument) >= precedence(node) && - hasExcessParensNoLineTerminator(yieldToken, node.argument)) || - hasDoubleExcessParens(node.argument)) { - report(node.argument); - } - } - }, - - ClassDeclaration: checkClass, - ClassExpression: checkClass, - - SpreadElement: checkSpreadOperator, - SpreadProperty: checkSpreadOperator, - ExperimentalSpreadProperty: checkSpreadOperator - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-extra-semi.js b/tools/node_modules/eslint/lib/rules/no-extra-semi.js deleted file mode 100644 index d87a181672f851..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-extra-semi.js +++ /dev/null @@ -1,127 +0,0 @@ -/** - * @fileoverview Rule to flag use of unnecessary semicolons - * @author Nicholas C. Zakas - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const FixTracker = require("../util/fix-tracker"); -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow unnecessary semicolons", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-extra-semi" - }, - - fixable: "code", - schema: [], - - messages: { - unexpected: "Unnecessary semicolon." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - /** - * Reports an unnecessary semicolon error. - * @param {Node|Token} nodeOrToken - A node or a token to be reported. - * @returns {void} - */ - function report(nodeOrToken) { - context.report({ - node: nodeOrToken, - messageId: "unexpected", - fix(fixer) { - - /* - * Expand the replacement range to include the surrounding - * tokens to avoid conflicting with semi. - * https://github.com/eslint/eslint/issues/7928 - */ - return new FixTracker(fixer, context.getSourceCode()) - .retainSurroundingTokens(nodeOrToken) - .remove(nodeOrToken); - } - }); - } - - /** - * Checks for a part of a class body. - * This checks tokens from a specified token to a next MethodDefinition or the end of class body. - * - * @param {Token} firstToken - The first token to check. - * @returns {void} - */ - function checkForPartOfClassBody(firstToken) { - for (let token = firstToken; - token.type === "Punctuator" && !astUtils.isClosingBraceToken(token); - token = sourceCode.getTokenAfter(token) - ) { - if (astUtils.isSemicolonToken(token)) { - report(token); - } - } - } - - return { - - /** - * Reports this empty statement, except if the parent node is a loop. - * @param {Node} node - A EmptyStatement node to be reported. - * @returns {void} - */ - EmptyStatement(node) { - const parent = node.parent, - allowedParentTypes = [ - "ForStatement", - "ForInStatement", - "ForOfStatement", - "WhileStatement", - "DoWhileStatement", - "IfStatement", - "LabeledStatement", - "WithStatement" - ]; - - if (allowedParentTypes.indexOf(parent.type) === -1) { - report(node); - } - }, - - /** - * Checks tokens from the head of this class body to the first MethodDefinition or the end of this class body. - * @param {Node} node - A ClassBody node to check. - * @returns {void} - */ - ClassBody(node) { - checkForPartOfClassBody(sourceCode.getFirstToken(node, 1)); // 0 is `{`. - }, - - /** - * Checks tokens from this MethodDefinition to the next MethodDefinition or the end of this class body. - * @param {Node} node - A MethodDefinition node of the start point. - * @returns {void} - */ - MethodDefinition(node) { - checkForPartOfClassBody(sourceCode.getTokenAfter(node)); - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-fallthrough.js b/tools/node_modules/eslint/lib/rules/no-fallthrough.js deleted file mode 100644 index dfd9d8541587b2..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-fallthrough.js +++ /dev/null @@ -1,142 +0,0 @@ -/** - * @fileoverview Rule to flag fall-through cases in switch statements. - * @author Matt DuVall - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const lodash = require("lodash"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const DEFAULT_FALLTHROUGH_COMMENT = /falls?\s?through/i; - -/** - * Checks whether or not a given node has a fallthrough comment. - * @param {ASTNode} node - A SwitchCase node to get comments. - * @param {RuleContext} context - A rule context which stores comments. - * @param {RegExp} fallthroughCommentPattern - A pattern to match comment to. - * @returns {boolean} `true` if the node has a valid fallthrough comment. - */ -function hasFallthroughComment(node, context, fallthroughCommentPattern) { - const sourceCode = context.getSourceCode(); - const comment = lodash.last(sourceCode.getCommentsBefore(node)); - - return Boolean(comment && fallthroughCommentPattern.test(comment.value)); -} - -/** - * Checks whether or not a given code path segment is reachable. - * @param {CodePathSegment} segment - A CodePathSegment to check. - * @returns {boolean} `true` if the segment is reachable. - */ -function isReachable(segment) { - return segment.reachable; -} - -/** - * Checks whether a node and a token are separated by blank lines - * @param {ASTNode} node - The node to check - * @param {Token} token - The token to compare against - * @returns {boolean} `true` if there are blank lines between node and token - */ -function hasBlankLinesBetween(node, token) { - return token.loc.start.line > node.loc.end.line + 1; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow fallthrough of `case` statements", - category: "Best Practices", - recommended: true, - url: "https://eslint.org/docs/rules/no-fallthrough" - }, - - schema: [ - { - type: "object", - properties: { - commentPattern: { - type: "string", - default: "" - } - }, - additionalProperties: false - } - ], - messages: { - case: "Expected a 'break' statement before 'case'.", - default: "Expected a 'break' statement before 'default'." - } - }, - - create(context) { - const options = context.options[0] || {}; - let currentCodePath = null; - const sourceCode = context.getSourceCode(); - - /* - * We need to use leading comments of the next SwitchCase node because - * trailing comments is wrong if semicolons are omitted. - */ - let fallthroughCase = null; - let fallthroughCommentPattern = null; - - if (options.commentPattern) { - fallthroughCommentPattern = new RegExp(options.commentPattern); - } else { - fallthroughCommentPattern = DEFAULT_FALLTHROUGH_COMMENT; - } - - return { - onCodePathStart(codePath) { - currentCodePath = codePath; - }, - onCodePathEnd() { - currentCodePath = currentCodePath.upper; - }, - - SwitchCase(node) { - - /* - * Checks whether or not there is a fallthrough comment. - * And reports the previous fallthrough node if that does not exist. - */ - if (fallthroughCase && !hasFallthroughComment(node, context, fallthroughCommentPattern)) { - context.report({ - messageId: node.test ? "case" : "default", - node - }); - } - fallthroughCase = null; - }, - - "SwitchCase:exit"(node) { - const nextToken = sourceCode.getTokenAfter(node); - - /* - * `reachable` meant fall through because statements preceded by - * `break`, `return`, or `throw` are unreachable. - * And allows empty cases and the last case. - */ - if (currentCodePath.currentSegments.some(isReachable) && - (node.consequent.length > 0 || hasBlankLinesBetween(node, nextToken)) && - lodash.last(node.parent.cases) !== node) { - fallthroughCase = node; - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-floating-decimal.js b/tools/node_modules/eslint/lib/rules/no-floating-decimal.js deleted file mode 100644 index de5a521525fdaa..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-floating-decimal.js +++ /dev/null @@ -1,70 +0,0 @@ -/** - * @fileoverview Rule to flag use of a leading/trailing decimal point in a numeric literal - * @author James Allardice - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow leading or trailing decimal points in numeric literals", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-floating-decimal" - }, - - schema: [], - fixable: "code", - messages: { - leading: "A leading decimal point can be confused with a dot.", - trailing: "A trailing decimal point can be confused with a dot." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - return { - Literal(node) { - - if (typeof node.value === "number") { - if (node.raw.startsWith(".")) { - context.report({ - node, - messageId: "leading", - fix(fixer) { - const tokenBefore = sourceCode.getTokenBefore(node); - const needsSpaceBefore = tokenBefore && - tokenBefore.range[1] === node.range[0] && - !astUtils.canTokensBeAdjacent(tokenBefore, `0${node.raw}`); - - return fixer.insertTextBefore(node, needsSpaceBefore ? " 0" : "0"); - } - }); - } - if (node.raw.indexOf(".") === node.raw.length - 1) { - context.report({ - node, - messageId: "trailing", - fix: fixer => fixer.insertTextAfter(node, "0") - }); - } - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-func-assign.js b/tools/node_modules/eslint/lib/rules/no-func-assign.js deleted file mode 100644 index ae96ab01f43057..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-func-assign.js +++ /dev/null @@ -1,66 +0,0 @@ -/** - * @fileoverview Rule to flag use of function declaration identifiers as variables. - * @author Ian Christian Myers - */ - -"use strict"; - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow reassigning `function` declarations", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-func-assign" - }, - - schema: [] - }, - - create(context) { - - /** - * Reports a reference if is non initializer and writable. - * @param {References} references - Collection of reference to check. - * @returns {void} - */ - function checkReference(references) { - astUtils.getModifyingReferences(references).forEach(reference => { - context.report({ node: reference.identifier, message: "'{{name}}' is a function.", data: { name: reference.identifier.name } }); - }); - } - - /** - * Finds and reports references that are non initializer and writable. - * @param {Variable} variable - A variable to check. - * @returns {void} - */ - function checkVariable(variable) { - if (variable.defs[0].type === "FunctionName") { - checkReference(variable.references); - } - } - - /** - * Checks parameters of a given function node. - * @param {ASTNode} node - A function node to check. - * @returns {void} - */ - function checkForFunction(node) { - context.getDeclaredVariables(node).forEach(checkVariable); - } - - return { - FunctionDeclaration: checkForFunction, - FunctionExpression: checkForFunction - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-global-assign.js b/tools/node_modules/eslint/lib/rules/no-global-assign.js deleted file mode 100644 index 73f36b25e4763e..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-global-assign.js +++ /dev/null @@ -1,88 +0,0 @@ -/** - * @fileoverview Rule to disallow assignments to native objects or read-only global variables - * @author Ilya Volodin - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow assignments to native objects or read-only global variables", - category: "Best Practices", - recommended: true, - url: "https://eslint.org/docs/rules/no-global-assign" - }, - - schema: [ - { - type: "object", - properties: { - exceptions: { - type: "array", - items: { type: "string" }, - uniqueItems: true - } - }, - additionalProperties: false - } - ] - }, - - create(context) { - const config = context.options[0]; - const exceptions = (config && config.exceptions) || []; - - /** - * Reports write references. - * @param {Reference} reference - A reference to check. - * @param {int} index - The index of the reference in the references. - * @param {Reference[]} references - The array that the reference belongs to. - * @returns {void} - */ - function checkReference(reference, index, references) { - const identifier = reference.identifier; - - if (reference.init === false && - reference.isWrite() && - - /* - * Destructuring assignments can have multiple default value, - * so possibly there are multiple writeable references for the same identifier. - */ - (index === 0 || references[index - 1].identifier !== identifier) - ) { - context.report({ - node: identifier, - message: "Read-only global '{{name}}' should not be modified.", - data: identifier - }); - } - } - - /** - * Reports write references if a given variable is read-only builtin. - * @param {Variable} variable - A variable to check. - * @returns {void} - */ - function checkVariable(variable) { - if (variable.writeable === false && exceptions.indexOf(variable.name) === -1) { - variable.references.forEach(checkReference); - } - } - - return { - Program() { - const globalScope = context.getScope(); - - globalScope.variables.forEach(checkVariable); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-implicit-coercion.js b/tools/node_modules/eslint/lib/rules/no-implicit-coercion.js deleted file mode 100644 index d54c578646d555..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-implicit-coercion.js +++ /dev/null @@ -1,296 +0,0 @@ -/** - * @fileoverview A rule to disallow the type conversions with shorter notations. - * @author Toru Nagashima - */ - -"use strict"; - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const INDEX_OF_PATTERN = /^(?:i|lastI)ndexOf$/; -const ALLOWABLE_OPERATORS = ["~", "!!", "+", "*"]; - -/** - * Parses and normalizes an option object. - * @param {Object} options - An option object to parse. - * @returns {Object} The parsed and normalized option object. - */ -function parseOptions(options) { - return { - boolean: "boolean" in options ? options.boolean : true, - number: "number" in options ? options.number : true, - string: "string" in options ? options.string : true, - allow: options.allow || [] - }; -} - -/** - * Checks whether or not a node is a double logical nigating. - * @param {ASTNode} node - An UnaryExpression node to check. - * @returns {boolean} Whether or not the node is a double logical nigating. - */ -function isDoubleLogicalNegating(node) { - return ( - node.operator === "!" && - node.argument.type === "UnaryExpression" && - node.argument.operator === "!" - ); -} - -/** - * Checks whether or not a node is a binary negating of `.indexOf()` method calling. - * @param {ASTNode} node - An UnaryExpression node to check. - * @returns {boolean} Whether or not the node is a binary negating of `.indexOf()` method calling. - */ -function isBinaryNegatingOfIndexOf(node) { - return ( - node.operator === "~" && - node.argument.type === "CallExpression" && - node.argument.callee.type === "MemberExpression" && - node.argument.callee.property.type === "Identifier" && - INDEX_OF_PATTERN.test(node.argument.callee.property.name) - ); -} - -/** - * Checks whether or not a node is a multiplying by one. - * @param {BinaryExpression} node - A BinaryExpression node to check. - * @returns {boolean} Whether or not the node is a multiplying by one. - */ -function isMultiplyByOne(node) { - return node.operator === "*" && ( - node.left.type === "Literal" && node.left.value === 1 || - node.right.type === "Literal" && node.right.value === 1 - ); -} - -/** - * Checks whether the result of a node is numeric or not - * @param {ASTNode} node The node to test - * @returns {boolean} true if the node is a number literal or a `Number()`, `parseInt` or `parseFloat` call - */ -function isNumeric(node) { - return ( - node.type === "Literal" && typeof node.value === "number" || - node.type === "CallExpression" && ( - node.callee.name === "Number" || - node.callee.name === "parseInt" || - node.callee.name === "parseFloat" - ) - ); -} - -/** - * Returns the first non-numeric operand in a BinaryExpression. Designed to be - * used from bottom to up since it walks up the BinaryExpression trees using - * node.parent to find the result. - * @param {BinaryExpression} node The BinaryExpression node to be walked up on - * @returns {ASTNode|null} The first non-numeric item in the BinaryExpression tree or null - */ -function getNonNumericOperand(node) { - const left = node.left, - right = node.right; - - if (right.type !== "BinaryExpression" && !isNumeric(right)) { - return right; - } - - if (left.type !== "BinaryExpression" && !isNumeric(left)) { - return left; - } - - return null; -} - -/** - * Checks whether a node is an empty string literal or not. - * @param {ASTNode} node The node to check. - * @returns {boolean} Whether or not the passed in node is an - * empty string literal or not. - */ -function isEmptyString(node) { - return astUtils.isStringLiteral(node) && (node.value === "" || (node.type === "TemplateLiteral" && node.quasis.length === 1 && node.quasis[0].value.cooked === "")); -} - -/** - * Checks whether or not a node is a concatenating with an empty string. - * @param {ASTNode} node - A BinaryExpression node to check. - * @returns {boolean} Whether or not the node is a concatenating with an empty string. - */ -function isConcatWithEmptyString(node) { - return node.operator === "+" && ( - (isEmptyString(node.left) && !astUtils.isStringLiteral(node.right)) || - (isEmptyString(node.right) && !astUtils.isStringLiteral(node.left)) - ); -} - -/** - * Checks whether or not a node is appended with an empty string. - * @param {ASTNode} node - An AssignmentExpression node to check. - * @returns {boolean} Whether or not the node is appended with an empty string. - */ -function isAppendEmptyString(node) { - return node.operator === "+=" && isEmptyString(node.right); -} - -/** - * Returns the operand that is not an empty string from a flagged BinaryExpression. - * @param {ASTNode} node - The flagged BinaryExpression node to check. - * @returns {ASTNode} The operand that is not an empty string from a flagged BinaryExpression. - */ -function getNonEmptyOperand(node) { - return isEmptyString(node.left) ? node.right : node.left; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow shorthand type conversions", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-implicit-coercion" - }, - - fixable: "code", - - schema: [{ - type: "object", - properties: { - boolean: { - type: "boolean", - default: true - }, - number: { - type: "boolean", - default: true - }, - string: { - type: "boolean", - default: true - }, - allow: { - type: "array", - items: { - enum: ALLOWABLE_OPERATORS - }, - uniqueItems: true - } - }, - additionalProperties: false - }] - }, - - create(context) { - const options = parseOptions(context.options[0] || {}); - const sourceCode = context.getSourceCode(); - - /** - * Reports an error and autofixes the node - * @param {ASTNode} node - An ast node to report the error on. - * @param {string} recommendation - The recommended code for the issue - * @param {bool} shouldFix - Whether this report should fix the node - * @returns {void} - */ - function report(node, recommendation, shouldFix) { - context.report({ - node, - message: "use `{{recommendation}}` instead.", - data: { - recommendation - }, - fix(fixer) { - if (!shouldFix) { - return null; - } - - const tokenBefore = sourceCode.getTokenBefore(node); - - if ( - tokenBefore && - tokenBefore.range[1] === node.range[0] && - !astUtils.canTokensBeAdjacent(tokenBefore, recommendation) - ) { - return fixer.replaceText(node, ` ${recommendation}`); - } - return fixer.replaceText(node, recommendation); - } - }); - } - - return { - UnaryExpression(node) { - let operatorAllowed; - - // !!foo - operatorAllowed = options.allow.indexOf("!!") >= 0; - if (!operatorAllowed && options.boolean && isDoubleLogicalNegating(node)) { - const recommendation = `Boolean(${sourceCode.getText(node.argument.argument)})`; - - report(node, recommendation, true); - } - - // ~foo.indexOf(bar) - operatorAllowed = options.allow.indexOf("~") >= 0; - if (!operatorAllowed && options.boolean && isBinaryNegatingOfIndexOf(node)) { - const recommendation = `${sourceCode.getText(node.argument)} !== -1`; - - report(node, recommendation, false); - } - - // +foo - operatorAllowed = options.allow.indexOf("+") >= 0; - if (!operatorAllowed && options.number && node.operator === "+" && !isNumeric(node.argument)) { - const recommendation = `Number(${sourceCode.getText(node.argument)})`; - - report(node, recommendation, true); - } - }, - - // Use `:exit` to prevent double reporting - "BinaryExpression:exit"(node) { - let operatorAllowed; - - // 1 * foo - operatorAllowed = options.allow.indexOf("*") >= 0; - const nonNumericOperand = !operatorAllowed && options.number && isMultiplyByOne(node) && getNonNumericOperand(node); - - if (nonNumericOperand) { - const recommendation = `Number(${sourceCode.getText(nonNumericOperand)})`; - - report(node, recommendation, true); - } - - // "" + foo - operatorAllowed = options.allow.indexOf("+") >= 0; - if (!operatorAllowed && options.string && isConcatWithEmptyString(node)) { - const recommendation = `String(${sourceCode.getText(getNonEmptyOperand(node))})`; - - report(node, recommendation, true); - } - }, - - AssignmentExpression(node) { - - // foo += "" - const operatorAllowed = options.allow.indexOf("+") >= 0; - - if (!operatorAllowed && options.string && isAppendEmptyString(node)) { - const code = sourceCode.getText(getNonEmptyOperand(node)); - const recommendation = `${code} = String(${code})`; - - report(node, recommendation, true); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-implicit-globals.js b/tools/node_modules/eslint/lib/rules/no-implicit-globals.js deleted file mode 100644 index 2eea2b28463250..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-implicit-globals.js +++ /dev/null @@ -1,58 +0,0 @@ -/** - * @fileoverview Rule to check for implicit global variables and functions. - * @author Joshua Peek - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow variable and `function` declarations in the global scope", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-implicit-globals" - }, - - schema: [] - }, - - create(context) { - return { - Program() { - const scope = context.getScope(); - - scope.variables.forEach(variable => { - if (variable.writeable) { - return; - } - - variable.defs.forEach(def => { - if (def.type === "FunctionName" || (def.type === "Variable" && def.parent.kind === "var")) { - context.report({ node: def.node, message: "Implicit global variable, assign as global property instead." }); - } - }); - }); - - scope.implicit.variables.forEach(variable => { - const scopeVariable = scope.set.get(variable.name); - - if (scopeVariable && scopeVariable.writeable) { - return; - } - - variable.defs.forEach(def => { - context.report({ node: def.node, message: "Implicit global variable, assign as global property instead." }); - }); - }); - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-implied-eval.js b/tools/node_modules/eslint/lib/rules/no-implied-eval.js deleted file mode 100644 index afa24ab8efda75..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-implied-eval.js +++ /dev/null @@ -1,164 +0,0 @@ -/** - * @fileoverview Rule to flag use of implied eval via setTimeout and setInterval - * @author James Allardice - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow the use of `eval()`-like methods", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-implied-eval" - }, - - schema: [] - }, - - create(context) { - const CALLEE_RE = /^(setTimeout|setInterval|execScript)$/; - - /* - * Figures out if we should inspect a given binary expression. Is a stack - * of stacks, where the first element in each substack is a CallExpression. - */ - const impliedEvalAncestorsStack = []; - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Get the last element of an array, without modifying arr, like pop(), but non-destructive. - * @param {Array} arr What to inspect - * @returns {*} The last element of arr - * @private - */ - function last(arr) { - return arr ? arr[arr.length - 1] : null; - } - - /** - * Checks if the given MemberExpression node is a potentially implied eval identifier on window. - * @param {ASTNode} node The MemberExpression node to check. - * @returns {boolean} Whether or not the given node is potentially an implied eval. - * @private - */ - function isImpliedEvalMemberExpression(node) { - const object = node.object, - property = node.property, - hasImpliedEvalName = CALLEE_RE.test(property.name) || CALLEE_RE.test(property.value); - - return object.name === "window" && hasImpliedEvalName; - } - - /** - * Determines if a node represents a call to a potentially implied eval. - * - * This checks the callee name and that there's an argument, but not the type of the argument. - * - * @param {ASTNode} node The CallExpression to check. - * @returns {boolean} True if the node matches, false if not. - * @private - */ - function isImpliedEvalCallExpression(node) { - const isMemberExpression = (node.callee.type === "MemberExpression"), - isIdentifier = (node.callee.type === "Identifier"), - isImpliedEvalCallee = - (isIdentifier && CALLEE_RE.test(node.callee.name)) || - (isMemberExpression && isImpliedEvalMemberExpression(node.callee)); - - return isImpliedEvalCallee && node.arguments.length; - } - - /** - * Checks that the parent is a direct descendent of an potential implied eval CallExpression, and if the parent is a CallExpression, that we're the first argument. - * @param {ASTNode} node The node to inspect the parent of. - * @returns {boolean} Was the parent a direct descendent, and is the child therefore potentially part of a dangerous argument? - * @private - */ - function hasImpliedEvalParent(node) { - - // make sure our parent is marked - return node.parent === last(last(impliedEvalAncestorsStack)) && - - // if our parent is a CallExpression, make sure we're the first argument - (node.parent.type !== "CallExpression" || node === node.parent.arguments[0]); - } - - /** - * Checks if our parent is marked as part of an implied eval argument. If - * so, collapses the top of impliedEvalAncestorsStack and reports on the - * original CallExpression. - * @param {ASTNode} node The CallExpression to check. - * @returns {boolean} True if the node matches, false if not. - * @private - */ - function checkString(node) { - if (hasImpliedEvalParent(node)) { - - // remove the entire substack, to avoid duplicate reports - const substack = impliedEvalAncestorsStack.pop(); - - context.report({ node: substack[0], message: "Implied eval. Consider passing a function instead of a string." }); - } - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - CallExpression(node) { - if (isImpliedEvalCallExpression(node)) { - - // call expressions create a new substack - impliedEvalAncestorsStack.push([node]); - } - }, - - "CallExpression:exit"(node) { - if (node === last(last(impliedEvalAncestorsStack))) { - - /* - * Destroys the entire sub-stack, rather than just using - * last(impliedEvalAncestorsStack).pop(), as a CallExpression is - * always the bottom of a impliedEvalAncestorsStack substack. - */ - impliedEvalAncestorsStack.pop(); - } - }, - - BinaryExpression(node) { - if (node.operator === "+" && hasImpliedEvalParent(node)) { - last(impliedEvalAncestorsStack).push(node); - } - }, - - "BinaryExpression:exit"(node) { - if (node === last(last(impliedEvalAncestorsStack))) { - last(impliedEvalAncestorsStack).pop(); - } - }, - - Literal(node) { - if (typeof node.value === "string") { - checkString(node); - } - }, - - TemplateLiteral(node) { - checkString(node); - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-inline-comments.js b/tools/node_modules/eslint/lib/rules/no-inline-comments.js deleted file mode 100644 index c282d16e75411a..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-inline-comments.js +++ /dev/null @@ -1,68 +0,0 @@ -/** - * @fileoverview Enforces or disallows inline comments. - * @author Greg Cochard - */ -"use strict"; - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow inline comments after code", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/no-inline-comments" - }, - - schema: [] - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - /** - * Will check that comments are not on lines starting with or ending with code - * @param {ASTNode} node The comment node to check - * @private - * @returns {void} - */ - function testCodeAroundComment(node) { - - // Get the whole line and cut it off at the start of the comment - const startLine = String(sourceCode.lines[node.loc.start.line - 1]); - const endLine = String(sourceCode.lines[node.loc.end.line - 1]); - - const preamble = startLine.slice(0, node.loc.start.column).trim(); - - // Also check after the comment - const postamble = endLine.slice(node.loc.end.column).trim(); - - // Check that this comment isn't an ESLint directive - const isDirective = astUtils.isDirectiveComment(node); - - // Should be empty if there was only whitespace around the comment - if (!isDirective && (preamble || postamble)) { - context.report({ node, message: "Unexpected comment inline with code." }); - } - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - Program() { - const comments = sourceCode.getAllComments(); - - comments.filter(token => token.type !== "Shebang").forEach(testCodeAroundComment); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-inner-declarations.js b/tools/node_modules/eslint/lib/rules/no-inner-declarations.js deleted file mode 100644 index 60508d3e864eda..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-inner-declarations.js +++ /dev/null @@ -1,92 +0,0 @@ -/** - * @fileoverview Rule to enforce declarations in program or function body root. - * @author Brandon Mills - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow variable or `function` declarations in nested blocks", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-inner-declarations" - }, - - schema: [ - { - enum: ["functions", "both"] - } - ] - }, - - create(context) { - - /** - * Find the nearest Program or Function ancestor node. - * @returns {Object} Ancestor's type and distance from node. - */ - function nearestBody() { - const ancestors = context.getAncestors(); - let ancestor = ancestors.pop(), - generation = 1; - - while (ancestor && ["Program", "FunctionDeclaration", - "FunctionExpression", "ArrowFunctionExpression" - ].indexOf(ancestor.type) < 0) { - generation += 1; - ancestor = ancestors.pop(); - } - - return { - - // Type of containing ancestor - type: ancestor.type, - - // Separation between ancestor and node - distance: generation - }; - } - - /** - * Ensure that a given node is at a program or function body's root. - * @param {ASTNode} node Declaration node to check. - * @returns {void} - */ - function check(node) { - const body = nearestBody(), - valid = ((body.type === "Program" && body.distance === 1) || - body.distance === 2); - - if (!valid) { - context.report({ - node, - message: "Move {{type}} declaration to {{body}} root.", - data: { - type: (node.type === "FunctionDeclaration" ? "function" : "variable"), - body: (body.type === "Program" ? "program" : "function body") - } - }); - } - } - - return { - - FunctionDeclaration: check, - VariableDeclaration(node) { - if (context.options[0] === "both" && node.kind === "var") { - check(node); - } - } - - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-invalid-regexp.js b/tools/node_modules/eslint/lib/rules/no-invalid-regexp.js deleted file mode 100644 index 74659001fdb9ce..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-invalid-regexp.js +++ /dev/null @@ -1,126 +0,0 @@ -/** - * @fileoverview Validate strings passed to the RegExp constructor - * @author Michael Ficarra - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const RegExpValidator = require("regexpp").RegExpValidator; -const validator = new RegExpValidator({ ecmaVersion: 2018 }); -const validFlags = /[gimuys]/g; -const undefined1 = void 0; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow invalid regular expression strings in `RegExp` constructors", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-invalid-regexp" - }, - - schema: [{ - type: "object", - properties: { - allowConstructorFlags: { - type: "array", - items: { - type: "string" - } - } - }, - additionalProperties: false - }] - }, - - create(context) { - - const options = context.options[0]; - let allowedFlags = null; - - if (options && options.allowConstructorFlags) { - const temp = options.allowConstructorFlags.join("").replace(validFlags, ""); - - if (temp) { - allowedFlags = new RegExp(`[${temp}]`, "gi"); - } - } - - /** - * Check if node is a string - * @param {ASTNode} node node to evaluate - * @returns {boolean} True if its a string - * @private - */ - function isString(node) { - return node && node.type === "Literal" && typeof node.value === "string"; - } - - /** - * Check syntax error in a given pattern. - * @param {string} pattern The RegExp pattern to validate. - * @param {boolean} uFlag The Unicode flag. - * @returns {string|null} The syntax error. - */ - function validateRegExpPattern(pattern, uFlag) { - try { - validator.validatePattern(pattern, undefined1, undefined1, uFlag); - return null; - } catch (err) { - return err.message; - } - } - - /** - * Check syntax error in a given flags. - * @param {string} flags The RegExp flags to validate. - * @returns {string|null} The syntax error. - */ - function validateRegExpFlags(flags) { - try { - validator.validateFlags(flags); - return null; - } catch (err) { - return `Invalid flags supplied to RegExp constructor '${flags}'`; - } - } - - return { - "CallExpression, NewExpression"(node) { - if (node.callee.type !== "Identifier" || node.callee.name !== "RegExp" || !isString(node.arguments[0])) { - return; - } - const pattern = node.arguments[0].value; - let flags = isString(node.arguments[1]) ? node.arguments[1].value : ""; - - if (allowedFlags) { - flags = flags.replace(allowedFlags, ""); - } - - // If flags are unknown, check both are errored or not. - const message = validateRegExpFlags(flags) || ( - flags - ? validateRegExpPattern(pattern, flags.indexOf("u") !== -1) - : validateRegExpPattern(pattern, true) && validateRegExpPattern(pattern, false) - ); - - if (message) { - context.report({ - node, - message: "{{message}}.", - data: { message } - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-invalid-this.js b/tools/node_modules/eslint/lib/rules/no-invalid-this.js deleted file mode 100644 index e9be4445260bdb..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-invalid-this.js +++ /dev/null @@ -1,126 +0,0 @@ -/** - * @fileoverview A rule to disallow `this` keywords outside of classes or class-like objects. - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow `this` keywords outside of classes or class-like objects", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-invalid-this" - }, - - schema: [] - }, - - create(context) { - const stack = [], - sourceCode = context.getSourceCode(); - - /** - * Gets the current checking context. - * - * The return value has a flag that whether or not `this` keyword is valid. - * The flag is initialized when got at the first time. - * - * @returns {{valid: boolean}} - * an object which has a flag that whether or not `this` keyword is valid. - */ - stack.getCurrent = function() { - const current = this[this.length - 1]; - - if (!current.init) { - current.init = true; - current.valid = !astUtils.isDefaultThisBinding( - current.node, - sourceCode - ); - } - return current; - }; - - /** - * Pushs new checking context into the stack. - * - * The checking context is not initialized yet. - * Because most functions don't have `this` keyword. - * When `this` keyword was found, the checking context is initialized. - * - * @param {ASTNode} node - A function node that was entered. - * @returns {void} - */ - function enterFunction(node) { - - // `this` can be invalid only under strict mode. - stack.push({ - init: !context.getScope().isStrict, - node, - valid: true - }); - } - - /** - * Pops the current checking context from the stack. - * @returns {void} - */ - function exitFunction() { - stack.pop(); - } - - return { - - /* - * `this` is invalid only under strict mode. - * Modules is always strict mode. - */ - Program(node) { - const scope = context.getScope(), - features = context.parserOptions.ecmaFeatures || {}; - - stack.push({ - init: true, - node, - valid: !( - scope.isStrict || - node.sourceType === "module" || - (features.globalReturn && scope.childScopes[0].isStrict) - ) - }); - }, - - "Program:exit"() { - stack.pop(); - }, - - FunctionDeclaration: enterFunction, - "FunctionDeclaration:exit": exitFunction, - FunctionExpression: enterFunction, - "FunctionExpression:exit": exitFunction, - - // Reports if `this` of the current context is invalid. - ThisExpression(node) { - const current = stack.getCurrent(); - - if (current && !current.valid) { - context.report({ node, message: "Unexpected 'this'." }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-irregular-whitespace.js b/tools/node_modules/eslint/lib/rules/no-irregular-whitespace.js deleted file mode 100644 index ddbfd1c91cc88d..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-irregular-whitespace.js +++ /dev/null @@ -1,239 +0,0 @@ -/** - * @fileoverview Rule to disalow whitespace that is not a tab or space, whitespace inside strings and comments are allowed - * @author Jonathan Kingston - * @author Christophe Porteneuve - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Constants -//------------------------------------------------------------------------------ - -const ALL_IRREGULARS = /[\f\v\u0085\ufeff\u00a0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u202f\u205f\u3000\u2028\u2029]/; -const IRREGULAR_WHITESPACE = /[\f\v\u0085\ufeff\u00a0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u202f\u205f\u3000]+/mg; -const IRREGULAR_LINE_TERMINATORS = /[\u2028\u2029]/mg; -const LINE_BREAK = astUtils.createGlobalLinebreakMatcher(); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow irregular whitespace", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-irregular-whitespace" - }, - - schema: [ - { - type: "object", - properties: { - skipComments: { - type: "boolean", - default: false - }, - skipStrings: { - type: "boolean", - default: true - }, - skipTemplates: { - type: "boolean", - default: false - }, - skipRegExps: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ] - }, - - create(context) { - - // Module store of errors that we have found - let errors = []; - - // Lookup the `skipComments` option, which defaults to `false`. - const options = context.options[0] || {}; - const skipComments = !!options.skipComments; - const skipStrings = options.skipStrings !== false; - const skipRegExps = !!options.skipRegExps; - const skipTemplates = !!options.skipTemplates; - - const sourceCode = context.getSourceCode(); - const commentNodes = sourceCode.getAllComments(); - - /** - * Removes errors that occur inside a string node - * @param {ASTNode} node to check for matching errors. - * @returns {void} - * @private - */ - function removeWhitespaceError(node) { - const locStart = node.loc.start; - const locEnd = node.loc.end; - - errors = errors.filter(({ loc: errorLoc }) => { - if (errorLoc.line >= locStart.line && errorLoc.line <= locEnd.line) { - if (errorLoc.column >= locStart.column && (errorLoc.column <= locEnd.column || errorLoc.line < locEnd.line)) { - return false; - } - } - return true; - }); - } - - /** - * Checks identifier or literal nodes for errors that we are choosing to ignore and calls the relevant methods to remove the errors - * @param {ASTNode} node to check for matching errors. - * @returns {void} - * @private - */ - function removeInvalidNodeErrorsInIdentifierOrLiteral(node) { - const shouldCheckStrings = skipStrings && (typeof node.value === "string"); - const shouldCheckRegExps = skipRegExps && Boolean(node.regex); - - if (shouldCheckStrings || shouldCheckRegExps) { - - // If we have irregular characters remove them from the errors list - if (ALL_IRREGULARS.test(node.raw)) { - removeWhitespaceError(node); - } - } - } - - /** - * Checks template string literal nodes for errors that we are choosing to ignore and calls the relevant methods to remove the errors - * @param {ASTNode} node to check for matching errors. - * @returns {void} - * @private - */ - function removeInvalidNodeErrorsInTemplateLiteral(node) { - if (typeof node.value.raw === "string") { - if (ALL_IRREGULARS.test(node.value.raw)) { - removeWhitespaceError(node); - } - } - } - - /** - * Checks comment nodes for errors that we are choosing to ignore and calls the relevant methods to remove the errors - * @param {ASTNode} node to check for matching errors. - * @returns {void} - * @private - */ - function removeInvalidNodeErrorsInComment(node) { - if (ALL_IRREGULARS.test(node.value)) { - removeWhitespaceError(node); - } - } - - /** - * Checks the program source for irregular whitespace - * @param {ASTNode} node The program node - * @returns {void} - * @private - */ - function checkForIrregularWhitespace(node) { - const sourceLines = sourceCode.lines; - - sourceLines.forEach((sourceLine, lineIndex) => { - const lineNumber = lineIndex + 1; - let match; - - while ((match = IRREGULAR_WHITESPACE.exec(sourceLine)) !== null) { - const location = { - line: lineNumber, - column: match.index - }; - - errors.push({ node, message: "Irregular whitespace not allowed.", loc: location }); - } - }); - } - - /** - * Checks the program source for irregular line terminators - * @param {ASTNode} node The program node - * @returns {void} - * @private - */ - function checkForIrregularLineTerminators(node) { - const source = sourceCode.getText(), - sourceLines = sourceCode.lines, - linebreaks = source.match(LINE_BREAK); - let lastLineIndex = -1, - match; - - while ((match = IRREGULAR_LINE_TERMINATORS.exec(source)) !== null) { - const lineIndex = linebreaks.indexOf(match[0], lastLineIndex + 1) || 0; - const location = { - line: lineIndex + 1, - column: sourceLines[lineIndex].length - }; - - errors.push({ node, message: "Irregular whitespace not allowed.", loc: location }); - lastLineIndex = lineIndex; - } - } - - /** - * A no-op function to act as placeholder for comment accumulation when the `skipComments` option is `false`. - * @returns {void} - * @private - */ - function noop() {} - - const nodes = {}; - - if (ALL_IRREGULARS.test(sourceCode.getText())) { - nodes.Program = function(node) { - - /* - * As we can easily fire warnings for all white space issues with - * all the source its simpler to fire them here. - * This means we can check all the application code without having - * to worry about issues caused in the parser tokens. - * When writing this code also evaluating per node was missing out - * connecting tokens in some cases. - * We can later filter the errors when they are found to be not an - * issue in nodes we don't care about. - */ - checkForIrregularWhitespace(node); - checkForIrregularLineTerminators(node); - }; - - nodes.Identifier = removeInvalidNodeErrorsInIdentifierOrLiteral; - nodes.Literal = removeInvalidNodeErrorsInIdentifierOrLiteral; - nodes.TemplateElement = skipTemplates ? removeInvalidNodeErrorsInTemplateLiteral : noop; - nodes["Program:exit"] = function() { - if (skipComments) { - - // First strip errors occurring in comment nodes. - commentNodes.forEach(removeInvalidNodeErrorsInComment); - } - - // If we have any errors remaining report on them - errors.forEach(error => context.report(error)); - }; - } else { - nodes.Program = noop; - } - - return nodes; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-iterator.js b/tools/node_modules/eslint/lib/rules/no-iterator.js deleted file mode 100644 index 82319a3fb1dfb6..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-iterator.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * @fileoverview Rule to flag usage of __iterator__ property - * @author Ian Christian Myers - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow the use of the `__iterator__` property", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-iterator" - }, - - schema: [] - }, - - create(context) { - - return { - - MemberExpression(node) { - - if (node.property && - (node.property.type === "Identifier" && node.property.name === "__iterator__" && !node.computed) || - (node.property.type === "Literal" && node.property.value === "__iterator__")) { - context.report({ node, message: "Reserved name '__iterator__'." }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-label-var.js b/tools/node_modules/eslint/lib/rules/no-label-var.js deleted file mode 100644 index fdba2defc350c6..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-label-var.js +++ /dev/null @@ -1,72 +0,0 @@ -/** - * @fileoverview Rule to flag labels that are the same as an identifier - * @author Ian Christian Myers - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow labels that share a name with a variable", - category: "Variables", - recommended: false, - url: "https://eslint.org/docs/rules/no-label-var" - }, - - schema: [] - }, - - create(context) { - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Check if the identifier is present inside current scope - * @param {Object} scope current scope - * @param {string} name To evaluate - * @returns {boolean} True if its present - * @private - */ - function findIdentifier(scope, name) { - return astUtils.getVariableByName(scope, name) !== null; - } - - //-------------------------------------------------------------------------- - // Public API - //-------------------------------------------------------------------------- - - return { - - LabeledStatement(node) { - - // Fetch the innermost scope. - const scope = context.getScope(); - - /* - * Recursively find the identifier walking up the scope, starting - * with the innermost scope. - */ - if (findIdentifier(scope, node.label.name)) { - context.report({ node, message: "Found identifier with same name as label." }); - } - } - - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-labels.js b/tools/node_modules/eslint/lib/rules/no-labels.js deleted file mode 100644 index 29580bd236bbd8..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-labels.js +++ /dev/null @@ -1,146 +0,0 @@ -/** - * @fileoverview Disallow Labeled Statements - * @author Nicholas C. Zakas - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow labeled statements", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-labels" - }, - - schema: [ - { - type: "object", - properties: { - allowLoop: { - type: "boolean", - default: false - }, - allowSwitch: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ] - }, - - create(context) { - const options = context.options[0]; - const allowLoop = options && options.allowLoop; - const allowSwitch = options && options.allowSwitch; - let scopeInfo = null; - - /** - * Gets the kind of a given node. - * - * @param {ASTNode} node - A node to get. - * @returns {string} The kind of the node. - */ - function getBodyKind(node) { - if (astUtils.isLoop(node)) { - return "loop"; - } - if (node.type === "SwitchStatement") { - return "switch"; - } - return "other"; - } - - /** - * Checks whether the label of a given kind is allowed or not. - * - * @param {string} kind - A kind to check. - * @returns {boolean} `true` if the kind is allowed. - */ - function isAllowed(kind) { - switch (kind) { - case "loop": return allowLoop; - case "switch": return allowSwitch; - default: return false; - } - } - - /** - * Checks whether a given name is a label of a loop or not. - * - * @param {string} label - A name of a label to check. - * @returns {boolean} `true` if the name is a label of a loop. - */ - function getKind(label) { - let info = scopeInfo; - - while (info) { - if (info.label === label) { - return info.kind; - } - info = info.upper; - } - - /* istanbul ignore next: syntax error */ - return "other"; - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - LabeledStatement(node) { - scopeInfo = { - label: node.label.name, - kind: getBodyKind(node.body), - upper: scopeInfo - }; - }, - - "LabeledStatement:exit"(node) { - if (!isAllowed(scopeInfo.kind)) { - context.report({ - node, - message: "Unexpected labeled statement." - }); - } - - scopeInfo = scopeInfo.upper; - }, - - BreakStatement(node) { - if (node.label && !isAllowed(getKind(node.label.name))) { - context.report({ - node, - message: "Unexpected label in break statement." - }); - } - }, - - ContinueStatement(node) { - if (node.label && !isAllowed(getKind(node.label.name))) { - context.report({ - node, - message: "Unexpected label in continue statement." - }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-lone-blocks.js b/tools/node_modules/eslint/lib/rules/no-lone-blocks.js deleted file mode 100644 index 6b51795863b379..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-lone-blocks.js +++ /dev/null @@ -1,115 +0,0 @@ -/** - * @fileoverview Rule to flag blocks with no reason to exist - * @author Brandon Mills - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow unnecessary nested blocks", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-lone-blocks" - }, - - schema: [] - }, - - create(context) { - - // A stack of lone blocks to be checked for block-level bindings - const loneBlocks = []; - let ruleDef; - - /** - * Reports a node as invalid. - * @param {ASTNode} node - The node to be reported. - * @returns {void} - */ - function report(node) { - const message = node.parent.type === "BlockStatement" ? "Nested block is redundant." : "Block is redundant."; - - context.report({ node, message }); - } - - /** - * Checks for any ocurrence of a BlockStatement in a place where lists of statements can appear - * @param {ASTNode} node The node to check - * @returns {boolean} True if the node is a lone block. - */ - function isLoneBlock(node) { - return node.parent.type === "BlockStatement" || - node.parent.type === "Program" || - - // Don't report blocks in switch cases if the block is the only statement of the case. - node.parent.type === "SwitchCase" && !(node.parent.consequent[0] === node && node.parent.consequent.length === 1); - } - - /** - * Checks the enclosing block of the current node for block-level bindings, - * and "marks it" as valid if any. - * @returns {void} - */ - function markLoneBlock() { - if (loneBlocks.length === 0) { - return; - } - - const block = context.getAncestors().pop(); - - if (loneBlocks[loneBlocks.length - 1] === block) { - loneBlocks.pop(); - } - } - - // Default rule definition: report all lone blocks - ruleDef = { - BlockStatement(node) { - if (isLoneBlock(node)) { - report(node); - } - } - }; - - // ES6: report blocks without block-level bindings - if (context.parserOptions.ecmaVersion >= 6) { - ruleDef = { - BlockStatement(node) { - if (isLoneBlock(node)) { - loneBlocks.push(node); - } - }, - "BlockStatement:exit"(node) { - if (loneBlocks.length > 0 && loneBlocks[loneBlocks.length - 1] === node) { - loneBlocks.pop(); - report(node); - } - } - }; - - ruleDef.VariableDeclaration = function(node) { - if (node.kind === "let" || node.kind === "const") { - markLoneBlock(); - } - }; - - ruleDef.FunctionDeclaration = function() { - if (context.getScope().isStrict) { - markLoneBlock(); - } - }; - - ruleDef.ClassDeclaration = markLoneBlock; - } - - return ruleDef; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-lonely-if.js b/tools/node_modules/eslint/lib/rules/no-lonely-if.js deleted file mode 100644 index 4bbb5399ff9519..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-lonely-if.js +++ /dev/null @@ -1,85 +0,0 @@ -/** - * @fileoverview Rule to disallow if as the only statmenet in an else block - * @author Brandon Mills - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow `if` statements as the only statement in `else` blocks", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/no-lonely-if" - }, - - schema: [], - fixable: "code" - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - return { - IfStatement(node) { - const ancestors = context.getAncestors(), - parent = ancestors.pop(), - grandparent = ancestors.pop(); - - if (parent && parent.type === "BlockStatement" && - parent.body.length === 1 && grandparent && - grandparent.type === "IfStatement" && - parent === grandparent.alternate) { - context.report({ - node, - message: "Unexpected if as the only statement in an else block.", - fix(fixer) { - const openingElseCurly = sourceCode.getFirstToken(parent); - const closingElseCurly = sourceCode.getLastToken(parent); - const elseKeyword = sourceCode.getTokenBefore(openingElseCurly); - const tokenAfterElseBlock = sourceCode.getTokenAfter(closingElseCurly); - const lastIfToken = sourceCode.getLastToken(node.consequent); - const sourceText = sourceCode.getText(); - - if (sourceText.slice(openingElseCurly.range[1], - node.range[0]).trim() || sourceText.slice(node.range[1], closingElseCurly.range[0]).trim()) { - - // Don't fix if there are any non-whitespace characters interfering (e.g. comments) - return null; - } - - if ( - node.consequent.type !== "BlockStatement" && lastIfToken.value !== ";" && tokenAfterElseBlock && - ( - node.consequent.loc.end.line === tokenAfterElseBlock.loc.start.line || - /^[([/+`-]/.test(tokenAfterElseBlock.value) || - lastIfToken.value === "++" || - lastIfToken.value === "--" - ) - ) { - - /* - * If the `if` statement has no block, and is not followed by a semicolon, make sure that fixing - * the issue would not change semantics due to ASI. If this would happen, don't do a fix. - */ - return null; - } - - return fixer.replaceTextRange( - [openingElseCurly.range[0], closingElseCurly.range[1]], - (elseKeyword.range[1] === openingElseCurly.range[0] ? " " : "") + sourceCode.getText(node) - ); - } - }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-loop-func.js b/tools/node_modules/eslint/lib/rules/no-loop-func.js deleted file mode 100644 index e6063806a5dec2..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-loop-func.js +++ /dev/null @@ -1,202 +0,0 @@ -/** - * @fileoverview Rule to flag creation of function inside a loop - * @author Ilya Volodin - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Gets the containing loop node of a specified node. - * - * We don't need to check nested functions, so this ignores those. - * `Scope.through` contains references of nested functions. - * - * @param {ASTNode} node - An AST node to get. - * @returns {ASTNode|null} The containing loop node of the specified node, or - * `null`. - */ -function getContainingLoopNode(node) { - for (let currentNode = node; currentNode.parent; currentNode = currentNode.parent) { - const parent = currentNode.parent; - - switch (parent.type) { - case "WhileStatement": - case "DoWhileStatement": - return parent; - - case "ForStatement": - - // `init` is outside of the loop. - if (parent.init !== currentNode) { - return parent; - } - break; - - case "ForInStatement": - case "ForOfStatement": - - // `right` is outside of the loop. - if (parent.right !== currentNode) { - return parent; - } - break; - - case "ArrowFunctionExpression": - case "FunctionExpression": - case "FunctionDeclaration": - - // We don't need to check nested functions. - return null; - - default: - break; - } - } - - return null; -} - -/** - * Gets the containing loop node of a given node. - * If the loop was nested, this returns the most outer loop. - * - * @param {ASTNode} node - A node to get. This is a loop node. - * @param {ASTNode|null} excludedNode - A node that the result node should not - * include. - * @returns {ASTNode} The most outer loop node. - */ -function getTopLoopNode(node, excludedNode) { - const border = excludedNode ? excludedNode.range[1] : 0; - let retv = node; - let containingLoopNode = node; - - while (containingLoopNode && containingLoopNode.range[0] >= border) { - retv = containingLoopNode; - containingLoopNode = getContainingLoopNode(containingLoopNode); - } - - return retv; -} - -/** - * Checks whether a given reference which refers to an upper scope's variable is - * safe or not. - * - * @param {ASTNode} loopNode - A containing loop node. - * @param {eslint-scope.Reference} reference - A reference to check. - * @returns {boolean} `true` if the reference is safe or not. - */ -function isSafe(loopNode, reference) { - const variable = reference.resolved; - const definition = variable && variable.defs[0]; - const declaration = definition && definition.parent; - const kind = (declaration && declaration.type === "VariableDeclaration") - ? declaration.kind - : ""; - - // Variables which are declared by `const` is safe. - if (kind === "const") { - return true; - } - - /* - * Variables which are declared by `let` in the loop is safe. - * It's a different instance from the next loop step's. - */ - if (kind === "let" && - declaration.range[0] > loopNode.range[0] && - declaration.range[1] < loopNode.range[1] - ) { - return true; - } - - /* - * WriteReferences which exist after this border are unsafe because those - * can modify the variable. - */ - const border = getTopLoopNode( - loopNode, - (kind === "let") ? declaration : null - ).range[0]; - - /** - * Checks whether a given reference is safe or not. - * The reference is every reference of the upper scope's variable we are - * looking now. - * - * It's safeafe if the reference matches one of the following condition. - * - is readonly. - * - doesn't exist inside a local function and after the border. - * - * @param {eslint-scope.Reference} upperRef - A reference to check. - * @returns {boolean} `true` if the reference is safe. - */ - function isSafeReference(upperRef) { - const id = upperRef.identifier; - - return ( - !upperRef.isWrite() || - variable.scope.variableScope === upperRef.from.variableScope && - id.range[0] < border - ); - } - - return Boolean(variable) && variable.references.every(isSafeReference); -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow `function` declarations and expressions inside loop statements", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-loop-func" - }, - - schema: [] - }, - - create(context) { - - /** - * Reports functions which match the following condition: - * - * - has a loop node in ancestors. - * - has any references which refers to an unsafe variable. - * - * @param {ASTNode} node The AST node to check. - * @returns {boolean} Whether or not the node is within a loop. - */ - function checkForLoops(node) { - const loopNode = getContainingLoopNode(node); - - if (!loopNode) { - return; - } - - const references = context.getScope().through; - - if (references.length > 0 && - !references.every(isSafe.bind(null, loopNode)) - ) { - context.report({ node, message: "Don't make functions within a loop." }); - } - } - - return { - ArrowFunctionExpression: checkForLoops, - FunctionExpression: checkForLoops, - FunctionDeclaration: checkForLoops - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-magic-numbers.js b/tools/node_modules/eslint/lib/rules/no-magic-numbers.js deleted file mode 100644 index 2c6ea61e283315..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-magic-numbers.js +++ /dev/null @@ -1,167 +0,0 @@ -/** - * @fileoverview Rule to flag statements that use magic numbers (adapted from https://github.com/danielstjules/buddy.js) - * @author Vincent Lemeunier - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow magic numbers", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-magic-numbers" - }, - - schema: [{ - type: "object", - properties: { - detectObjects: { - type: "boolean", - default: false - }, - enforceConst: { - type: "boolean", - default: false - }, - ignore: { - type: "array", - items: { - type: "number" - }, - uniqueItems: true - }, - ignoreArrayIndexes: { - type: "boolean", - default: false - } - }, - additionalProperties: false - }], - - messages: { - useConst: "Number constants declarations must use 'const'.", - noMagic: "No magic number: {{raw}}." - } - }, - - create(context) { - const config = context.options[0] || {}, - detectObjects = !!config.detectObjects, - enforceConst = !!config.enforceConst, - ignore = config.ignore || [], - ignoreArrayIndexes = !!config.ignoreArrayIndexes; - - /** - * Returns whether the node is number literal - * @param {Node} node - the node literal being evaluated - * @returns {boolean} true if the node is a number literal - */ - function isNumber(node) { - return typeof node.value === "number"; - } - - /** - * Returns whether the number should be ignored - * @param {number} num - the number - * @returns {boolean} true if the number should be ignored - */ - function shouldIgnoreNumber(num) { - return ignore.indexOf(num) !== -1; - } - - /** - * Returns whether the number should be ignored when used as a radix within parseInt() or Number.parseInt() - * @param {ASTNode} parent - the non-"UnaryExpression" parent - * @param {ASTNode} node - the node literal being evaluated - * @returns {boolean} true if the number should be ignored - */ - function shouldIgnoreParseInt(parent, node) { - return parent.type === "CallExpression" && node === parent.arguments[1] && - (parent.callee.name === "parseInt" || - parent.callee.type === "MemberExpression" && - parent.callee.object.name === "Number" && - parent.callee.property.name === "parseInt"); - } - - /** - * Returns whether the number should be ignored when used to define a JSX prop - * @param {ASTNode} parent - the non-"UnaryExpression" parent - * @returns {boolean} true if the number should be ignored - */ - function shouldIgnoreJSXNumbers(parent) { - return parent.type.indexOf("JSX") === 0; - } - - /** - * Returns whether the number should be ignored when used as an array index with enabled 'ignoreArrayIndexes' option. - * @param {ASTNode} parent - the non-"UnaryExpression" parent. - * @returns {boolean} true if the number should be ignored - */ - function shouldIgnoreArrayIndexes(parent) { - return parent.type === "MemberExpression" && ignoreArrayIndexes; - } - - return { - Literal(node) { - const okTypes = detectObjects ? [] : ["ObjectExpression", "Property", "AssignmentExpression"]; - - if (!isNumber(node)) { - return; - } - - let fullNumberNode; - let parent; - let value; - let raw; - - // For negative magic numbers: update the value and parent node - if (node.parent.type === "UnaryExpression" && node.parent.operator === "-") { - fullNumberNode = node.parent; - parent = fullNumberNode.parent; - value = -node.value; - raw = `-${node.raw}`; - } else { - fullNumberNode = node; - parent = node.parent; - value = node.value; - raw = node.raw; - } - - if (shouldIgnoreNumber(value) || - shouldIgnoreParseInt(parent, fullNumberNode) || - shouldIgnoreArrayIndexes(parent) || - shouldIgnoreJSXNumbers(parent)) { - return; - } - - if (parent.type === "VariableDeclarator") { - if (enforceConst && parent.parent.kind !== "const") { - context.report({ - node: fullNumberNode, - messageId: "useConst" - }); - } - } else if ( - okTypes.indexOf(parent.type) === -1 || - (parent.type === "AssignmentExpression" && parent.left.type === "Identifier") - ) { - context.report({ - node: fullNumberNode, - messageId: "noMagic", - data: { - raw - } - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-misleading-character-class.js b/tools/node_modules/eslint/lib/rules/no-misleading-character-class.js deleted file mode 100644 index 4fa650ed52725a..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-misleading-character-class.js +++ /dev/null @@ -1,193 +0,0 @@ -/** - * @author Toru Nagashima - */ -"use strict"; - -const { CALL, CONSTRUCT, ReferenceTracker, getStringIfConstant } = require("eslint-utils"); -const { RegExpParser, visitRegExpAST } = require("regexpp"); -const { isCombiningCharacter, isEmojiModifier, isRegionalIndicatorSymbol, isSurrogatePair } = require("../util/unicode"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Iterate character sequences of a given nodes. - * - * CharacterClassRange syntax can steal a part of character sequence, - * so this function reverts CharacterClassRange syntax and restore the sequence. - * - * @param {regexpp.AST.CharacterClassElement[]} nodes The node list to iterate character sequences. - * @returns {IterableIterator} The list of character sequences. - */ -function *iterateCharacterSequence(nodes) { - let seq = []; - - for (const node of nodes) { - switch (node.type) { - case "Character": - seq.push(node.value); - break; - - case "CharacterClassRange": - seq.push(node.min.value); - yield seq; - seq = [node.max.value]; - break; - - case "CharacterSet": - if (seq.length > 0) { - yield seq; - seq = []; - } - break; - - // no default - } - } - - if (seq.length > 0) { - yield seq; - } -} - -const hasCharacterSequence = { - surrogatePairWithoutUFlag(chars) { - return chars.some((c, i) => i !== 0 && isSurrogatePair(chars[i - 1], c)); - }, - - combiningClass(chars) { - return chars.some((c, i) => ( - i !== 0 && - isCombiningCharacter(c) && - !isCombiningCharacter(chars[i - 1]) - )); - }, - - emojiModifier(chars) { - return chars.some((c, i) => ( - i !== 0 && - isEmojiModifier(c) && - !isEmojiModifier(chars[i - 1]) - )); - }, - - regionalIndicatorSymbol(chars) { - return chars.some((c, i) => ( - i !== 0 && - isRegionalIndicatorSymbol(c) && - isRegionalIndicatorSymbol(chars[i - 1]) - )); - }, - - zwj(chars) { - const lastIndex = chars.length - 1; - - return chars.some((c, i) => ( - i !== 0 && - i !== lastIndex && - c === 0x200d && - chars[i - 1] !== 0x200d && - chars[i + 1] !== 0x200d - )); - } -}; - -const kinds = Object.keys(hasCharacterSequence); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow characters which are made with multiple code points in character class syntax", - category: "Possible Errors", - recommended: false, - url: "https://eslint.org/docs/rules/no-misleading-character-class" - }, - - schema: [], - - messages: { - surrogatePairWithoutUFlag: "Unexpected surrogate pair in character class. Use 'u' flag.", - combiningClass: "Unexpected combined character in character class.", - emojiModifier: "Unexpected modified Emoji in character class.", - regionalIndicatorSymbol: "Unexpected national flag in character class.", - zwj: "Unexpected joined character sequence in character class." - } - }, - create(context) { - const parser = new RegExpParser(); - - /** - * Verify a given regular expression. - * @param {Node} node The node to report. - * @param {string} pattern The regular expression pattern to verify. - * @param {string} flags The flags of the regular expression. - * @returns {void} - */ - function verify(node, pattern, flags) { - const patternNode = parser.parsePattern( - pattern, - 0, - pattern.length, - flags.includes("u") - ); - const has = { - surrogatePairWithoutUFlag: false, - combiningClass: false, - variationSelector: false, - emojiModifier: false, - regionalIndicatorSymbol: false, - zwj: false - }; - - visitRegExpAST(patternNode, { - onCharacterClassEnter(ccNode) { - for (const chars of iterateCharacterSequence(ccNode.elements)) { - for (const kind of kinds) { - has[kind] = has[kind] || hasCharacterSequence[kind](chars); - } - } - } - }); - - for (const kind of kinds) { - if (has[kind]) { - context.report({ node, messageId: kind }); - } - } - } - - return { - "Literal[regex]"(node) { - verify(node, node.regex.pattern, node.regex.flags); - }, - "Program"() { - const scope = context.getScope(); - const tracker = new ReferenceTracker(scope); - - /* - * Iterate calls of RegExp. - * E.g., `new RegExp()`, `RegExp()`, `new window.RegExp()`, - * `const {RegExp: a} = window; new a()`, etc... - */ - for (const { node } of tracker.iterateGlobalReferences({ - RegExp: { [CALL]: true, [CONSTRUCT]: true } - })) { - const [patternNode, flagsNode] = node.arguments; - const pattern = getStringIfConstant(patternNode, scope); - const flags = getStringIfConstant(flagsNode, scope); - - if (typeof pattern === "string") { - verify(node, pattern, flags || ""); - } - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-mixed-operators.js b/tools/node_modules/eslint/lib/rules/no-mixed-operators.js deleted file mode 100644 index 2b603a86df5571..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-mixed-operators.js +++ /dev/null @@ -1,214 +0,0 @@ -/** - * @fileoverview Rule to disallow mixed binary operators. - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils.js"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const ARITHMETIC_OPERATORS = ["+", "-", "*", "/", "%", "**"]; -const BITWISE_OPERATORS = ["&", "|", "^", "~", "<<", ">>", ">>>"]; -const COMPARISON_OPERATORS = ["==", "!=", "===", "!==", ">", ">=", "<", "<="]; -const LOGICAL_OPERATORS = ["&&", "||"]; -const RELATIONAL_OPERATORS = ["in", "instanceof"]; -const ALL_OPERATORS = [].concat( - ARITHMETIC_OPERATORS, - BITWISE_OPERATORS, - COMPARISON_OPERATORS, - LOGICAL_OPERATORS, - RELATIONAL_OPERATORS -); -const DEFAULT_GROUPS = [ - ARITHMETIC_OPERATORS, - BITWISE_OPERATORS, - COMPARISON_OPERATORS, - LOGICAL_OPERATORS, - RELATIONAL_OPERATORS -]; -const TARGET_NODE_TYPE = /^(?:Binary|Logical)Expression$/; - -/** - * Normalizes options. - * - * @param {Object|undefined} options - A options object to normalize. - * @returns {Object} Normalized option object. - */ -function normalizeOptions(options = {}) { - const hasGroups = options.groups && options.groups.length > 0; - const groups = hasGroups ? options.groups : DEFAULT_GROUPS; - const allowSamePrecedence = options.allowSamePrecedence !== false; - - return { - groups, - allowSamePrecedence - }; -} - -/** - * Checks whether any group which includes both given operator exists or not. - * - * @param {Array.} groups - A list of groups to check. - * @param {string} left - An operator. - * @param {string} right - Another operator. - * @returns {boolean} `true` if such group existed. - */ -function includesBothInAGroup(groups, left, right) { - return groups.some(group => group.indexOf(left) !== -1 && group.indexOf(right) !== -1); -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow mixed binary operators", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/no-mixed-operators" - }, - - schema: [ - { - type: "object", - properties: { - groups: { - type: "array", - items: { - type: "array", - items: { enum: ALL_OPERATORS }, - minItems: 2, - uniqueItems: true - }, - uniqueItems: true - }, - allowSamePrecedence: { - type: "boolean", - default: true - } - }, - additionalProperties: false - } - ] - }, - - create(context) { - const sourceCode = context.getSourceCode(); - const options = normalizeOptions(context.options[0]); - - /** - * Checks whether a given node should be ignored by options or not. - * - * @param {ASTNode} node - A node to check. This is a BinaryExpression - * node or a LogicalExpression node. This parent node is one of - * them, too. - * @returns {boolean} `true` if the node should be ignored. - */ - function shouldIgnore(node) { - const a = node; - const b = node.parent; - - return ( - !includesBothInAGroup(options.groups, a.operator, b.operator) || - ( - options.allowSamePrecedence && - astUtils.getPrecedence(a) === astUtils.getPrecedence(b) - ) - ); - } - - /** - * Checks whether the operator of a given node is mixed with parent - * node's operator or not. - * - * @param {ASTNode} node - A node to check. This is a BinaryExpression - * node or a LogicalExpression node. This parent node is one of - * them, too. - * @returns {boolean} `true` if the node was mixed. - */ - function isMixedWithParent(node) { - return ( - node.operator !== node.parent.operator && - !astUtils.isParenthesised(sourceCode, node) - ); - } - - /** - * Gets the operator token of a given node. - * - * @param {ASTNode} node - A node to check. This is a BinaryExpression - * node or a LogicalExpression node. - * @returns {Token} The operator token of the node. - */ - function getOperatorToken(node) { - return sourceCode.getTokenAfter(node.left, astUtils.isNotClosingParenToken); - } - - /** - * Reports both the operator of a given node and the operator of the - * parent node. - * - * @param {ASTNode} node - A node to check. This is a BinaryExpression - * node or a LogicalExpression node. This parent node is one of - * them, too. - * @returns {void} - */ - function reportBothOperators(node) { - const parent = node.parent; - const left = (parent.left === node) ? node : parent; - const right = (parent.left !== node) ? node : parent; - const message = - "Unexpected mix of '{{leftOperator}}' and '{{rightOperator}}'."; - const data = { - leftOperator: left.operator, - rightOperator: right.operator - }; - - context.report({ - node: left, - loc: getOperatorToken(left).loc.start, - message, - data - }); - context.report({ - node: right, - loc: getOperatorToken(right).loc.start, - message, - data - }); - } - - /** - * Checks between the operator of this node and the operator of the - * parent node. - * - * @param {ASTNode} node - A node to check. - * @returns {void} - */ - function check(node) { - if (TARGET_NODE_TYPE.test(node.parent.type) && - isMixedWithParent(node) && - !shouldIgnore(node) - ) { - reportBothOperators(node); - } - } - - return { - BinaryExpression: check, - LogicalExpression: check - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-mixed-requires.js b/tools/node_modules/eslint/lib/rules/no-mixed-requires.js deleted file mode 100644 index 5b07a5f2938753..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-mixed-requires.js +++ /dev/null @@ -1,225 +0,0 @@ -/** - * @fileoverview Rule to enforce grouped require statements for Node.JS - * @author Raphael Pigulla - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow `require` calls to be mixed with regular variable declarations", - category: "Node.js and CommonJS", - recommended: false, - url: "https://eslint.org/docs/rules/no-mixed-requires" - }, - - schema: [ - { - oneOf: [ - { - type: "boolean" - }, - { - type: "object", - properties: { - grouping: { - type: "boolean", - default: false - }, - allowCall: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ] - } - ] - }, - - create(context) { - - const options = context.options[0]; - let grouping = false, - allowCall = false; - - if (typeof options === "object") { - grouping = options.grouping; - allowCall = options.allowCall; - } else { - grouping = !!options; - } - - /** - * Returns the list of built-in modules. - * - * @returns {string[]} An array of built-in Node.js modules. - */ - function getBuiltinModules() { - - /* - * This list is generated using: - * `require("repl")._builtinLibs.concat('repl').sort()` - * This particular list is as per nodejs v0.12.2 and iojs v0.7.1 - */ - return [ - "assert", "buffer", "child_process", "cluster", "crypto", - "dgram", "dns", "domain", "events", "fs", "http", "https", - "net", "os", "path", "punycode", "querystring", "readline", - "repl", "smalloc", "stream", "string_decoder", "tls", "tty", - "url", "util", "v8", "vm", "zlib" - ]; - } - - const BUILTIN_MODULES = getBuiltinModules(); - - const DECL_REQUIRE = "require", - DECL_UNINITIALIZED = "uninitialized", - DECL_OTHER = "other"; - - const REQ_CORE = "core", - REQ_FILE = "file", - REQ_MODULE = "module", - REQ_COMPUTED = "computed"; - - /** - * Determines the type of a declaration statement. - * @param {ASTNode} initExpression The init node of the VariableDeclarator. - * @returns {string} The type of declaration represented by the expression. - */ - function getDeclarationType(initExpression) { - if (!initExpression) { - - // "var x;" - return DECL_UNINITIALIZED; - } - - if (initExpression.type === "CallExpression" && - initExpression.callee.type === "Identifier" && - initExpression.callee.name === "require" - ) { - - // "var x = require('util');" - return DECL_REQUIRE; - } - if (allowCall && - initExpression.type === "CallExpression" && - initExpression.callee.type === "CallExpression" - ) { - - // "var x = require('diagnose')('sub-module');" - return getDeclarationType(initExpression.callee); - } - if (initExpression.type === "MemberExpression") { - - // "var x = require('glob').Glob;" - return getDeclarationType(initExpression.object); - } - - // "var x = 42;" - return DECL_OTHER; - } - - /** - * Determines the type of module that is loaded via require. - * @param {ASTNode} initExpression The init node of the VariableDeclarator. - * @returns {string} The module type. - */ - function inferModuleType(initExpression) { - if (initExpression.type === "MemberExpression") { - - // "var x = require('glob').Glob;" - return inferModuleType(initExpression.object); - } - if (initExpression.arguments.length === 0) { - - // "var x = require();" - return REQ_COMPUTED; - } - - const arg = initExpression.arguments[0]; - - if (arg.type !== "Literal" || typeof arg.value !== "string") { - - // "var x = require(42);" - return REQ_COMPUTED; - } - - if (BUILTIN_MODULES.indexOf(arg.value) !== -1) { - - // "var fs = require('fs');" - return REQ_CORE; - } - if (/^\.{0,2}\//.test(arg.value)) { - - // "var utils = require('./utils');" - return REQ_FILE; - } - - // "var async = require('async');" - return REQ_MODULE; - - } - - /** - * Check if the list of variable declarations is mixed, i.e. whether it - * contains both require and other declarations. - * @param {ASTNode} declarations The list of VariableDeclarators. - * @returns {boolean} True if the declarations are mixed, false if not. - */ - function isMixed(declarations) { - const contains = {}; - - declarations.forEach(declaration => { - const type = getDeclarationType(declaration.init); - - contains[type] = true; - }); - - return !!( - contains[DECL_REQUIRE] && - (contains[DECL_UNINITIALIZED] || contains[DECL_OTHER]) - ); - } - - /** - * Check if all require declarations in the given list are of the same - * type. - * @param {ASTNode} declarations The list of VariableDeclarators. - * @returns {boolean} True if the declarations are grouped, false if not. - */ - function isGrouped(declarations) { - const found = {}; - - declarations.forEach(declaration => { - if (getDeclarationType(declaration.init) === DECL_REQUIRE) { - found[inferModuleType(declaration.init)] = true; - } - }); - - return Object.keys(found).length <= 1; - } - - - return { - - VariableDeclaration(node) { - - if (isMixed(node.declarations)) { - context.report({ node, message: "Do not mix 'require' and other declarations." }); - } else if (grouping && !isGrouped(node.declarations)) { - context.report({ node, message: "Do not mix core, module, file and computed requires." }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-mixed-spaces-and-tabs.js b/tools/node_modules/eslint/lib/rules/no-mixed-spaces-and-tabs.js deleted file mode 100644 index 1fc0b6074b8fd7..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-mixed-spaces-and-tabs.js +++ /dev/null @@ -1,146 +0,0 @@ -/** - * @fileoverview Disallow mixed spaces and tabs for indentation - * @author Jary Niebur - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "disallow mixed spaces and tabs for indentation", - category: "Stylistic Issues", - recommended: true, - url: "https://eslint.org/docs/rules/no-mixed-spaces-and-tabs" - }, - - schema: [ - { - enum: ["smart-tabs", true, false] - } - ] - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - let smartTabs; - const ignoredLocs = []; - - switch (context.options[0]) { - case true: // Support old syntax, maybe add deprecation warning here - case "smart-tabs": - smartTabs = true; - break; - default: - smartTabs = false; - } - - /** - * Determines if a given line and column are before a location. - * @param {Location} loc The location object from an AST node. - * @param {int} line The line to check. - * @param {int} column The column to check. - * @returns {boolean} True if the line and column are before the location, false if not. - * @private - */ - function beforeLoc(loc, line, column) { - if (line < loc.start.line) { - return true; - } - return line === loc.start.line && column < loc.start.column; - } - - /** - * Determines if a given line and column are after a location. - * @param {Location} loc The location object from an AST node. - * @param {int} line The line to check. - * @param {int} column The column to check. - * @returns {boolean} True if the line and column are after the location, false if not. - * @private - */ - function afterLoc(loc, line, column) { - if (line > loc.end.line) { - return true; - } - return line === loc.end.line && column > loc.end.column; - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - - TemplateElement(node) { - ignoredLocs.push(node.loc); - }, - - "Program:exit"(node) { - - /* - * At least one space followed by a tab - * or the reverse before non-tab/-space - * characters begin. - */ - let regex = /^(?=[\t ]*(\t | \t))/; - const lines = sourceCode.lines, - comments = sourceCode.getAllComments(); - - comments.forEach(comment => { - ignoredLocs.push(comment.loc); - }); - - ignoredLocs.sort((first, second) => { - if (beforeLoc(first, second.start.line, second.start.column)) { - return 1; - } - - if (beforeLoc(second, first.start.line, second.start.column)) { - return -1; - } - - return 0; - }); - - if (smartTabs) { - - /* - * At least one space followed by a tab - * before non-tab/-space characters begin. - */ - regex = /^(?=[\t ]* \t)/; - } - - lines.forEach((line, i) => { - const match = regex.exec(line); - - if (match) { - const lineNumber = i + 1, - column = match.index + 1; - - for (let j = 0; j < ignoredLocs.length; j++) { - if (beforeLoc(ignoredLocs[j], lineNumber, column)) { - continue; - } - if (afterLoc(ignoredLocs[j], lineNumber, column)) { - continue; - } - - return; - } - - context.report({ node, loc: { line: lineNumber, column }, message: "Mixed spaces and tabs." }); - } - }); - } - - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-multi-assign.js b/tools/node_modules/eslint/lib/rules/no-multi-assign.js deleted file mode 100644 index 8524a1a571ef9e..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-multi-assign.js +++ /dev/null @@ -1,45 +0,0 @@ -/** - * @fileoverview Rule to check use of chained assignment expressions - * @author Stewart Rand - */ - -"use strict"; - - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow use of chained assignment expressions", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/no-multi-assign" - }, - - schema: [] - }, - - create(context) { - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - AssignmentExpression(node) { - if (["AssignmentExpression", "VariableDeclarator"].indexOf(node.parent.type) !== -1) { - context.report({ - node, - message: "Unexpected chained assignment." - }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-multi-spaces.js b/tools/node_modules/eslint/lib/rules/no-multi-spaces.js deleted file mode 100644 index c5fb07403421af..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-multi-spaces.js +++ /dev/null @@ -1,134 +0,0 @@ -/** - * @fileoverview Disallow use of multiple spaces. - * @author Nicholas C. Zakas - */ - -"use strict"; - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "disallow multiple spaces", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-multi-spaces" - }, - - fixable: "whitespace", - - schema: [ - { - type: "object", - properties: { - exceptions: { - type: "object", - patternProperties: { - "^([A-Z][a-z]*)+$": { - type: "boolean" - } - }, - additionalProperties: false - }, - ignoreEOLComments: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ] - }, - - create(context) { - const sourceCode = context.getSourceCode(); - const options = context.options[0] || {}; - const ignoreEOLComments = options.ignoreEOLComments; - const exceptions = Object.assign({ Property: true }, options.exceptions); - const hasExceptions = Object.keys(exceptions).filter(key => exceptions[key]).length > 0; - - /** - * Formats value of given comment token for error message by truncating its length. - * @param {Token} token comment token - * @returns {string} formatted value - * @private - */ - function formatReportedCommentValue(token) { - const valueLines = token.value.split("\n"); - const value = valueLines[0]; - const formattedValue = `${value.slice(0, 12)}...`; - - return valueLines.length === 1 && value.length <= 12 ? value : formattedValue; - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - Program() { - sourceCode.tokensAndComments.forEach((leftToken, leftIndex, tokensAndComments) => { - if (leftIndex === tokensAndComments.length - 1) { - return; - } - const rightToken = tokensAndComments[leftIndex + 1]; - - // Ignore tokens that don't have 2 spaces between them or are on different lines - if ( - !sourceCode.text.slice(leftToken.range[1], rightToken.range[0]).includes(" ") || - leftToken.loc.end.line < rightToken.loc.start.line - ) { - return; - } - - // Ignore comments that are the last token on their line if `ignoreEOLComments` is active. - if ( - ignoreEOLComments && - astUtils.isCommentToken(rightToken) && - ( - leftIndex === tokensAndComments.length - 2 || - rightToken.loc.end.line < tokensAndComments[leftIndex + 2].loc.start.line - ) - ) { - return; - } - - // Ignore tokens that are in a node in the "exceptions" object - if (hasExceptions) { - const parentNode = sourceCode.getNodeByRangeIndex(rightToken.range[0] - 1); - - if (parentNode && exceptions[parentNode.type]) { - return; - } - } - - let displayValue; - - if (rightToken.type === "Block") { - displayValue = `/*${formatReportedCommentValue(rightToken)}*/`; - } else if (rightToken.type === "Line") { - displayValue = `//${formatReportedCommentValue(rightToken)}`; - } else { - displayValue = rightToken.value; - } - - context.report({ - node: rightToken, - loc: rightToken.loc.start, - message: "Multiple spaces found before '{{displayValue}}'.", - data: { displayValue }, - fix: fixer => fixer.replaceTextRange([leftToken.range[1], rightToken.range[0]], " ") - }); - }); - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-multi-str.js b/tools/node_modules/eslint/lib/rules/no-multi-str.js deleted file mode 100644 index 844842392df7d3..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-multi-str.js +++ /dev/null @@ -1,58 +0,0 @@ -/** - * @fileoverview Rule to flag when using multiline strings - * @author Ilya Volodin - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow multiline strings", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-multi-str" - }, - - schema: [] - }, - - create(context) { - - /** - * Determines if a given node is part of JSX syntax. - * @param {ASTNode} node The node to check. - * @returns {boolean} True if the node is a JSX node, false if not. - * @private - */ - function isJSXElement(node) { - return node.type.indexOf("JSX") === 0; - } - - //-------------------------------------------------------------------------- - // Public API - //-------------------------------------------------------------------------- - - return { - - Literal(node) { - if (astUtils.LINEBREAK_MATCHER.test(node.raw) && !isJSXElement(node.parent)) { - context.report({ node, message: "Multiline support is limited to browsers supporting ES5 only." }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-multiple-empty-lines.js b/tools/node_modules/eslint/lib/rules/no-multiple-empty-lines.js deleted file mode 100644 index f945cfeffe2b07..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-multiple-empty-lines.js +++ /dev/null @@ -1,139 +0,0 @@ -/** - * @fileoverview Disallows multiple blank lines. - * implementation adapted from the no-trailing-spaces rule. - * @author Greg Cochard - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "disallow multiple empty lines", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/no-multiple-empty-lines" - }, - - fixable: "whitespace", - - schema: [ - { - type: "object", - properties: { - max: { - type: "integer", - minimum: 0 - }, - maxEOF: { - type: "integer", - minimum: 0 - }, - maxBOF: { - type: "integer", - minimum: 0 - } - }, - required: ["max"], - additionalProperties: false - } - ] - }, - - create(context) { - - // Use options.max or 2 as default - let max = 2, - maxEOF = max, - maxBOF = max; - - if (context.options.length) { - max = context.options[0].max; - maxEOF = typeof context.options[0].maxEOF !== "undefined" ? context.options[0].maxEOF : max; - maxBOF = typeof context.options[0].maxBOF !== "undefined" ? context.options[0].maxBOF : max; - } - - const sourceCode = context.getSourceCode(); - - // 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; - const templateLiteralLines = new Set(); - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - TemplateLiteral(node) { - node.quasis.forEach(literalPart => { - - // Empty lines have a semantic meaning if they're inside template literals. Don't count these as empty lines. - for (let ignoredLine = literalPart.loc.start.line; ignoredLine < literalPart.loc.end.line; ignoredLine++) { - templateLiteralLines.add(ignoredLine); - } - }); - }, - "Program:exit"(node) { - return allLines - - // Given a list of lines, first get a list of line numbers that are non-empty. - .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) - - // Given two line numbers of non-empty lines, report the lines between if the difference is too large. - .reduce((lastLineNumber, lineNumber) => { - let message, maxAllowed; - - if (lastLineNumber === 0) { - message = "Too many blank lines at the beginning of file. Max of {{max}} allowed."; - maxAllowed = maxBOF; - } else if (lineNumber === allLines.length + 1) { - message = "Too many blank lines at the end of file. Max of {{max}} allowed."; - maxAllowed = maxEOF; - } else { - message = "More than {{max}} blank {{pluralizedLines}} not allowed."; - maxAllowed = max; - } - - if (lineNumber - lastLineNumber - 1 > maxAllowed) { - context.report({ - node, - loc: { start: { line: lastLineNumber + 1, column: 0 }, end: { line: lineNumber, column: 0 } }, - message, - data: { max: maxAllowed, pluralizedLines: maxAllowed === 1 ? "line" : "lines" }, - fix(fixer) { - const rangeStart = sourceCode.getIndexFromLoc({ line: lastLineNumber + 1, column: 0 }); - - /* - * The end of the removal range is usually the start index of the next line. - * However, at the end of the file there is no next line, so the end of the - * range is just the length of the text. - */ - const lineNumberAfterRemovedLines = lineNumber - maxAllowed; - const rangeEnd = lineNumberAfterRemovedLines <= allLines.length - ? sourceCode.getIndexFromLoc({ line: lineNumberAfterRemovedLines, column: 0 }) - : sourceCode.text.length; - - return fixer.removeRange([rangeStart, rangeEnd]); - } - }); - } - - return lineNumber; - }, 0); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-native-reassign.js b/tools/node_modules/eslint/lib/rules/no-native-reassign.js deleted file mode 100644 index 9ecfb4da7cbee9..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-native-reassign.js +++ /dev/null @@ -1,93 +0,0 @@ -/** - * @fileoverview Rule to disallow assignments to native objects or read-only global variables - * @author Ilya Volodin - * @deprecated in ESLint v3.3.0 - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow assignments to native objects or read-only global variables", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-native-reassign" - }, - - deprecated: true, - - replacedBy: ["no-global-assign"], - - schema: [ - { - type: "object", - properties: { - exceptions: { - type: "array", - items: { type: "string" }, - uniqueItems: true - } - }, - additionalProperties: false - } - ] - }, - - create(context) { - const config = context.options[0]; - const exceptions = (config && config.exceptions) || []; - - /** - * Reports write references. - * @param {Reference} reference - A reference to check. - * @param {int} index - The index of the reference in the references. - * @param {Reference[]} references - The array that the reference belongs to. - * @returns {void} - */ - function checkReference(reference, index, references) { - const identifier = reference.identifier; - - if (reference.init === false && - reference.isWrite() && - - /* - * Destructuring assignments can have multiple default value, - * so possibly there are multiple writeable references for the same identifier. - */ - (index === 0 || references[index - 1].identifier !== identifier) - ) { - context.report({ - node: identifier, - message: "Read-only global '{{name}}' should not be modified.", - data: identifier - }); - } - } - - /** - * Reports write references if a given variable is read-only builtin. - * @param {Variable} variable - A variable to check. - * @returns {void} - */ - function checkVariable(variable) { - if (variable.writeable === false && exceptions.indexOf(variable.name) === -1) { - variable.references.forEach(checkReference); - } - } - - return { - Program() { - const globalScope = context.getScope(); - - globalScope.variables.forEach(checkVariable); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-negated-condition.js b/tools/node_modules/eslint/lib/rules/no-negated-condition.js deleted file mode 100644 index e55a8287487de3..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-negated-condition.js +++ /dev/null @@ -1,85 +0,0 @@ -/** - * @fileoverview Rule to disallow a negated condition - * @author Alberto Rodríguez - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow negated conditions", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/no-negated-condition" - }, - - schema: [] - }, - - create(context) { - - /** - * Determines if a given node is an if-else without a condition on the else - * @param {ASTNode} node The node to check. - * @returns {boolean} True if the node has an else without an if. - * @private - */ - function hasElseWithoutCondition(node) { - return node.alternate && node.alternate.type !== "IfStatement"; - } - - /** - * Determines if a given node is a negated unary expression - * @param {Object} test The test object to check. - * @returns {boolean} True if the node is a negated unary expression. - * @private - */ - function isNegatedUnaryExpression(test) { - return test.type === "UnaryExpression" && test.operator === "!"; - } - - /** - * Determines if a given node is a negated binary expression - * @param {Test} test The test to check. - * @returns {boolean} True if the node is a negated binary expression. - * @private - */ - function isNegatedBinaryExpression(test) { - return test.type === "BinaryExpression" && - (test.operator === "!=" || test.operator === "!=="); - } - - /** - * Determines if a given node has a negated if expression - * @param {ASTNode} node The node to check. - * @returns {boolean} True if the node has a negated if expression. - * @private - */ - function isNegatedIf(node) { - return isNegatedUnaryExpression(node.test) || isNegatedBinaryExpression(node.test); - } - - return { - IfStatement(node) { - if (!hasElseWithoutCondition(node)) { - return; - } - - if (isNegatedIf(node)) { - context.report({ node, message: "Unexpected negated condition." }); - } - }, - ConditionalExpression(node) { - if (isNegatedIf(node)) { - context.report({ node, message: "Unexpected negated condition." }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-negated-in-lhs.js b/tools/node_modules/eslint/lib/rules/no-negated-in-lhs.js deleted file mode 100644 index 0084ad1570bb00..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-negated-in-lhs.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * @fileoverview A rule to disallow negated left operands of the `in` operator - * @author Michael Ficarra - * @deprecated in ESLint v3.3.0 - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow negating the left operand in `in` expressions", - category: "Possible Errors", - recommended: false, - url: "https://eslint.org/docs/rules/no-negated-in-lhs" - }, - - replacedBy: ["no-unsafe-negation"], - - deprecated: true, - schema: [] - }, - - create(context) { - - return { - - BinaryExpression(node) { - if (node.operator === "in" && node.left.type === "UnaryExpression" && node.left.operator === "!") { - context.report({ node, message: "The 'in' expression's left operand is negated." }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-nested-ternary.js b/tools/node_modules/eslint/lib/rules/no-nested-ternary.js deleted file mode 100644 index 87a11e87962a8f..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-nested-ternary.js +++ /dev/null @@ -1,37 +0,0 @@ -/** - * @fileoverview Rule to flag nested ternary expressions - * @author Ian Christian Myers - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow nested ternary expressions", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/no-nested-ternary" - }, - - schema: [] - }, - - create(context) { - - return { - ConditionalExpression(node) { - if (node.alternate.type === "ConditionalExpression" || - node.consequent.type === "ConditionalExpression") { - context.report({ node, message: "Do not nest ternary expressions." }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-new-func.js b/tools/node_modules/eslint/lib/rules/no-new-func.js deleted file mode 100644 index 23e92f7bf3030c..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-new-func.js +++ /dev/null @@ -1,48 +0,0 @@ -/** - * @fileoverview Rule to flag when using new Function - * @author Ilya Volodin - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow `new` operators with the `Function` object", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-new-func" - }, - - schema: [] - }, - - create(context) { - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Reports a node. - * @param {ASTNode} node The node to report - * @returns {void} - * @private - */ - function report(node) { - context.report({ node, message: "The Function constructor is eval." }); - } - - return { - "NewExpression[callee.name = 'Function']": report, - "CallExpression[callee.name = 'Function']": report - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-new-object.js b/tools/node_modules/eslint/lib/rules/no-new-object.js deleted file mode 100644 index f5cc28664f4e1c..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-new-object.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * @fileoverview A rule to disallow calls to the Object constructor - * @author Matt DuVall - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow `Object` constructors", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/no-new-object" - }, - - schema: [] - }, - - create(context) { - - return { - - NewExpression(node) { - if (node.callee.name === "Object") { - context.report({ node, message: "The object literal notation {} is preferrable." }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-new-require.js b/tools/node_modules/eslint/lib/rules/no-new-require.js deleted file mode 100644 index 1eae0659430fbd..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-new-require.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * @fileoverview Rule to disallow use of new operator with the `require` function - * @author Wil Moore III - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow `new` operators with calls to `require`", - category: "Node.js and CommonJS", - recommended: false, - url: "https://eslint.org/docs/rules/no-new-require" - }, - - schema: [] - }, - - create(context) { - - return { - - NewExpression(node) { - if (node.callee.type === "Identifier" && node.callee.name === "require") { - context.report({ node, message: "Unexpected use of new with require." }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-new-symbol.js b/tools/node_modules/eslint/lib/rules/no-new-symbol.js deleted file mode 100644 index ccf757ed6a0cee..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-new-symbol.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * @fileoverview Rule to disallow use of the new operator with the `Symbol` object - * @author Alberto Rodríguez - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow `new` operators with the `Symbol` object", - category: "ECMAScript 6", - recommended: true, - url: "https://eslint.org/docs/rules/no-new-symbol" - }, - - schema: [] - }, - - create(context) { - - return { - "Program:exit"() { - const globalScope = context.getScope(); - const variable = globalScope.set.get("Symbol"); - - if (variable && variable.defs.length === 0) { - variable.references.forEach(ref => { - const node = ref.identifier; - - if (node.parent && node.parent.type === "NewExpression") { - context.report({ node, message: "`Symbol` cannot be called as a constructor." }); - } - }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-new-wrappers.js b/tools/node_modules/eslint/lib/rules/no-new-wrappers.js deleted file mode 100644 index ae2aeec0341243..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-new-wrappers.js +++ /dev/null @@ -1,40 +0,0 @@ -/** - * @fileoverview Rule to flag when using constructor for wrapper objects - * @author Ilya Volodin - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow `new` operators with the `String`, `Number`, and `Boolean` objects", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-new-wrappers" - }, - - schema: [] - }, - - create(context) { - - return { - - NewExpression(node) { - const wrapperObjects = ["String", "Number", "Boolean", "Math", "JSON"]; - - if (wrapperObjects.indexOf(node.callee.name) > -1) { - context.report({ node, message: "Do not use {{fn}} as a constructor.", data: { fn: node.callee.name } }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-new.js b/tools/node_modules/eslint/lib/rules/no-new.js deleted file mode 100644 index 2e0702597eade3..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-new.js +++ /dev/null @@ -1,36 +0,0 @@ -/** - * @fileoverview Rule to flag statements with function invocation preceded by - * "new" and not part of assignment - * @author Ilya Volodin - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow `new` operators outside of assignments or comparisons", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-new" - }, - - schema: [] - }, - - create(context) { - - return { - "ExpressionStatement > NewExpression"(node) { - context.report({ node: node.parent, message: "Do not use 'new' for side effects." }); - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-obj-calls.js b/tools/node_modules/eslint/lib/rules/no-obj-calls.js deleted file mode 100644 index 92492b7a26ed79..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-obj-calls.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * @fileoverview Rule to flag use of an object property of the global object (Math and JSON) as a function - * @author James Allardice - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow calling global object properties as functions", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-obj-calls" - }, - - schema: [] - }, - - create(context) { - - return { - CallExpression(node) { - - if (node.callee.type === "Identifier") { - const name = node.callee.name; - - if (name === "Math" || name === "JSON" || name === "Reflect") { - context.report({ node, message: "'{{name}}' is not a function.", data: { name } }); - } - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-octal-escape.js b/tools/node_modules/eslint/lib/rules/no-octal-escape.js deleted file mode 100644 index fc073b14033410..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-octal-escape.js +++ /dev/null @@ -1,50 +0,0 @@ -/** - * @fileoverview Rule to flag octal escape sequences in string literals. - * @author Ian Christian Myers - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow octal escape sequences in string literals", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-octal-escape" - }, - - schema: [] - }, - - create(context) { - - return { - - Literal(node) { - if (typeof node.value !== "string") { - return; - } - - const match = node.raw.match(/^([^\\]|\\[^0-7])*\\([0-3][0-7]{1,2}|[4-7][0-7]|[0-7])/); - - if (match) { - const octalDigit = match[2]; - - // \0 is actually not considered an octal - if (match[2] !== "0" || typeof match[3] !== "undefined") { - context.report({ node, message: "Don't use octal: '\\{{octalDigit}}'. Use '\\u....' instead.", data: { octalDigit } }); - } - } - } - - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-octal.js b/tools/node_modules/eslint/lib/rules/no-octal.js deleted file mode 100644 index db1fa40aa5df0a..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-octal.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * @fileoverview Rule to flag when initializing octal literal - * @author Ilya Volodin - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow octal literals", - category: "Best Practices", - recommended: true, - url: "https://eslint.org/docs/rules/no-octal" - }, - - schema: [] - }, - - create(context) { - - return { - - Literal(node) { - if (typeof node.value === "number" && /^0[0-7]/.test(node.raw)) { - context.report({ node, message: "Octal literals should not be used." }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-param-reassign.js b/tools/node_modules/eslint/lib/rules/no-param-reassign.js deleted file mode 100644 index 83760edb8c2fec..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-param-reassign.js +++ /dev/null @@ -1,184 +0,0 @@ -/** - * @fileoverview Disallow reassignment of function parameters. - * @author Nat Burns - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -const stopNodePattern = /(?:Statement|Declaration|Function(?:Expression)?|Program)$/; - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow reassigning `function` parameters", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-param-reassign" - }, - - schema: [ - { - oneOf: [ - { - type: "object", - properties: { - props: { - enum: [false] - } - }, - additionalProperties: false - }, - { - type: "object", - properties: { - props: { - enum: [true] - }, - ignorePropertyModificationsFor: { - type: "array", - items: { - type: "string" - }, - uniqueItems: true - } - }, - additionalProperties: false - } - ] - } - ] - }, - - create(context) { - const props = context.options[0] && context.options[0].props; - const ignoredPropertyAssignmentsFor = context.options[0] && context.options[0].ignorePropertyModificationsFor || []; - - /** - * Checks whether or not the reference modifies properties of its variable. - * @param {Reference} reference - A reference to check. - * @returns {boolean} Whether or not the reference modifies properties of its variable. - */ - function isModifyingProp(reference) { - let node = reference.identifier; - let parent = node.parent; - - while (parent && !stopNodePattern.test(parent.type)) { - switch (parent.type) { - - // e.g. foo.a = 0; - case "AssignmentExpression": - return parent.left === node; - - // e.g. ++foo.a; - case "UpdateExpression": - return true; - - // e.g. delete foo.a; - case "UnaryExpression": - if (parent.operator === "delete") { - return true; - } - break; - - // EXCLUDES: e.g. cache.get(foo.a).b = 0; - case "CallExpression": - if (parent.callee !== node) { - return false; - } - break; - - // EXCLUDES: e.g. cache[foo.a] = 0; - case "MemberExpression": - if (parent.property === node) { - return false; - } - break; - - // EXCLUDES: e.g. ({ [foo]: a }) = bar; - case "Property": - if (parent.key === node) { - return false; - } - - break; - - // EXCLUDES: e.g. (foo ? a : b).c = bar; - case "ConditionalExpression": - if (parent.test === node) { - return false; - } - - break; - - // no default - } - - node = parent; - parent = node.parent; - } - - return false; - } - - /** - * Reports a reference if is non initializer and writable. - * @param {Reference} reference - A reference to check. - * @param {int} index - The index of the reference in the references. - * @param {Reference[]} references - The array that the reference belongs to. - * @returns {void} - */ - function checkReference(reference, index, references) { - const identifier = reference.identifier; - - if (identifier && - !reference.init && - - /* - * Destructuring assignments can have multiple default value, - * so possibly there are multiple writeable references for the same identifier. - */ - (index === 0 || references[index - 1].identifier !== identifier) - ) { - if (reference.isWrite()) { - context.report({ node: identifier, message: "Assignment to function parameter '{{name}}'.", data: { name: identifier.name } }); - } else if (props && isModifyingProp(reference) && ignoredPropertyAssignmentsFor.indexOf(identifier.name) === -1) { - context.report({ node: identifier, message: "Assignment to property of function parameter '{{name}}'.", data: { name: identifier.name } }); - } - } - } - - /** - * Finds and reports references that are non initializer and writable. - * @param {Variable} variable - A variable to check. - * @returns {void} - */ - function checkVariable(variable) { - if (variable.defs[0].type === "Parameter") { - variable.references.forEach(checkReference); - } - } - - /** - * Checks parameters of a given function node. - * @param {ASTNode} node - A function node to check. - * @returns {void} - */ - function checkForFunction(node) { - context.getDeclaredVariables(node).forEach(checkVariable); - } - - return { - - // `:exit` is needed for the `node.parent` property of identifier nodes. - "FunctionDeclaration:exit": checkForFunction, - "FunctionExpression:exit": checkForFunction, - "ArrowFunctionExpression:exit": checkForFunction - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-path-concat.js b/tools/node_modules/eslint/lib/rules/no-path-concat.js deleted file mode 100644 index dad56a4f56a9d0..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-path-concat.js +++ /dev/null @@ -1,52 +0,0 @@ -/** - * @fileoverview Disallow string concatenation when using __dirname and __filename - * @author Nicholas C. Zakas - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow string concatenation with `__dirname` and `__filename`", - category: "Node.js and CommonJS", - recommended: false, - url: "https://eslint.org/docs/rules/no-path-concat" - }, - - schema: [] - }, - - create(context) { - - const MATCHER = /^__(?:dir|file)name$/; - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - - BinaryExpression(node) { - - const left = node.left, - right = node.right; - - if (node.operator === "+" && - ((left.type === "Identifier" && MATCHER.test(left.name)) || - (right.type === "Identifier" && MATCHER.test(right.name))) - ) { - - context.report({ node, message: "Use path.join() or path.resolve() instead of + to create paths." }); - } - } - - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-plusplus.js b/tools/node_modules/eslint/lib/rules/no-plusplus.js deleted file mode 100644 index 1d122dcd31f086..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-plusplus.js +++ /dev/null @@ -1,65 +0,0 @@ -/** - * @fileoverview Rule to flag use of unary increment and decrement operators. - * @author Ian Christian Myers - * @author Brody McKee (github.com/mrmckeb) - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow the unary operators `++` and `--`", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/no-plusplus" - }, - - schema: [ - { - type: "object", - properties: { - allowForLoopAfterthoughts: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ] - }, - - create(context) { - - const config = context.options[0]; - let allowInForAfterthought = false; - - if (typeof config === "object") { - allowInForAfterthought = config.allowForLoopAfterthoughts === true; - } - - return { - - UpdateExpression(node) { - if (allowInForAfterthought && node.parent.type === "ForStatement") { - return; - } - context.report({ - node, - message: "Unary operator '{{operator}}' used.", - data: { - operator: node.operator - } - }); - } - - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-process-env.js b/tools/node_modules/eslint/lib/rules/no-process-env.js deleted file mode 100644 index a66d9709b09b4f..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-process-env.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * @fileoverview Disallow the use of process.env() - * @author Vignesh Anand - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow the use of `process.env`", - category: "Node.js and CommonJS", - recommended: false, - url: "https://eslint.org/docs/rules/no-process-env" - }, - - schema: [] - }, - - create(context) { - - return { - - MemberExpression(node) { - const objectName = node.object.name, - propertyName = node.property.name; - - if (objectName === "process" && !node.computed && propertyName && propertyName === "env") { - context.report({ node, message: "Unexpected use of process.env." }); - } - - } - - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-process-exit.js b/tools/node_modules/eslint/lib/rules/no-process-exit.js deleted file mode 100644 index fcfc6b2af59d0e..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-process-exit.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * @fileoverview Disallow the use of process.exit() - * @author Nicholas C. Zakas - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow the use of `process.exit()`", - category: "Node.js and CommonJS", - recommended: false, - url: "https://eslint.org/docs/rules/no-process-exit" - }, - - schema: [] - }, - - create(context) { - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - "CallExpression > MemberExpression.callee[object.name = 'process'][property.name = 'exit']"(node) { - context.report({ node: node.parent, message: "Don't use process.exit(); throw an error instead." }); - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-proto.js b/tools/node_modules/eslint/lib/rules/no-proto.js deleted file mode 100644 index 80b9650941696d..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-proto.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * @fileoverview Rule to flag usage of __proto__ property - * @author Ilya Volodin - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow the use of the `__proto__` property", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-proto" - }, - - schema: [] - }, - - create(context) { - - return { - - MemberExpression(node) { - - if (node.property && - (node.property.type === "Identifier" && node.property.name === "__proto__" && !node.computed) || - (node.property.type === "Literal" && node.property.value === "__proto__")) { - context.report({ node, message: "The '__proto__' property is deprecated." }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-prototype-builtins.js b/tools/node_modules/eslint/lib/rules/no-prototype-builtins.js deleted file mode 100644 index 171395306725eb..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-prototype-builtins.js +++ /dev/null @@ -1,57 +0,0 @@ -/** - * @fileoverview Rule to disallow use of Object.prototype builtins on objects - * @author Andrew Levine - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow calling some `Object.prototype` methods directly on objects", - category: "Possible Errors", - recommended: false, - url: "https://eslint.org/docs/rules/no-prototype-builtins" - }, - - schema: [] - }, - - create(context) { - const DISALLOWED_PROPS = [ - "hasOwnProperty", - "isPrototypeOf", - "propertyIsEnumerable" - ]; - - /** - * Reports if a disallowed property is used in a CallExpression - * @param {ASTNode} node The CallExpression node. - * @returns {void} - */ - function disallowBuiltIns(node) { - if (node.callee.type !== "MemberExpression" || node.callee.computed) { - return; - } - const propName = node.callee.property.name; - - if (DISALLOWED_PROPS.indexOf(propName) > -1) { - context.report({ - message: "Do not access Object.prototype method '{{prop}}' from target object.", - loc: node.callee.property.loc.start, - data: { prop: propName }, - node - }); - } - } - - return { - CallExpression: disallowBuiltIns - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-redeclare.js b/tools/node_modules/eslint/lib/rules/no-redeclare.js deleted file mode 100644 index 4d689cc6138716..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-redeclare.js +++ /dev/null @@ -1,104 +0,0 @@ -/** - * @fileoverview Rule to flag when the same variable is declared more then once. - * @author Ilya Volodin - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow variable redeclaration", - category: "Best Practices", - recommended: true, - url: "https://eslint.org/docs/rules/no-redeclare" - }, - - schema: [ - { - type: "object", - properties: { - builtinGlobals: { type: "boolean", default: false } - }, - additionalProperties: false - } - ] - }, - - create(context) { - const options = { - builtinGlobals: context.options[0] && context.options[0].builtinGlobals - }; - - /** - * Find variables in a given scope and flag redeclared ones. - * @param {Scope} scope - An eslint-scope scope object. - * @returns {void} - * @private - */ - function findVariablesInScope(scope) { - 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((a, b) => a.range[1] - b.range[1]); - - for (let i = (hasBuiltin ? 0 : 1), l = variable.identifiers.length; i < l; i++) { - context.report({ node: variable.identifiers[i], message: "'{{a}}' is already defined.", data: { a: variable.name } }); - } - } - }); - - } - - /** - * Find variables in the current scope. - * @param {ASTNode} node - The Program node. - * @returns {void} - * @private - */ - function checkForGlobal(node) { - const scope = context.getScope(), - parserOptions = context.parserOptions, - ecmaFeatures = parserOptions.ecmaFeatures || {}; - - // Nodejs env or modules has a special scope. - if (ecmaFeatures.globalReturn || node.sourceType === "module") { - findVariablesInScope(scope.childScopes[0]); - } else { - findVariablesInScope(scope); - } - } - - /** - * Find variables in the current scope. - * @returns {void} - * @private - */ - function checkForBlock() { - findVariablesInScope(context.getScope()); - } - - if (context.parserOptions.ecmaVersion >= 6) { - return { - Program: checkForGlobal, - BlockStatement: checkForBlock, - SwitchStatement: checkForBlock - }; - } - return { - Program: checkForGlobal, - FunctionDeclaration: checkForBlock, - FunctionExpression: checkForBlock, - ArrowFunctionExpression: checkForBlock - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-regex-spaces.js b/tools/node_modules/eslint/lib/rules/no-regex-spaces.js deleted file mode 100644 index d0f7293d20eef1..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-regex-spaces.js +++ /dev/null @@ -1,116 +0,0 @@ -/** - * @fileoverview Rule to count multiple spaces in regular expressions - * @author Matt DuVall - */ - -"use strict"; - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow multiple spaces in regular expressions", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-regex-spaces" - }, - - schema: [], - fixable: "code" - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - /** - * Validate regular expressions - * @param {ASTNode} node node to validate - * @param {string} value regular expression to validate - * @param {number} valueStart The start location of the regex/string literal. It will always be the case that - * `sourceCode.getText().slice(valueStart, valueStart + value.length) === value` - * @returns {void} - * @private - */ - function checkRegex(node, value, valueStart) { - const multipleSpacesRegex = /( {2,})( [+*{?]|[^+*{?]|$)/, - regexResults = multipleSpacesRegex.exec(value); - - if (regexResults !== null) { - const count = regexResults[1].length; - - context.report({ - node, - message: "Spaces are hard to count. Use {{{count}}}.", - data: { count }, - fix(fixer) { - return fixer.replaceTextRange( - [valueStart + regexResults.index, valueStart + regexResults.index + count], - ` {${count}}` - ); - } - }); - - /* - * TODO: (platinumazure) Fix message to use rule message - * substitution when api.report is fixed in lib/eslint.js. - */ - } - } - - /** - * Validate regular expression literals - * @param {ASTNode} node node to validate - * @returns {void} - * @private - */ - function checkLiteral(node) { - const token = sourceCode.getFirstToken(node), - nodeType = token.type, - nodeValue = token.value; - - if (nodeType === "RegularExpression") { - checkRegex(node, nodeValue, token.range[0]); - } - } - - /** - * Check if node is a string - * @param {ASTNode} node node to evaluate - * @returns {boolean} True if its a string - * @private - */ - function isString(node) { - return node && node.type === "Literal" && typeof node.value === "string"; - } - - /** - * Validate strings passed to the RegExp constructor - * @param {ASTNode} node node to validate - * @returns {void} - * @private - */ - function checkFunction(node) { - const scope = context.getScope(); - const regExpVar = astUtils.getVariableByName(scope, "RegExp"); - const shadowed = regExpVar && regExpVar.defs.length > 0; - - if (node.callee.type === "Identifier" && node.callee.name === "RegExp" && isString(node.arguments[0]) && !shadowed) { - checkRegex(node, node.arguments[0].value, node.arguments[0].range[0] + 1); - } - } - - return { - Literal: checkLiteral, - CallExpression: checkFunction, - NewExpression: checkFunction - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-restricted-globals.js b/tools/node_modules/eslint/lib/rules/no-restricted-globals.js deleted file mode 100644 index 1a2629a8ec95e8..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-restricted-globals.js +++ /dev/null @@ -1,123 +0,0 @@ -/** - * @fileoverview Restrict usage of specified globals. - * @author Benoît Zugmeyer - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const DEFAULT_MESSAGE_TEMPLATE = "Unexpected use of '{{name}}'.", - CUSTOM_MESSAGE_TEMPLATE = "Unexpected use of '{{name}}'. {{customMessage}}"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow specified global variables", - category: "Variables", - recommended: false, - url: "https://eslint.org/docs/rules/no-restricted-globals" - }, - - schema: { - type: "array", - items: { - oneOf: [ - { - type: "string" - }, - { - type: "object", - properties: { - name: { type: "string" }, - message: { type: "string" } - }, - required: ["name"], - additionalProperties: false - } - ] - }, - uniqueItems: true, - minItems: 0 - } - }, - - create(context) { - - // If no globals are restricted, we don't need to do anything - if (context.options.length === 0) { - return {}; - } - - const restrictedGlobalMessages = context.options.reduce((memo, option) => { - if (typeof option === "string") { - memo[option] = null; - } else { - memo[option.name] = option.message; - } - - return memo; - }, {}); - - /** - * Report a variable to be used as a restricted global. - * @param {Reference} reference the variable reference - * @returns {void} - * @private - */ - function reportReference(reference) { - const name = reference.identifier.name, - customMessage = restrictedGlobalMessages[name], - message = customMessage - ? CUSTOM_MESSAGE_TEMPLATE - : DEFAULT_MESSAGE_TEMPLATE; - - context.report({ - node: reference.identifier, - message, - data: { - name, - customMessage - } - }); - } - - /** - * Check if the given name is a restricted global name. - * @param {string} name name of a variable - * @returns {boolean} whether the variable is a restricted global or not - * @private - */ - function isRestricted(name) { - return Object.prototype.hasOwnProperty.call(restrictedGlobalMessages, name); - } - - return { - Program() { - const scope = context.getScope(); - - // Report variables declared elsewhere (ex: variables defined as "global" by eslint) - scope.variables.forEach(variable => { - if (!variable.defs.length && isRestricted(variable.name)) { - variable.references.forEach(reportReference); - } - }); - - // Report variables not declared at all - scope.through.forEach(reference => { - if (isRestricted(reference.identifier.name)) { - reportReference(reference); - } - }); - - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-restricted-imports.js b/tools/node_modules/eslint/lib/rules/no-restricted-imports.js deleted file mode 100644 index b8917ee9c563d1..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-restricted-imports.js +++ /dev/null @@ -1,282 +0,0 @@ -/** - * @fileoverview Restrict usage of specified node imports. - * @author Guy Ellis - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const DEFAULT_MESSAGE_TEMPLATE = "'{{importSource}}' import is restricted from being used."; -const CUSTOM_MESSAGE_TEMPLATE = "'{{importSource}}' import is restricted from being used. {{customMessage}}"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -const ignore = require("ignore"); - -const arrayOfStrings = { - type: "array", - items: { type: "string" }, - uniqueItems: true -}; - -const arrayOfStringsOrObjects = { - type: "array", - items: { - anyOf: [ - { type: "string" }, - { - type: "object", - properties: { - name: { type: "string" }, - message: { - type: "string", - minLength: 1 - }, - importNames: { - type: "array", - items: { - type: "string" - } - } - }, - additionalProperties: false, - required: ["name"] - } - ] - }, - uniqueItems: true -}; - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow specified modules when loaded by `import`", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/no-restricted-imports" - }, - - schema: { - anyOf: [ - arrayOfStringsOrObjects, - { - type: "array", - items: { - type: "object", - properties: { - paths: arrayOfStringsOrObjects, - patterns: arrayOfStrings - }, - additionalProperties: false - }, - additionalItems: false - } - ] - } - }, - - create(context) { - const options = Array.isArray(context.options) ? context.options : []; - const isPathAndPatternsObject = - typeof options[0] === "object" && - (Object.prototype.hasOwnProperty.call(options[0], "paths") || Object.prototype.hasOwnProperty.call(options[0], "patterns")); - - const restrictedPaths = (isPathAndPatternsObject ? options[0].paths : context.options) || []; - const restrictedPatterns = (isPathAndPatternsObject ? options[0].patterns : []) || []; - - const restrictedPathMessages = restrictedPaths.reduce((memo, importSource) => { - if (typeof importSource === "string") { - memo[importSource] = { message: null }; - } else { - memo[importSource.name] = { - message: importSource.message, - importNames: importSource.importNames - }; - } - return memo; - }, {}); - - // if no imports are restricted we don"t need to check - if (Object.keys(restrictedPaths).length === 0 && restrictedPatterns.length === 0) { - return {}; - } - - const restrictedPatternsMatcher = ignore().add(restrictedPatterns); - - /** - * Checks to see if "*" is being used to import everything. - * @param {Set.} importNames - Set of import names that are being imported - * @returns {boolean} whether everything is imported or not - */ - function isEverythingImported(importNames) { - return importNames.has("*"); - } - - /** - * Report a restricted path. - * @param {node} node representing the restricted path reference - * @returns {void} - * @private - */ - function reportPath(node) { - const importSource = node.source.value.trim(); - const customMessage = restrictedPathMessages[importSource] && restrictedPathMessages[importSource].message; - const message = customMessage - ? CUSTOM_MESSAGE_TEMPLATE - : DEFAULT_MESSAGE_TEMPLATE; - - context.report({ - node, - message, - data: { - importSource, - customMessage - } - }); - } - - /** - * Report a restricted path specifically for patterns. - * @param {node} node - representing the restricted path reference - * @returns {void} - * @private - */ - function reportPathForPatterns(node) { - const importSource = node.source.value.trim(); - - context.report({ - node, - message: "'{{importSource}}' import is restricted from being used by a pattern.", - data: { - importSource - } - }); - } - - /** - * Report a restricted path specifically when using the '*' import. - * @param {string} importSource - path of the import - * @param {node} node - representing the restricted path reference - * @returns {void} - * @private - */ - function reportPathForEverythingImported(importSource, node) { - const importNames = restrictedPathMessages[importSource].importNames; - - context.report({ - node, - message: "* import is invalid because '{{importNames}}' from '{{importSource}}' is restricted.", - data: { - importSource, - importNames - } - }); - } - - /** - * Check if the given importSource is restricted because '*' is being imported. - * @param {string} importSource - path of the import - * @param {Set.} importNames - Set of import names that are being imported - * @returns {boolean} whether the path is restricted - * @private - */ - function isRestrictedForEverythingImported(importSource, importNames) { - return Object.prototype.hasOwnProperty.call(restrictedPathMessages, importSource) && - restrictedPathMessages[importSource].importNames && - isEverythingImported(importNames); - } - - /** - * Check if the given importNames are restricted given a list of restrictedImportNames. - * @param {Set.} importNames - Set of import names that are being imported - * @param {string[]} restrictedImportNames - array of import names that are restricted for this import - * @returns {boolean} whether the objectName is restricted - * @private - */ - function isRestrictedObject(importNames, restrictedImportNames) { - return restrictedImportNames.some(restrictedObjectName => ( - importNames.has(restrictedObjectName) - )); - } - - /** - * Check if the given importSource is a restricted path. - * @param {string} importSource - path of the import - * @param {Set.} importNames - Set of import names that are being imported - * @returns {boolean} whether the variable is a restricted path or not - * @private - */ - function isRestrictedPath(importSource, importNames) { - let isRestricted = false; - - if (Object.prototype.hasOwnProperty.call(restrictedPathMessages, importSource)) { - if (restrictedPathMessages[importSource].importNames) { - isRestricted = isRestrictedObject(importNames, restrictedPathMessages[importSource].importNames); - } else { - isRestricted = true; - } - } - - return isRestricted; - } - - /** - * Check if the given importSource is restricted by a pattern. - * @param {string} importSource - path of the import - * @returns {boolean} whether the variable is a restricted pattern or not - * @private - */ - function isRestrictedPattern(importSource) { - return restrictedPatterns.length > 0 && restrictedPatternsMatcher.ignores(importSource); - } - - /** - * Checks a node to see if any problems should be reported. - * @param {ASTNode} node The node to check. - * @returns {void} - * @private - */ - function checkNode(node) { - const importSource = node.source.value.trim(); - const importNames = node.specifiers ? node.specifiers.reduce((set, specifier) => { - if (specifier.type === "ImportDefaultSpecifier") { - set.add("default"); - } else if (specifier.type === "ImportNamespaceSpecifier") { - set.add("*"); - } else if (specifier.imported) { - set.add(specifier.imported.name); - } else if (specifier.local) { - set.add(specifier.local.name); - } - return set; - }, new Set()) : new Set(); - - if (isRestrictedForEverythingImported(importSource, importNames)) { - reportPathForEverythingImported(importSource, node); - } - - if (isRestrictedPath(importSource, importNames)) { - reportPath(node); - } - if (isRestrictedPattern(importSource)) { - reportPathForPatterns(node); - } - } - - return { - ImportDeclaration: checkNode, - ExportNamedDeclaration(node) { - if (node.source) { - checkNode(node); - } - }, - ExportAllDeclaration: checkNode - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-restricted-modules.js b/tools/node_modules/eslint/lib/rules/no-restricted-modules.js deleted file mode 100644 index ef8748a7d04baf..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-restricted-modules.js +++ /dev/null @@ -1,180 +0,0 @@ -/** - * @fileoverview Restrict usage of specified node modules. - * @author Christian Schulz - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const DEFAULT_MESSAGE_TEMPLATE = "'{{moduleName}}' module is restricted from being used."; -const CUSTOM_MESSAGE_TEMPLATE = "'{{moduleName}}' module is restricted from being used. {{customMessage}}"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -const ignore = require("ignore"); - -const arrayOfStrings = { - type: "array", - items: { type: "string" }, - uniqueItems: true -}; - -const arrayOfStringsOrObjects = { - type: "array", - items: { - anyOf: [ - { type: "string" }, - { - type: "object", - properties: { - name: { type: "string" }, - message: { - type: "string", - minLength: 1 - } - }, - additionalProperties: false, - required: ["name"] - } - ] - }, - uniqueItems: true -}; - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow specified modules when loaded by `require`", - category: "Node.js and CommonJS", - recommended: false, - url: "https://eslint.org/docs/rules/no-restricted-modules" - }, - - schema: { - anyOf: [ - arrayOfStringsOrObjects, - { - type: "array", - items: { - type: "object", - properties: { - paths: arrayOfStringsOrObjects, - patterns: arrayOfStrings - }, - additionalProperties: false - }, - additionalItems: false - } - ] - } - }, - - create(context) { - const options = Array.isArray(context.options) ? context.options : []; - const isPathAndPatternsObject = - typeof options[0] === "object" && - (Object.prototype.hasOwnProperty.call(options[0], "paths") || Object.prototype.hasOwnProperty.call(options[0], "patterns")); - - const restrictedPaths = (isPathAndPatternsObject ? options[0].paths : context.options) || []; - const restrictedPatterns = (isPathAndPatternsObject ? options[0].patterns : []) || []; - - const restrictedPathMessages = restrictedPaths.reduce((memo, importName) => { - if (typeof importName === "string") { - memo[importName] = null; - } else { - memo[importName.name] = importName.message; - } - return memo; - }, {}); - - // if no imports are restricted we don"t need to check - if (Object.keys(restrictedPaths).length === 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. - * @returns {boolean} If the node is a string literal. - */ - function isString(node) { - return node && node.type === "Literal" && typeof node.value === "string"; - } - - /** - * Function to check if a node is a require call. - * @param {ASTNode} node The node to check. - * @returns {boolean} If the node is a require call. - */ - function isRequireCall(node) { - return node.callee.type === "Identifier" && node.callee.name === "require"; - } - - /** - * Report a restricted path. - * @param {node} node representing the restricted path reference - * @returns {void} - * @private - */ - function reportPath(node) { - const moduleName = node.arguments[0].value.trim(); - const customMessage = restrictedPathMessages[moduleName]; - const message = customMessage - ? CUSTOM_MESSAGE_TEMPLATE - : DEFAULT_MESSAGE_TEMPLATE; - - context.report({ - node, - message, - data: { - moduleName, - customMessage - } - }); - } - - /** - * Check if the given name is a restricted path name - * @param {string} name name of a variable - * @returns {boolean} whether the variable is a restricted path or not - * @private - */ - function isRestrictedPath(name) { - return Object.prototype.hasOwnProperty.call(restrictedPathMessages, name); - } - - return { - CallExpression(node) { - if (isRequireCall(node)) { - - // 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 (isRestrictedPath(moduleName)) { - reportPath(node); - } - - 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/node_modules/eslint/lib/rules/no-restricted-properties.js b/tools/node_modules/eslint/lib/rules/no-restricted-properties.js deleted file mode 100644 index eede6ad1c161dd..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-restricted-properties.js +++ /dev/null @@ -1,176 +0,0 @@ -/** - * @fileoverview Rule to disallow certain object properties - * @author Will Klein & Eli White - */ - -"use strict"; - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow certain properties on certain objects", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-restricted-properties" - }, - - schema: { - type: "array", - items: { - anyOf: [ // `object` and `property` are both optional, but at least one of them must be provided. - { - type: "object", - properties: { - object: { - type: "string" - }, - property: { - type: "string" - }, - message: { - type: "string" - } - }, - additionalProperties: false, - required: ["object"] - }, - { - type: "object", - properties: { - object: { - type: "string" - }, - property: { - type: "string" - }, - message: { - type: "string" - } - }, - additionalProperties: false, - required: ["property"] - } - ] - }, - uniqueItems: true - } - }, - - create(context) { - const restrictedCalls = context.options; - - if (restrictedCalls.length === 0) { - return {}; - } - - const restrictedProperties = new Map(); - const globallyRestrictedObjects = new Map(); - const globallyRestrictedProperties = new Map(); - - restrictedCalls.forEach(option => { - const objectName = option.object; - const propertyName = option.property; - - if (typeof objectName === "undefined") { - globallyRestrictedProperties.set(propertyName, { message: option.message }); - } else if (typeof propertyName === "undefined") { - globallyRestrictedObjects.set(objectName, { message: option.message }); - } else { - if (!restrictedProperties.has(objectName)) { - restrictedProperties.set(objectName, new Map()); - } - - restrictedProperties.get(objectName).set(propertyName, { - message: option.message - }); - } - }); - - /** - * Checks to see whether a property access is restricted, and reports it if so. - * @param {ASTNode} node The node to report - * @param {string} objectName The name of the object - * @param {string} propertyName The name of the property - * @returns {undefined} - */ - function checkPropertyAccess(node, objectName, propertyName) { - if (propertyName === null) { - return; - } - const matchedObject = restrictedProperties.get(objectName); - const matchedObjectProperty = matchedObject ? matchedObject.get(propertyName) : globallyRestrictedObjects.get(objectName); - const globalMatchedProperty = globallyRestrictedProperties.get(propertyName); - - if (matchedObjectProperty) { - const message = matchedObjectProperty.message ? ` ${matchedObjectProperty.message}` : ""; - - context.report({ - node, - // eslint-disable-next-line eslint-plugin/report-message-format - 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, - // eslint-disable-next-line eslint-plugin/report-message-format - message: "'{{propertyName}}' is restricted from being used.{{message}}", - data: { - propertyName, - message - } - }); - } - } - - /** - * Checks property accesses in a destructuring assignment expression, e.g. `var foo; ({foo} = bar);` - * @param {ASTNode} node An AssignmentExpression or AssignmentPattern node - * @returns {undefined} - */ - function checkDestructuringAssignment(node) { - if (node.right.type === "Identifier") { - const objectName = node.right.name; - - if (node.left.type === "ObjectPattern") { - node.left.properties.forEach(property => { - checkPropertyAccess(node.left, objectName, astUtils.getStaticPropertyName(property)); - }); - } - } - } - - return { - MemberExpression(node) { - checkPropertyAccess(node, node.object && node.object.name, astUtils.getStaticPropertyName(node)); - }, - VariableDeclarator(node) { - if (node.init && node.init.type === "Identifier") { - const objectName = node.init.name; - - if (node.id.type === "ObjectPattern") { - node.id.properties.forEach(property => { - checkPropertyAccess(node.id, objectName, astUtils.getStaticPropertyName(property)); - }); - } - } - }, - AssignmentExpression: checkDestructuringAssignment, - AssignmentPattern: checkDestructuringAssignment - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-restricted-syntax.js b/tools/node_modules/eslint/lib/rules/no-restricted-syntax.js deleted file mode 100644 index 74eea1478911aa..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-restricted-syntax.js +++ /dev/null @@ -1,65 +0,0 @@ -/** - * @fileoverview Rule to flag use of certain node types - * @author Burak Yigit Kaya - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow specified syntax", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/no-restricted-syntax" - }, - - schema: { - type: "array", - items: [{ - oneOf: [ - { - type: "string" - }, - { - type: "object", - properties: { - selector: { type: "string" }, - message: { type: "string" } - }, - required: ["selector"], - additionalProperties: false - } - ] - }], - uniqueItems: true, - minItems: 0 - } - }, - - create(context) { - return context.options.reduce((result, selectorOrObject) => { - const isStringFormat = (typeof selectorOrObject === "string"); - const hasCustomMessage = !isStringFormat && Boolean(selectorOrObject.message); - - const selector = isStringFormat ? selectorOrObject : selectorOrObject.selector; - const message = hasCustomMessage ? selectorOrObject.message : "Using '{{selector}}' is not allowed."; - - return Object.assign(result, { - [selector](node) { - context.report({ - node, - message, - data: hasCustomMessage ? {} : { selector } - }); - } - }); - }, {}); - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-return-assign.js b/tools/node_modules/eslint/lib/rules/no-return-assign.js deleted file mode 100644 index b3c39ea2b8c4b2..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-return-assign.js +++ /dev/null @@ -1,75 +0,0 @@ -/** - * @fileoverview Rule to flag when return statement contains assignment - * @author Ilya Volodin - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const SENTINEL_TYPE = /^(?:[a-zA-Z]+?Statement|ArrowFunctionExpression|FunctionExpression|ClassExpression)$/; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow assignment operators in `return` statements", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-return-assign" - }, - - schema: [ - { - enum: ["except-parens", "always"] - } - ] - }, - - create(context) { - const always = (context.options[0] || "except-parens") !== "except-parens"; - const sourceCode = context.getSourceCode(); - - return { - AssignmentExpression(node) { - if (!always && astUtils.isParenthesised(sourceCode, node)) { - return; - } - - let currentChild = node; - let parent = currentChild.parent; - - // Find ReturnStatement or ArrowFunctionExpression in ancestors. - while (parent && !SENTINEL_TYPE.test(parent.type)) { - currentChild = parent; - parent = parent.parent; - } - - // Reports. - if (parent && parent.type === "ReturnStatement") { - context.report({ - node: parent, - message: "Return statement should not contain assignment." - }); - } else if (parent && parent.type === "ArrowFunctionExpression" && parent.body === currentChild) { - context.report({ - node: parent, - message: "Arrow function should not return assignment." - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-return-await.js b/tools/node_modules/eslint/lib/rules/no-return-await.js deleted file mode 100644 index 24cb45ee5a7e52..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-return-await.js +++ /dev/null @@ -1,101 +0,0 @@ -/** - * @fileoverview Disallows unnecessary `return await` - * @author Jordan Harband - */ -"use strict"; - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -const message = "Redundant use of `await` on a return value."; - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow unnecessary `return await`", - category: "Best Practices", - - recommended: false, - - url: "https://eslint.org/docs/rules/no-return-await" - }, - - fixable: null, - - 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/node_modules/eslint/lib/rules/no-script-url.js b/tools/node_modules/eslint/lib/rules/no-script-url.js deleted file mode 100644 index 40e9bfe8b27544..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-script-url.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * @fileoverview Rule to flag when using javascript: urls - * @author Ilya Volodin - */ -/* jshint scripturl: true */ -/* eslint no-script-url: 0 */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow `javascript:` urls", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-script-url" - }, - - schema: [] - }, - - create(context) { - - return { - - Literal(node) { - if (node.value && typeof node.value === "string") { - const value = node.value.toLowerCase(); - - if (value.indexOf("javascript:") === 0) { - context.report({ node, message: "Script URL is a form of eval." }); - } - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-self-assign.js b/tools/node_modules/eslint/lib/rules/no-self-assign.js deleted file mode 100644 index 8bc7afbe38e9b8..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-self-assign.js +++ /dev/null @@ -1,219 +0,0 @@ -/** - * @fileoverview Rule to disallow assignments where both sides are exactly the same - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const SPACES = /\s+/g; - -/** - * Checks whether the property of 2 given member expression nodes are the same - * property or not. - * - * @param {ASTNode} left - A member expression node to check. - * @param {ASTNode} right - Another member expression node to check. - * @returns {boolean} `true` if the member expressions have the same property. - */ -function isSameProperty(left, right) { - if (left.property.type === "Identifier" && - left.property.type === right.property.type && - left.property.name === right.property.name && - left.computed === right.computed - ) { - return true; - } - - const lname = astUtils.getStaticPropertyName(left); - const rname = astUtils.getStaticPropertyName(right); - - return lname !== null && lname === rname; -} - -/** - * Checks whether 2 given member expression nodes are the reference to the same - * property or not. - * - * @param {ASTNode} left - A member expression node to check. - * @param {ASTNode} right - Another member expression node to check. - * @returns {boolean} `true` if the member expressions are the reference to the - * same property or not. - */ -function isSameMember(left, right) { - if (!isSameProperty(left, right)) { - return false; - } - - const lobj = left.object; - const robj = right.object; - - if (lobj.type !== robj.type) { - return false; - } - if (lobj.type === "MemberExpression") { - return isSameMember(lobj, robj); - } - return lobj.type === "Identifier" && lobj.name === robj.name; -} - -/** - * Traverses 2 Pattern nodes in parallel, then reports self-assignments. - * - * @param {ASTNode|null} left - A left node to traverse. This is a Pattern or - * a Property. - * @param {ASTNode|null} right - A right node to traverse. This is a Pattern or - * a Property. - * @param {boolean} props - The flag to check member expressions as well. - * @param {Function} report - A callback function to report. - * @returns {void} - */ -function eachSelfAssignment(left, right, props, report) { - if (!left || !right) { - - // do nothing - } else if ( - left.type === "Identifier" && - right.type === "Identifier" && - left.name === right.name - ) { - report(right); - } else if ( - left.type === "ArrayPattern" && - right.type === "ArrayExpression" - ) { - const end = Math.min(left.elements.length, right.elements.length); - - for (let i = 0; i < end; ++i) { - const rightElement = right.elements[i]; - - eachSelfAssignment(left.elements[i], rightElement, props, report); - - // After a spread element, those indices are unknown. - if (rightElement && rightElement.type === "SpreadElement") { - break; - } - } - } else if ( - left.type === "RestElement" && - right.type === "SpreadElement" - ) { - eachSelfAssignment(left.argument, right.argument, props, report); - } else if ( - left.type === "ObjectPattern" && - right.type === "ObjectExpression" && - right.properties.length >= 1 - ) { - - /* - * Gets the index of the last spread property. - * It's possible to overwrite properties followed by it. - */ - let startJ = 0; - - for (let i = right.properties.length - 1; i >= 0; --i) { - const propType = right.properties[i].type; - - if (propType === "SpreadElement" || propType === "ExperimentalSpreadProperty") { - startJ = i + 1; - break; - } - } - - for (let i = 0; i < left.properties.length; ++i) { - for (let j = startJ; j < right.properties.length; ++j) { - eachSelfAssignment( - left.properties[i], - right.properties[j], - props, - report - ); - } - } - } else if ( - left.type === "Property" && - right.type === "Property" && - !left.computed && - !right.computed && - right.kind === "init" && - !right.method && - left.key.name === right.key.name - ) { - eachSelfAssignment(left.value, right.value, props, report); - } else if ( - props && - left.type === "MemberExpression" && - right.type === "MemberExpression" && - isSameMember(left, right) - ) { - report(right); - } -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow assignments where both sides are exactly the same", - category: "Best Practices", - recommended: true, - url: "https://eslint.org/docs/rules/no-self-assign" - }, - - schema: [ - { - type: "object", - properties: { - props: { - type: "boolean", - default: true - } - }, - additionalProperties: false - } - ] - }, - - create(context) { - const sourceCode = context.getSourceCode(); - const [{ props = true } = {}] = context.options; - - /** - * Reports a given node as self assignments. - * - * @param {ASTNode} node - A node to report. This is an Identifier node. - * @returns {void} - */ - function report(node) { - context.report({ - node, - message: "'{{name}}' is assigned to itself.", - data: { - name: sourceCode.getText(node).replace(SPACES, "") - } - }); - } - - return { - AssignmentExpression(node) { - if (node.operator === "=") { - eachSelfAssignment(node.left, node.right, props, report); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-self-compare.js b/tools/node_modules/eslint/lib/rules/no-self-compare.js deleted file mode 100644 index 8986240ec5c842..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-self-compare.js +++ /dev/null @@ -1,56 +0,0 @@ -/** - * @fileoverview Rule to flag comparison where left part is the same as the right - * part. - * @author Ilya Volodin - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow comparisons where both sides are exactly the same", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-self-compare" - }, - - schema: [] - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - /** - * Determines whether two nodes are composed of the same tokens. - * @param {ASTNode} nodeA The first node - * @param {ASTNode} nodeB The second node - * @returns {boolean} true if the nodes have identical token representations - */ - function hasSameTokens(nodeA, nodeB) { - const tokensA = sourceCode.getTokens(nodeA); - const tokensB = sourceCode.getTokens(nodeB); - - return tokensA.length === tokensB.length && - tokensA.every((token, index) => token.type === tokensB[index].type && token.value === tokensB[index].value); - } - - return { - - BinaryExpression(node) { - const operators = new Set(["===", "==", "!==", "!=", ">", "<", ">=", "<="]); - - if (operators.has(node.operator) && hasSameTokens(node.left, node.right)) { - context.report({ node, message: "Comparing to itself is potentially pointless." }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-sequences.js b/tools/node_modules/eslint/lib/rules/no-sequences.js deleted file mode 100644 index 2570912f348e91..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-sequences.js +++ /dev/null @@ -1,115 +0,0 @@ -/** - * @fileoverview Rule to flag use of comma operator - * @author Brandon Mills - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow comma operators", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-sequences" - }, - - schema: [] - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - /** - * Parts of the grammar that are required to have parens. - */ - const parenthesized = { - DoWhileStatement: "test", - IfStatement: "test", - SwitchStatement: "discriminant", - WhileStatement: "test", - WithStatement: "object", - ArrowFunctionExpression: "body" - - /* - * Omitting CallExpression - commas are parsed as argument separators - * Omitting NewExpression - commas are parsed as argument separators - * Omitting ForInStatement - parts aren't individually parenthesised - * Omitting ForStatement - parts aren't individually parenthesised - */ - }; - - /** - * Determines whether a node is required by the grammar to be wrapped in - * parens, e.g. the test of an if statement. - * @param {ASTNode} node - The AST node - * @returns {boolean} True if parens around node belong to parent node. - */ - function requiresExtraParens(node) { - return node.parent && parenthesized[node.parent.type] && - node === node.parent[parenthesized[node.parent.type]]; - } - - /** - * Check if a node is wrapped in parens. - * @param {ASTNode} node - The AST node - * @returns {boolean} True if the node has a paren on each side. - */ - function isParenthesised(node) { - return astUtils.isParenthesised(sourceCode, node); - } - - /** - * Check if a node is wrapped in two levels of parens. - * @param {ASTNode} node - The AST node - * @returns {boolean} True if two parens surround the node on each side. - */ - function isParenthesisedTwice(node) { - const previousToken = sourceCode.getTokenBefore(node, 1), - nextToken = sourceCode.getTokenAfter(node, 1); - - return isParenthesised(node) && previousToken && nextToken && - astUtils.isOpeningParenToken(previousToken) && previousToken.range[1] <= node.range[0] && - astUtils.isClosingParenToken(nextToken) && nextToken.range[0] >= node.range[1]; - } - - return { - SequenceExpression(node) { - - // Always allow sequences in for statement update - if (node.parent.type === "ForStatement" && - (node === node.parent.init || node === node.parent.update)) { - return; - } - - // Wrapping a sequence in extra parens indicates intent - if (requiresExtraParens(node)) { - if (isParenthesisedTwice(node)) { - return; - } - } else { - if (isParenthesised(node)) { - return; - } - } - - const child = sourceCode.getTokenAfter(node.expressions[0]); - - context.report({ node, loc: child.loc.start, message: "Unexpected use of comma operator." }); - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-shadow-restricted-names.js b/tools/node_modules/eslint/lib/rules/no-shadow-restricted-names.js deleted file mode 100644 index f09f3767da4257..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-shadow-restricted-names.js +++ /dev/null @@ -1,60 +0,0 @@ -/** - * @fileoverview Disallow shadowing of NaN, undefined, and Infinity (ES5 section 15.1.1) - * @author Michael Ficarra - */ -"use strict"; - -/** - * Determines if a variable safely shadows undefined. - * This is the case when a variable named `undefined` is never assigned to a value (i.e. it always shares the same value - * as the global). - * @param {eslintScope.Variable} variable The variable to check - * @returns {boolean} true if this variable safely shadows `undefined` - */ -function safelyShadowsUndefined(variable) { - return variable.name === "undefined" && - variable.references.every(ref => !ref.isWrite()) && - variable.defs.every(def => def.node.type === "VariableDeclarator" && def.node.init === null); -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow identifiers from shadowing restricted names", - category: "Variables", - recommended: false, - url: "https://eslint.org/docs/rules/no-shadow-restricted-names" - }, - - schema: [] - }, - - create(context) { - - - const RESTRICTED = new Set(["undefined", "NaN", "Infinity", "arguments", "eval"]); - - return { - "VariableDeclaration, :function, CatchClause"(node) { - for (const variable of context.getDeclaredVariables(node)) { - if (variable.defs.length > 0 && RESTRICTED.has(variable.name) && !safelyShadowsUndefined(variable)) { - context.report({ - node: variable.defs[0].name, - message: "Shadowing of global property '{{idName}}'.", - data: { - idName: variable.name - } - }); - } - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-shadow.js b/tools/node_modules/eslint/lib/rules/no-shadow.js deleted file mode 100644 index 5f617e52a74ba0..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-shadow.js +++ /dev/null @@ -1,191 +0,0 @@ -/** - * @fileoverview Rule to flag on declaring variables already declared in the outer scope - * @author Ilya Volodin - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow variable declarations from shadowing variables declared in the outer scope", - category: "Variables", - recommended: false, - url: "https://eslint.org/docs/rules/no-shadow" - }, - - schema: [ - { - type: "object", - properties: { - builtinGlobals: { type: "boolean", default: false }, - hoist: { enum: ["all", "functions", "never"], default: "functions" }, - allow: { - type: "array", - items: { - type: "string" - } - } - }, - additionalProperties: false - } - ] - }, - - create(context) { - - const options = { - builtinGlobals: context.options[0] && context.options[0].builtinGlobals, - hoist: (context.options[0] && context.options[0].hoist) || "functions", - allow: (context.options[0] && context.options[0].allow) || [] - }; - - /** - * Check if variable name is allowed. - * - * @param {ASTNode} variable The variable to check. - * @returns {boolean} Whether or not the variable name is allowed. - */ - function isAllowed(variable) { - return options.allow.indexOf(variable.name) !== -1; - } - - /** - * Checks if a variable of the class name in the class scope of ClassDeclaration. - * - * ClassDeclaration creates two variables of its name into its outer scope and its class scope. - * So we should ignore the variable in the class scope. - * - * @param {Object} variable The variable to check. - * @returns {boolean} Whether or not the variable of the class name in the class scope of ClassDeclaration. - */ - function isDuplicatedClassNameVariable(variable) { - const block = variable.scope.block; - - return block.type === "ClassDeclaration" && block.id === variable.identifiers[0]; - } - - /** - * Checks if a variable is inside the initializer of scopeVar. - * - * To avoid reporting at declarations such as `var a = function a() {};`. - * But it should report `var a = function(a) {};` or `var a = function() { function a() {} };`. - * - * @param {Object} variable The variable to check. - * @param {Object} scopeVar The scope variable to look for. - * @returns {boolean} Whether or not the variable is inside initializer of scopeVar. - */ - function isOnInitializer(variable, scopeVar) { - const outerScope = scopeVar.scope; - const outerDef = scopeVar.defs[0]; - const outer = outerDef && outerDef.parent && outerDef.parent.range; - const innerScope = variable.scope; - const innerDef = variable.defs[0]; - const inner = innerDef && innerDef.name.range; - - return ( - outer && - inner && - outer[0] < inner[0] && - inner[1] < outer[1] && - ((innerDef.type === "FunctionName" && innerDef.node.type === "FunctionExpression") || innerDef.node.type === "ClassExpression") && - outerScope === innerScope.upper - ); - } - - /** - * Get a range of a variable's identifier node. - * @param {Object} variable The variable to get. - * @returns {Array|undefined} The range of the variable's identifier node. - */ - function getNameRange(variable) { - const def = variable.defs[0]; - - return def && def.name.range; - } - - /** - * Checks if a variable is in TDZ of scopeVar. - * @param {Object} variable The variable to check. - * @param {Object} scopeVar The variable of TDZ. - * @returns {boolean} Whether or not the variable is in TDZ of scopeVar. - */ - function isInTdz(variable, scopeVar) { - const outerDef = scopeVar.defs[0]; - const inner = getNameRange(variable); - const outer = getNameRange(scopeVar); - - return ( - inner && - outer && - inner[1] < outer[0] && - - // Excepts FunctionDeclaration if is {"hoist":"function"}. - (options.hoist !== "functions" || !outerDef || outerDef.node.type !== "FunctionDeclaration") - ); - } - - /** - * Checks the current context for shadowed variables. - * @param {Scope} scope - Fixme - * @returns {void} - */ - function checkForShadows(scope) { - const variables = scope.variables; - - for (let i = 0; i < variables.length; ++i) { - const variable = variables[i]; - - // Skips "arguments" or variables of a class name in the class scope of ClassDeclaration. - if (variable.identifiers.length === 0 || - isDuplicatedClassNameVariable(variable) || - isAllowed(variable) - ) { - continue; - } - - // Gets shadowed variable. - const shadowed = astUtils.getVariableByName(scope.upper, variable.name); - - if (shadowed && - (shadowed.identifiers.length > 0 || (options.builtinGlobals && "writeable" in shadowed)) && - !isOnInitializer(variable, shadowed) && - !(options.hoist !== "all" && isInTdz(variable, shadowed)) - ) { - context.report({ - node: variable.identifiers[0], - message: "'{{name}}' is already declared in the upper scope.", - data: variable - }); - } - } - } - - return { - "Program:exit"() { - const globalScope = context.getScope(); - const stack = globalScope.childScopes.slice(); - - while (stack.length) { - const scope = stack.pop(); - - stack.push(...scope.childScopes); - checkForShadows(scope); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-spaced-func.js b/tools/node_modules/eslint/lib/rules/no-spaced-func.js deleted file mode 100644 index 8535881f435e48..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-spaced-func.js +++ /dev/null @@ -1,79 +0,0 @@ -/** - * @fileoverview Rule to check that spaced function application - * @author Matt DuVall - * @deprecated in ESLint v3.3.0 - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "disallow spacing between function identifiers and their applications (deprecated)", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/no-spaced-func" - }, - - deprecated: true, - - replacedBy: ["func-call-spacing"], - - fixable: "whitespace", - schema: [] - }, - - create(context) { - - const sourceCode = context.getSourceCode(); - - /** - * Check if open space is present in a function name - * @param {ASTNode} node node to evaluate - * @returns {void} - * @private - */ - function detectOpenSpaces(node) { - const lastCalleeToken = sourceCode.getLastToken(node.callee); - let prevToken = lastCalleeToken, - parenToken = sourceCode.getTokenAfter(lastCalleeToken); - - // advances to an open parenthesis. - while ( - parenToken && - parenToken.range[1] < node.range[1] && - parenToken.value !== "(" - ) { - prevToken = parenToken; - parenToken = sourceCode.getTokenAfter(parenToken); - } - - // look for a space between the callee and the open paren - if (parenToken && - parenToken.range[1] < node.range[1] && - sourceCode.isSpaceBetweenTokens(prevToken, parenToken) - ) { - context.report({ - node, - loc: lastCalleeToken.loc.start, - message: "Unexpected space between function name and paren.", - fix(fixer) { - return fixer.removeRange([prevToken.range[1], parenToken.range[0]]); - } - }); - } - } - - return { - CallExpression: detectOpenSpaces, - NewExpression: detectOpenSpaces - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-sparse-arrays.js b/tools/node_modules/eslint/lib/rules/no-sparse-arrays.js deleted file mode 100644 index 985109c36b267d..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-sparse-arrays.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * @fileoverview Disallow sparse arrays - * @author Nicholas C. Zakas - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow sparse arrays", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-sparse-arrays" - }, - - schema: [] - }, - - create(context) { - - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - - ArrayExpression(node) { - - const emptySpot = node.elements.indexOf(null) > -1; - - if (emptySpot) { - context.report({ node, message: "Unexpected comma in middle of array." }); - } - } - - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-sync.js b/tools/node_modules/eslint/lib/rules/no-sync.js deleted file mode 100644 index 578bac96d3d061..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-sync.js +++ /dev/null @@ -1,57 +0,0 @@ -/** - * @fileoverview Rule to check for properties whose identifier ends with the string Sync - * @author Matt DuVall - */ - -/* jshint node:true */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow synchronous methods", - category: "Node.js and CommonJS", - recommended: false, - url: "https://eslint.org/docs/rules/no-sync" - }, - - schema: [ - { - type: "object", - properties: { - allowAtRootLevel: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ] - }, - - create(context) { - const selector = context.options[0] && context.options[0].allowAtRootLevel - ? ":function MemberExpression[property.name=/.*Sync$/]" - : "MemberExpression[property.name=/.*Sync$/]"; - - return { - [selector](node) { - context.report({ - node, - message: "Unexpected sync method: '{{propertyName}}'.", - data: { - propertyName: node.property.name - } - }); - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-tabs.js b/tools/node_modules/eslint/lib/rules/no-tabs.js deleted file mode 100644 index 91fb000796f369..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-tabs.js +++ /dev/null @@ -1,68 +0,0 @@ -/** - * @fileoverview Rule to check for tabs inside a file - * @author Gyandeep Singh - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const tabRegex = /\t+/g; -const anyNonWhitespaceRegex = /\S/; - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "disallow all tabs", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/no-tabs" - }, - schema: [{ - type: "object", - properties: { - allowIndentationTabs: { - type: "boolean", - default: false - } - }, - additionalProperties: false - }] - }, - - create(context) { - const sourceCode = context.getSourceCode(); - const allowIndentationTabs = context.options && context.options[0] && context.options[0].allowIndentationTabs; - - return { - Program(node) { - sourceCode.getLines().forEach((line, index) => { - let match; - - while ((match = tabRegex.exec(line)) !== null) { - if (allowIndentationTabs && !anyNonWhitespaceRegex.test(line.slice(0, match.index))) { - continue; - } - - context.report({ - node, - loc: { - line: index + 1, - column: match.index - }, - message: "Unexpected tab character." - }); - } - }); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-template-curly-in-string.js b/tools/node_modules/eslint/lib/rules/no-template-curly-in-string.js deleted file mode 100644 index c286ec69000d60..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-template-curly-in-string.js +++ /dev/null @@ -1,40 +0,0 @@ -/** - * @fileoverview Warn when using template string syntax in regular strings - * @author Jeroen Engels - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow template literal placeholder syntax in regular strings", - category: "Possible Errors", - recommended: false, - url: "https://eslint.org/docs/rules/no-template-curly-in-string" - }, - - schema: [] - }, - - create(context) { - const regex = /\$\{[^}]+\}/; - - return { - Literal(node) { - if (typeof node.value === "string" && regex.test(node.value)) { - context.report({ - node, - message: "Unexpected template string expression." - }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-ternary.js b/tools/node_modules/eslint/lib/rules/no-ternary.js deleted file mode 100644 index 890f2abfa0c59a..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-ternary.js +++ /dev/null @@ -1,37 +0,0 @@ -/** - * @fileoverview Rule to flag use of ternary operators. - * @author Ian Christian Myers - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow ternary operators", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/no-ternary" - }, - - schema: [] - }, - - create(context) { - - return { - - ConditionalExpression(node) { - context.report({ node, message: "Ternary operator used." }); - } - - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-this-before-super.js b/tools/node_modules/eslint/lib/rules/no-this-before-super.js deleted file mode 100644 index bca379bf971b80..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-this-before-super.js +++ /dev/null @@ -1,301 +0,0 @@ -/** - * @fileoverview A rule to disallow using `this`/`super` before `super()`. - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks whether or not a given node is a constructor. - * @param {ASTNode} node - A node to check. This node type is one of - * `Program`, `FunctionDeclaration`, `FunctionExpression`, and - * `ArrowFunctionExpression`. - * @returns {boolean} `true` if the node is a constructor. - */ -function isConstructorFunction(node) { - return ( - node.type === "FunctionExpression" && - node.parent.type === "MethodDefinition" && - node.parent.kind === "constructor" - ); -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow `this`/`super` before calling `super()` in constructors", - category: "ECMAScript 6", - recommended: true, - url: "https://eslint.org/docs/rules/no-this-before-super" - }, - - schema: [] - }, - - create(context) { - - /* - * Information for each constructor. - * - upper: Information of the upper constructor. - * - hasExtends: A flag which shows whether the owner class has a valid - * `extends` part. - * - scope: The scope of the owner class. - * - codePath: The code path of this constructor. - */ - let funcInfo = null; - - /* - * Information for each code path segment. - * Each key is the id of a code path segment. - * Each value is an object: - * - superCalled: The flag which shows `super()` called in all code paths. - * - invalidNodes: The array of invalid ThisExpression and Super nodes. - */ - let segInfoMap = Object.create(null); - - /** - * Gets whether or not `super()` is called in a given code path segment. - * @param {CodePathSegment} segment - A code path segment to get. - * @returns {boolean} `true` if `super()` is called. - */ - function isCalled(segment) { - return !segment.reachable || segInfoMap[segment.id].superCalled; - } - - /** - * Checks whether or not this is in a constructor. - * @returns {boolean} `true` if this is in a constructor. - */ - function isInConstructorOfDerivedClass() { - return Boolean(funcInfo && funcInfo.isConstructor && funcInfo.hasExtends); - } - - /** - * Checks whether or not this is before `super()` is called. - * @returns {boolean} `true` if this is before `super()` is called. - */ - function isBeforeCallOfSuper() { - return ( - isInConstructorOfDerivedClass() && - !funcInfo.codePath.currentSegments.every(isCalled) - ); - } - - /** - * Sets a given node as invalid. - * @param {ASTNode} node - A node to set as invalid. This is one of - * a ThisExpression and a Super. - * @returns {void} - */ - function setInvalid(node) { - const segments = funcInfo.codePath.currentSegments; - - for (let i = 0; i < segments.length; ++i) { - const segment = segments[i]; - - if (segment.reachable) { - segInfoMap[segment.id].invalidNodes.push(node); - } - } - } - - /** - * Sets the current segment as `super` was called. - * @returns {void} - */ - function setSuperCalled() { - const segments = funcInfo.codePath.currentSegments; - - for (let i = 0; i < segments.length; ++i) { - const segment = segments[i]; - - if (segment.reachable) { - segInfoMap[segment.id].superCalled = true; - } - } - } - - return { - - /** - * Adds information of a constructor into the stack. - * @param {CodePath} codePath - A code path which was started. - * @param {ASTNode} node - The current node. - * @returns {void} - */ - onCodePathStart(codePath, node) { - if (isConstructorFunction(node)) { - - // Class > ClassBody > MethodDefinition > FunctionExpression - const classNode = node.parent.parent.parent; - - funcInfo = { - upper: funcInfo, - isConstructor: true, - hasExtends: Boolean( - classNode.superClass && - !astUtils.isNullOrUndefined(classNode.superClass) - ), - codePath - }; - } else { - funcInfo = { - upper: funcInfo, - isConstructor: false, - hasExtends: false, - codePath - }; - } - }, - - /** - * Removes the top of stack item. - * - * And this treverses all segments of this code path then reports every - * invalid node. - * - * @param {CodePath} codePath - A code path which was ended. - * @returns {void} - */ - onCodePathEnd(codePath) { - const isDerivedClass = funcInfo.hasExtends; - - funcInfo = funcInfo.upper; - if (!isDerivedClass) { - return; - } - - codePath.traverseSegments((segment, controller) => { - const info = segInfoMap[segment.id]; - - for (let i = 0; i < info.invalidNodes.length; ++i) { - const invalidNode = info.invalidNodes[i]; - - context.report({ - message: "'{{kind}}' is not allowed before 'super()'.", - node: invalidNode, - data: { - kind: invalidNode.type === "Super" ? "super" : "this" - } - }); - } - - if (info.superCalled) { - controller.skip(); - } - }); - }, - - /** - * Initialize information of a given code path segment. - * @param {CodePathSegment} segment - A code path segment to initialize. - * @returns {void} - */ - onCodePathSegmentStart(segment) { - if (!isInConstructorOfDerivedClass()) { - return; - } - - // Initialize info. - segInfoMap[segment.id] = { - superCalled: ( - segment.prevSegments.length > 0 && - segment.prevSegments.every(isCalled) - ), - invalidNodes: [] - }; - }, - - /** - * Update information of the code path segment when a code path was - * looped. - * @param {CodePathSegment} fromSegment - The code path segment of the - * end of a loop. - * @param {CodePathSegment} toSegment - A code path segment of the head - * of a loop. - * @returns {void} - */ - onCodePathSegmentLoop(fromSegment, toSegment) { - if (!isInConstructorOfDerivedClass()) { - return; - } - - // Update information inside of the loop. - funcInfo.codePath.traverseSegments( - { first: toSegment, last: fromSegment }, - (segment, controller) => { - const info = segInfoMap[segment.id]; - - if (info.superCalled) { - info.invalidNodes = []; - controller.skip(); - } else if ( - segment.prevSegments.length > 0 && - segment.prevSegments.every(isCalled) - ) { - info.superCalled = true; - info.invalidNodes = []; - } - } - ); - }, - - /** - * Reports if this is before `super()`. - * @param {ASTNode} node - A target node. - * @returns {void} - */ - ThisExpression(node) { - if (isBeforeCallOfSuper()) { - setInvalid(node); - } - }, - - /** - * Reports if this is before `super()`. - * @param {ASTNode} node - A target node. - * @returns {void} - */ - Super(node) { - if (!astUtils.isCallee(node) && isBeforeCallOfSuper()) { - setInvalid(node); - } - }, - - /** - * Marks `super()` called. - * @param {ASTNode} node - A target node. - * @returns {void} - */ - "CallExpression:exit"(node) { - if (node.callee.type === "Super" && isBeforeCallOfSuper()) { - setSuperCalled(); - } - }, - - /** - * Resets state. - * @returns {void} - */ - "Program:exit"() { - segInfoMap = Object.create(null); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-throw-literal.js b/tools/node_modules/eslint/lib/rules/no-throw-literal.js deleted file mode 100644 index c4a6b86bfb4cc9..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-throw-literal.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * @fileoverview Rule to restrict what can be thrown as an exception. - * @author Dieter Oberkofler - */ - -"use strict"; - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow throwing literals as exceptions", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-throw-literal" - }, - - schema: [] - }, - - create(context) { - - return { - - ThrowStatement(node) { - if (!astUtils.couldBeError(node.argument)) { - context.report({ node, message: "Expected an object to be thrown." }); - } else if (node.argument.type === "Identifier") { - if (node.argument.name === "undefined") { - context.report({ node, message: "Do not throw undefined." }); - } - } - - } - - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-trailing-spaces.js b/tools/node_modules/eslint/lib/rules/no-trailing-spaces.js deleted file mode 100644 index 1f0b53aca2abad..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-trailing-spaces.js +++ /dev/null @@ -1,174 +0,0 @@ -/** - * @fileoverview Disallow trailing spaces at the end of lines. - * @author Nodeca Team - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "disallow trailing whitespace at the end of lines", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/no-trailing-spaces" - }, - - fixable: "whitespace", - - schema: [ - { - type: "object", - properties: { - skipBlankLines: { - type: "boolean", - default: false - }, - ignoreComments: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ] - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - const BLANK_CLASS = "[ \t\u00a0\u2000-\u200b\u3000]", - SKIP_BLANK = `^${BLANK_CLASS}*$`, - NONBLANK = `${BLANK_CLASS}+$`; - - const options = context.options[0] || {}, - skipBlankLines = options.skipBlankLines || false, - ignoreComments = options.ignoreComments || false; - - /** - * Report the error message - * @param {ASTNode} node node to report - * @param {int[]} location range information - * @param {int[]} fixRange Range based on the whole program - * @returns {void} - */ - function report(node, location, fixRange) { - - /* - * Passing node is a bit dirty, because message data will contain big - * text in `source`. But... who cares :) ? - * One more kludge will not make worse the bloody wizardry of this - * plugin. - */ - context.report({ - node, - loc: location, - message: "Trailing spaces not allowed.", - fix(fixer) { - return fixer.removeRange(fixRange); - } - }); - } - - /** - * Given a list of comment nodes, return the line numbers for those comments. - * @param {Array} comments An array of comment nodes. - * @returns {number[]} An array of line numbers containing comments. - */ - function getCommentLineNumbers(comments) { - const lines = new Set(); - - comments.forEach(comment => { - for (let i = comment.loc.start.line; i <= comment.loc.end.line; i++) { - lines.add(i); - } - }); - - return lines; - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - - Program: function checkTrailingSpaces(node) { - - /* - * Let's hack. Since Espree does not return whitespace nodes, - * fetch the source code and do matching via regexps. - */ - - const re = new RegExp(NONBLANK), - skipMatch = new RegExp(SKIP_BLANK), - lines = sourceCode.lines, - linebreaks = sourceCode.getText().match(astUtils.createGlobalLinebreakMatcher()), - comments = sourceCode.getAllComments(), - commentLineNumbers = getCommentLineNumbers(comments); - - let totalLength = 0, - fixRange = []; - - for (let i = 0, ii = lines.length; i < ii; i++) { - const matches = re.exec(lines[i]); - - /* - * Always add linebreak length to line length to accommodate for line break (\n or \r\n) - * Because during the fix time they also reserve one spot in the array. - * Usually linebreak length is 2 for \r\n (CRLF) and 1 for \n (LF) - */ - const linebreakLength = linebreaks && linebreaks[i] ? linebreaks[i].length : 1; - const lineLength = lines[i].length + linebreakLength; - - if (matches) { - const location = { - line: i + 1, - column: matches.index - }; - - const rangeStart = totalLength + location.column; - const rangeEnd = totalLength + lineLength - linebreakLength; - const containingNode = sourceCode.getNodeByRangeIndex(rangeStart); - - if (containingNode && containingNode.type === "TemplateElement" && - rangeStart > containingNode.parent.range[0] && - rangeEnd < containingNode.parent.range[1]) { - totalLength += lineLength; - continue; - } - - /* - * If the line has only whitespace, and skipBlankLines - * is true, don't report it - */ - if (skipBlankLines && skipMatch.test(lines[i])) { - totalLength += lineLength; - continue; - } - - fixRange = [rangeStart, rangeEnd]; - - if (!ignoreComments || !commentLineNumbers.has(location.line)) { - report(node, location, fixRange); - } - } - - totalLength += lineLength; - } - } - - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-undef-init.js b/tools/node_modules/eslint/lib/rules/no-undef-init.js deleted file mode 100644 index 67f3944d47e7f4..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-undef-init.js +++ /dev/null @@ -1,65 +0,0 @@ -/** - * @fileoverview Rule to flag when initializing to undefined - * @author Ilya Volodin - */ - -"use strict"; - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow initializing variables to `undefined`", - category: "Variables", - recommended: false, - url: "https://eslint.org/docs/rules/no-undef-init" - }, - - schema: [], - fixable: "code" - }, - - create(context) { - - const sourceCode = context.getSourceCode(); - - return { - - VariableDeclarator(node) { - const name = sourceCode.getText(node.id), - init = node.init && node.init.name, - scope = context.getScope(), - undefinedVar = astUtils.getVariableByName(scope, "undefined"), - shadowed = undefinedVar && undefinedVar.defs.length > 0; - - if (init === "undefined" && node.parent.kind !== "const" && !shadowed) { - context.report({ - node, - message: "It's not necessary to initialize '{{name}}' to undefined.", - data: { name }, - fix(fixer) { - if (node.parent.kind === "var") { - return null; - } - - if (node.id.type === "ArrayPattern" || node.id.type === "ObjectPattern") { - - // Don't fix destructuring assignment to `undefined`. - return null; - } - return fixer.removeRange([node.id.range[1], node.range[1]]); - } - }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-undef.js b/tools/node_modules/eslint/lib/rules/no-undef.js deleted file mode 100644 index 6b5140819bbd30..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-undef.js +++ /dev/null @@ -1,78 +0,0 @@ -/** - * @fileoverview Rule to flag references to undeclared variables. - * @author Mark Macdonald - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks if the given node is the argument of a typeof operator. - * @param {ASTNode} node The AST node being checked. - * @returns {boolean} Whether or not the node is the argument of a typeof operator. - */ -function hasTypeOfOperator(node) { - const parent = node.parent; - - return parent.type === "UnaryExpression" && parent.operator === "typeof"; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow the use of undeclared variables unless mentioned in `/*global */` comments", - category: "Variables", - recommended: true, - url: "https://eslint.org/docs/rules/no-undef" - }, - - schema: [ - { - type: "object", - properties: { - typeof: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - messages: { - undef: "'{{name}}' is not defined." - } - }, - - create(context) { - const options = context.options[0]; - const considerTypeOf = options && options.typeof === true || false; - - return { - "Program:exit"(/* node */) { - const globalScope = context.getScope(); - - globalScope.through.forEach(ref => { - const identifier = ref.identifier; - - if (!considerTypeOf && hasTypeOfOperator(identifier)) { - return; - } - - context.report({ - node: identifier, - messageId: "undef", - data: identifier - }); - }); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-undefined.js b/tools/node_modules/eslint/lib/rules/no-undefined.js deleted file mode 100644 index b92f6700637c30..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-undefined.js +++ /dev/null @@ -1,80 +0,0 @@ -/** - * @fileoverview Rule to flag references to the undefined variable. - * @author Michael Ficarra - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow the use of `undefined` as an identifier", - category: "Variables", - recommended: false, - url: "https://eslint.org/docs/rules/no-undefined" - }, - - schema: [] - }, - - create(context) { - - /** - * Report an invalid "undefined" identifier node. - * @param {ASTNode} node The node to report. - * @returns {void} - */ - function report(node) { - context.report({ - node, - message: "Unexpected use of undefined." - }); - } - - /** - * Checks the given scope for references to `undefined` and reports - * all references found. - * @param {eslint-scope.Scope} scope The scope to check. - * @returns {void} - */ - function checkScope(scope) { - const undefinedVar = scope.set.get("undefined"); - - if (!undefinedVar) { - return; - } - - const references = undefinedVar.references; - - const defs = undefinedVar.defs; - - // Report non-initializing references (those are covered in defs below) - references - .filter(ref => !ref.init) - .forEach(ref => report(ref.identifier)); - - defs.forEach(def => report(def.name)); - } - - return { - "Program:exit"() { - const globalScope = context.getScope(); - - const stack = [globalScope]; - - while (stack.length) { - const scope = stack.pop(); - - stack.push(...scope.childScopes); - checkScope(scope); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-underscore-dangle.js b/tools/node_modules/eslint/lib/rules/no-underscore-dangle.js deleted file mode 100644 index 3f59815b575f84..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-underscore-dangle.js +++ /dev/null @@ -1,209 +0,0 @@ -/** - * @fileoverview Rule to flag trailing underscores in variable declarations. - * @author Matt DuVall - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow dangling underscores in identifiers", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/no-underscore-dangle" - }, - - schema: [ - { - type: "object", - properties: { - allow: { - type: "array", - items: { - type: "string" - } - }, - allowAfterThis: { - type: "boolean", - default: false - }, - allowAfterSuper: { - type: "boolean", - default: false - }, - enforceInMethodNames: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ] - }, - - create(context) { - - const options = context.options[0] || {}; - const ALLOWED_VARIABLES = options.allow ? options.allow : []; - const allowAfterThis = typeof options.allowAfterThis !== "undefined" ? options.allowAfterThis : false; - const allowAfterSuper = typeof options.allowAfterSuper !== "undefined" ? options.allowAfterSuper : false; - const enforceInMethodNames = typeof options.enforceInMethodNames !== "undefined" ? options.enforceInMethodNames : false; - - //------------------------------------------------------------------------- - // Helpers - //------------------------------------------------------------------------- - - /** - * Check if identifier is present inside the allowed option - * @param {string} identifier name of the node - * @returns {boolean} true if its is present - * @private - */ - function isAllowed(identifier) { - return ALLOWED_VARIABLES.some(ident => ident === identifier); - } - - /** - * Check if identifier has a underscore at the end - * @param {ASTNode} identifier node to evaluate - * @returns {boolean} true if its is present - * @private - */ - function hasTrailingUnderscore(identifier) { - const len = identifier.length; - - return identifier !== "_" && (identifier[0] === "_" || identifier[len - 1] === "_"); - } - - /** - * Check if identifier is a special case member expression - * @param {ASTNode} identifier node to evaluate - * @returns {boolean} true if its is a special case - * @private - */ - function isSpecialCaseIdentifierForMemberExpression(identifier) { - return identifier === "__proto__"; - } - - /** - * Check if identifier is a special case variable expression - * @param {ASTNode} identifier node to evaluate - * @returns {boolean} true if its is a special case - * @private - */ - function isSpecialCaseIdentifierInVariableExpression(identifier) { - - // Checks for the underscore library usage here - return identifier === "_"; - } - - /** - * Check if function has a underscore at the end - * @param {ASTNode} node node to evaluate - * @returns {void} - * @private - */ - function checkForTrailingUnderscoreInFunctionDeclaration(node) { - if (node.id) { - const identifier = node.id.name; - - if (typeof identifier !== "undefined" && hasTrailingUnderscore(identifier) && !isAllowed(identifier)) { - context.report({ - node, - message: "Unexpected dangling '_' in '{{identifier}}'.", - data: { - identifier - } - }); - } - } - } - - /** - * Check if variable expression has a underscore at the end - * @param {ASTNode} node node to evaluate - * @returns {void} - * @private - */ - function checkForTrailingUnderscoreInVariableExpression(node) { - const identifier = node.id.name; - - if (typeof identifier !== "undefined" && hasTrailingUnderscore(identifier) && - !isSpecialCaseIdentifierInVariableExpression(identifier) && !isAllowed(identifier)) { - context.report({ - node, - message: "Unexpected dangling '_' in '{{identifier}}'.", - data: { - identifier - } - }); - } - } - - /** - * Check if member expression has a underscore at the end - * @param {ASTNode} node node to evaluate - * @returns {void} - * @private - */ - function checkForTrailingUnderscoreInMemberExpression(node) { - const identifier = node.property.name, - isMemberOfThis = node.object.type === "ThisExpression", - isMemberOfSuper = node.object.type === "Super"; - - if (typeof identifier !== "undefined" && hasTrailingUnderscore(identifier) && - !(isMemberOfThis && allowAfterThis) && - !(isMemberOfSuper && allowAfterSuper) && - !isSpecialCaseIdentifierForMemberExpression(identifier) && !isAllowed(identifier)) { - context.report({ - node, - message: "Unexpected dangling '_' in '{{identifier}}'.", - data: { - identifier - } - }); - } - } - - /** - * Check if method declaration or method property has a underscore at the end - * @param {ASTNode} node node to evaluate - * @returns {void} - * @private - */ - function checkForTrailingUnderscoreInMethod(node) { - const identifier = node.key.name; - const isMethod = node.type === "MethodDefinition" || node.type === "Property" && node.method; - - if (typeof identifier !== "undefined" && enforceInMethodNames && isMethod && hasTrailingUnderscore(identifier)) { - context.report({ - node, - message: "Unexpected dangling '_' in '{{identifier}}'.", - data: { - identifier - } - }); - } - } - - //-------------------------------------------------------------------------- - // Public API - //-------------------------------------------------------------------------- - - return { - FunctionDeclaration: checkForTrailingUnderscoreInFunctionDeclaration, - VariableDeclarator: checkForTrailingUnderscoreInVariableExpression, - MemberExpression: checkForTrailingUnderscoreInMemberExpression, - MethodDefinition: checkForTrailingUnderscoreInMethod, - Property: checkForTrailingUnderscoreInMethod - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-unexpected-multiline.js b/tools/node_modules/eslint/lib/rules/no-unexpected-multiline.js deleted file mode 100644 index 35c2140bae605b..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-unexpected-multiline.js +++ /dev/null @@ -1,102 +0,0 @@ -/** - * @fileoverview Rule to spot scenarios where a newline looks like it is ending a statement, but is not. - * @author Glen Mailer - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow confusing multiline expressions", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-unexpected-multiline" - }, - - schema: [], - messages: { - function: "Unexpected newline between function and ( of function call.", - property: "Unexpected newline between object and [ of property access.", - taggedTemplate: "Unexpected newline between template tag and template literal.", - division: "Unexpected newline between numerator and division operator." - } - }, - - create(context) { - - const REGEX_FLAG_MATCHER = /^[gimsuy]+$/; - - const sourceCode = context.getSourceCode(); - - /** - * Check to see if there is a newline between the node and the following open bracket - * line's expression - * @param {ASTNode} node The node to check. - * @param {string} messageId The error messageId to use. - * @returns {void} - * @private - */ - function checkForBreakAfter(node, messageId) { - const openParen = sourceCode.getTokenAfter(node, astUtils.isNotClosingParenToken); - const nodeExpressionEnd = sourceCode.getTokenBefore(openParen); - - if (openParen.loc.start.line !== nodeExpressionEnd.loc.end.line) { - context.report({ node, loc: openParen.loc.start, messageId, data: { char: openParen.value } }); - } - } - - //-------------------------------------------------------------------------- - // Public API - //-------------------------------------------------------------------------- - - return { - - MemberExpression(node) { - if (!node.computed) { - return; - } - checkForBreakAfter(node.object, "property"); - }, - - TaggedTemplateExpression(node) { - if (node.tag.loc.end.line === node.quasi.loc.start.line) { - return; - } - context.report({ node, loc: node.loc.start, messageId: "taggedTemplate" }); - }, - - CallExpression(node) { - if (node.arguments.length === 0) { - return; - } - checkForBreakAfter(node.callee, "function"); - }, - - "BinaryExpression[operator='/'] > BinaryExpression[operator='/'].left"(node) { - const secondSlash = sourceCode.getTokenAfter(node, token => token.value === "/"); - const tokenAfterOperator = sourceCode.getTokenAfter(secondSlash); - - if ( - tokenAfterOperator.type === "Identifier" && - REGEX_FLAG_MATCHER.test(tokenAfterOperator.value) && - secondSlash.range[1] === tokenAfterOperator.range[0] - ) { - checkForBreakAfter(node.left, "division"); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-unmodified-loop-condition.js b/tools/node_modules/eslint/lib/rules/no-unmodified-loop-condition.js deleted file mode 100644 index 95898c5f19d814..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-unmodified-loop-condition.js +++ /dev/null @@ -1,369 +0,0 @@ -/** - * @fileoverview Rule to disallow use of unmodified expressions in loop conditions - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const Traverser = require("../util/traverser"), - astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const SENTINEL_PATTERN = /(?:(?:Call|Class|Function|Member|New|Yield)Expression|Statement|Declaration)$/; -const LOOP_PATTERN = /^(?:DoWhile|For|While)Statement$/; // for-in/of statements don't have `test` property. -const GROUP_PATTERN = /^(?:BinaryExpression|ConditionalExpression)$/; -const SKIP_PATTERN = /^(?:ArrowFunction|Class|Function)Expression$/; -const DYNAMIC_PATTERN = /^(?:Call|Member|New|TaggedTemplate|Yield)Expression$/; - -/** - * @typedef {Object} LoopConditionInfo - * @property {eslint-scope.Reference} reference - The reference. - * @property {ASTNode} group - BinaryExpression or ConditionalExpression nodes - * that the reference is belonging to. - * @property {Function} isInLoop - The predicate which checks a given reference - * is in this loop. - * @property {boolean} modified - The flag that the reference is modified in - * this loop. - */ - -/** - * Checks whether or not a given reference is a write reference. - * - * @param {eslint-scope.Reference} reference - A reference to check. - * @returns {boolean} `true` if the reference is a write reference. - */ -function isWriteReference(reference) { - if (reference.init) { - const def = reference.resolved && reference.resolved.defs[0]; - - if (!def || def.type !== "Variable" || def.parent.kind !== "var") { - return false; - } - } - return reference.isWrite(); -} - -/** - * Checks whether or not a given loop condition info does not have the modified - * flag. - * - * @param {LoopConditionInfo} condition - A loop condition info to check. - * @returns {boolean} `true` if the loop condition info is "unmodified". - */ -function isUnmodified(condition) { - return !condition.modified; -} - -/** - * Checks whether or not a given loop condition info does not have the modified - * flag and does not have the group this condition belongs to. - * - * @param {LoopConditionInfo} condition - A loop condition info to check. - * @returns {boolean} `true` if the loop condition info is "unmodified". - */ -function isUnmodifiedAndNotBelongToGroup(condition) { - return !(condition.modified || condition.group); -} - -/** - * Checks whether or not a given reference is inside of a given node. - * - * @param {ASTNode} node - A node to check. - * @param {eslint-scope.Reference} reference - A reference to check. - * @returns {boolean} `true` if the reference is inside of the node. - */ -function isInRange(node, reference) { - const or = node.range; - const ir = reference.identifier.range; - - return or[0] <= ir[0] && ir[1] <= or[1]; -} - -/** - * Checks whether or not a given reference is inside of a loop node's condition. - * - * @param {ASTNode} node - A node to check. - * @param {eslint-scope.Reference} reference - A reference to check. - * @returns {boolean} `true` if the reference is inside of the loop node's - * condition. - */ -const isInLoop = { - WhileStatement: isInRange, - DoWhileStatement: isInRange, - ForStatement(node, reference) { - return ( - isInRange(node, reference) && - !(node.init && isInRange(node.init, reference)) - ); - } -}; - -/** - * Gets the function which encloses a given reference. - * This supports only FunctionDeclaration. - * - * @param {eslint-scope.Reference} reference - A reference to get. - * @returns {ASTNode|null} The function node or null. - */ -function getEncloseFunctionDeclaration(reference) { - let node = reference.identifier; - - while (node) { - if (node.type === "FunctionDeclaration") { - return node.id ? node : null; - } - - node = node.parent; - } - - return null; -} - -/** - * Updates the "modified" flags of given loop conditions with given modifiers. - * - * @param {LoopConditionInfo[]} conditions - The loop conditions to be updated. - * @param {eslint-scope.Reference[]} modifiers - The references to update. - * @returns {void} - */ -function updateModifiedFlag(conditions, modifiers) { - - for (let i = 0; i < conditions.length; ++i) { - const condition = conditions[i]; - - for (let j = 0; !condition.modified && j < modifiers.length; ++j) { - const modifier = modifiers[j]; - let funcNode, funcVar; - - /* - * Besides checking for the condition being in the loop, we want to - * check the function that this modifier is belonging to is called - * in the loop. - * FIXME: This should probably be extracted to a function. - */ - const inLoop = condition.isInLoop(modifier) || Boolean( - (funcNode = getEncloseFunctionDeclaration(modifier)) && - (funcVar = astUtils.getVariableByName(modifier.from.upper, funcNode.id.name)) && - funcVar.references.some(condition.isInLoop) - ); - - condition.modified = inLoop; - } - } -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow unmodified loop conditions", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-unmodified-loop-condition" - }, - - schema: [] - }, - - create(context) { - const sourceCode = context.getSourceCode(); - let groupMap = null; - - /** - * Reports a given condition info. - * - * @param {LoopConditionInfo} condition - A loop condition info to report. - * @returns {void} - */ - function report(condition) { - const node = condition.reference.identifier; - - context.report({ - node, - message: "'{{name}}' is not modified in this loop.", - data: node - }); - } - - /** - * Registers given conditions to the group the condition belongs to. - * - * @param {LoopConditionInfo[]} conditions - A loop condition info to - * register. - * @returns {void} - */ - function registerConditionsToGroup(conditions) { - for (let i = 0; i < conditions.length; ++i) { - const condition = conditions[i]; - - if (condition.group) { - let group = groupMap.get(condition.group); - - if (!group) { - group = []; - groupMap.set(condition.group, group); - } - group.push(condition); - } - } - } - - /** - * Reports references which are inside of unmodified groups. - * - * @param {LoopConditionInfo[]} conditions - A loop condition info to report. - * @returns {void} - */ - function checkConditionsInGroup(conditions) { - if (conditions.every(isUnmodified)) { - conditions.forEach(report); - } - } - - /** - * Checks whether or not a given group node has any dynamic elements. - * - * @param {ASTNode} root - A node to check. - * This node is one of BinaryExpression or ConditionalExpression. - * @returns {boolean} `true` if the node is dynamic. - */ - function hasDynamicExpressions(root) { - let retv = false; - - Traverser.traverse(root, { - visitorKeys: sourceCode.visitorKeys, - enter(node) { - if (DYNAMIC_PATTERN.test(node.type)) { - retv = true; - this.break(); - } else if (SKIP_PATTERN.test(node.type)) { - this.skip(); - } - } - }); - - return retv; - } - - /** - * Creates the loop condition information from a given reference. - * - * @param {eslint-scope.Reference} reference - A reference to create. - * @returns {LoopConditionInfo|null} Created loop condition info, or null. - */ - function toLoopCondition(reference) { - if (reference.init) { - return null; - } - - let group = null; - let child = reference.identifier; - let node = child.parent; - - while (node) { - if (SENTINEL_PATTERN.test(node.type)) { - if (LOOP_PATTERN.test(node.type) && node.test === child) { - - // This reference is inside of a loop condition. - return { - reference, - group, - isInLoop: isInLoop[node.type].bind(null, node), - modified: false - }; - } - - // This reference is outside of a loop condition. - break; - } - - /* - * If it's inside of a group, OK if either operand is modified. - * So stores the group this reference belongs to. - */ - if (GROUP_PATTERN.test(node.type)) { - - // If this expression is dynamic, no need to check. - if (hasDynamicExpressions(node)) { - break; - } else { - group = node; - } - } - - child = node; - node = node.parent; - } - - return null; - } - - /** - * Finds unmodified references which are inside of a loop condition. - * Then reports the references which are outside of groups. - * - * @param {eslint-scope.Variable} variable - A variable to report. - * @returns {void} - */ - function checkReferences(variable) { - - // Gets references that exist in loop conditions. - const conditions = variable - .references - .map(toLoopCondition) - .filter(Boolean); - - if (conditions.length === 0) { - return; - } - - // Registers the conditions to belonging groups. - registerConditionsToGroup(conditions); - - // Check the conditions are modified. - const modifiers = variable.references.filter(isWriteReference); - - if (modifiers.length > 0) { - updateModifiedFlag(conditions, modifiers); - } - - /* - * Reports the conditions which are not belonging to groups. - * Others will be reported after all variables are done. - */ - conditions - .filter(isUnmodifiedAndNotBelongToGroup) - .forEach(report); - } - - return { - "Program:exit"() { - const queue = [context.getScope()]; - - groupMap = new Map(); - - let scope; - - while ((scope = queue.pop())) { - queue.push(...scope.childScopes); - scope.variables.forEach(checkReferences); - } - - groupMap.forEach(checkConditionsInGroup); - groupMap = null; - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-unneeded-ternary.js b/tools/node_modules/eslint/lib/rules/no-unneeded-ternary.js deleted file mode 100644 index e75a36430fe8aa..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-unneeded-ternary.js +++ /dev/null @@ -1,159 +0,0 @@ -/** - * @fileoverview Rule to flag no-unneeded-ternary - * @author Gyandeep Singh - */ - -"use strict"; - -const astUtils = require("../util/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 -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow ternary operators when simpler alternatives exist", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/no-unneeded-ternary" - }, - - schema: [ - { - type: "object", - properties: { - defaultAssignment: { - type: "boolean", - default: true - } - }, - 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 - * @param {ASTNode} node - The node to report. - * @returns {boolean} True if the its a boolean literal - * @private - */ - function isBooleanLiteral(node) { - 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.getFirstTokenBetween( - node.left, - node.right, - token => token.value === node.operator - ); - const text = sourceCode.getText(); - - return text.slice(node.range[0], - operatorToken.range[0]) + OPERATOR_INVERSES[node.operator] + text.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. - * @returns {boolean} True if the pattern is matched, and false otherwise - * @private - */ - function matchesDefaultAssignment(node) { - return node.test.type === "Identifier" && - node.consequent.type === "Identifier" && - node.test.name === node.consequent.name; - } - - return { - - ConditionalExpression(node) { - if (isBooleanLiteral(node.alternate) && isBooleanLiteral(node.consequent)) { - 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, - loc: node.consequent.loc.start, - message: "Unnecessary use of conditional expression for default assignment.", - fix: fixer => { - let nodeAlternate = astUtils.getParenthesisedText(sourceCode, node.alternate); - - if (node.alternate.type === "ConditionalExpression" || node.alternate.type === "YieldExpression") { - const isAlternateParenthesised = astUtils.isParenthesised(sourceCode, node.alternate); - - nodeAlternate = isAlternateParenthesised ? nodeAlternate : `(${nodeAlternate})`; - } - - return fixer.replaceText(node, `${astUtils.getParenthesisedText(sourceCode, node.test)} || ${nodeAlternate}`); - } - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-unreachable.js b/tools/node_modules/eslint/lib/rules/no-unreachable.js deleted file mode 100644 index 8ea2583f7cb251..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-unreachable.js +++ /dev/null @@ -1,214 +0,0 @@ -/** - * @fileoverview Checks for unreachable code due to return, throws, break, and continue. - * @author Joel Feenstra - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks whether or not a given variable declarator has the initializer. - * @param {ASTNode} node - A VariableDeclarator node to check. - * @returns {boolean} `true` if the node has the initializer. - */ -function isInitialized(node) { - return Boolean(node.init); -} - -/** - * Checks whether or not a given code path segment is unreachable. - * @param {CodePathSegment} segment - A CodePathSegment to check. - * @returns {boolean} `true` if the segment is unreachable. - */ -function isUnreachable(segment) { - return !segment.reachable; -} - -/** - * The class to distinguish consecutive unreachable statements. - */ -class ConsecutiveRange { - constructor(sourceCode) { - this.sourceCode = sourceCode; - this.startNode = null; - this.endNode = null; - } - - /** - * The location object of this range. - * @type {Object} - */ - get location() { - return { - start: this.startNode.loc.start, - end: this.endNode.loc.end - }; - } - - /** - * `true` if this range is empty. - * @type {boolean} - */ - get isEmpty() { - return !(this.startNode && this.endNode); - } - - /** - * Checks whether the given node is inside of this range. - * @param {ASTNode|Token} node - The node to check. - * @returns {boolean} `true` if the node is inside of this range. - */ - contains(node) { - return ( - node.range[0] >= this.startNode.range[0] && - node.range[1] <= this.endNode.range[1] - ); - } - - /** - * Checks whether the given node is consecutive to this range. - * @param {ASTNode} node - The node to check. - * @returns {boolean} `true` if the node is consecutive to this range. - */ - isConsecutive(node) { - return this.contains(this.sourceCode.getTokenBefore(node)); - } - - /** - * Merges the given node to this range. - * @param {ASTNode} node - The node to merge. - * @returns {void} - */ - merge(node) { - this.endNode = node; - } - - /** - * Resets this range by the given node or null. - * @param {ASTNode|null} node - The node to reset, or null. - * @returns {void} - */ - reset(node) { - this.startNode = this.endNode = node; - } -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow unreachable code after `return`, `throw`, `continue`, and `break` statements", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-unreachable" - }, - - schema: [] - }, - - create(context) { - let currentCodePath = null; - - const range = new ConsecutiveRange(context.getSourceCode()); - - /** - * Reports a given node if it's unreachable. - * @param {ASTNode} node - A statement node to report. - * @returns {void} - */ - function reportIfUnreachable(node) { - let nextNode = null; - - if (node && currentCodePath.currentSegments.every(isUnreachable)) { - - // Store this statement to distinguish consecutive statements. - if (range.isEmpty) { - range.reset(node); - return; - } - - // Skip if this statement is inside of the current range. - if (range.contains(node)) { - return; - } - - // Merge if this statement is consecutive to the current range. - if (range.isConsecutive(node)) { - range.merge(node); - return; - } - - nextNode = node; - } - - /* - * Report the current range since this statement is reachable or is - * not consecutive to the current range. - */ - if (!range.isEmpty) { - context.report({ - message: "Unreachable code.", - loc: range.location, - node: range.startNode - }); - } - - // Update the current range. - range.reset(nextNode); - } - - return { - - // Manages the current code path. - onCodePathStart(codePath) { - currentCodePath = codePath; - }, - - onCodePathEnd() { - currentCodePath = currentCodePath.upper; - }, - - // Registers for all statement nodes (excludes FunctionDeclaration). - BlockStatement: reportIfUnreachable, - BreakStatement: reportIfUnreachable, - ClassDeclaration: reportIfUnreachable, - ContinueStatement: reportIfUnreachable, - DebuggerStatement: reportIfUnreachable, - DoWhileStatement: reportIfUnreachable, - ExpressionStatement: reportIfUnreachable, - ForInStatement: reportIfUnreachable, - ForOfStatement: reportIfUnreachable, - ForStatement: reportIfUnreachable, - IfStatement: reportIfUnreachable, - ImportDeclaration: reportIfUnreachable, - LabeledStatement: reportIfUnreachable, - ReturnStatement: reportIfUnreachable, - SwitchStatement: reportIfUnreachable, - ThrowStatement: reportIfUnreachable, - TryStatement: reportIfUnreachable, - - VariableDeclaration(node) { - if (node.kind !== "var" || node.declarations.some(isInitialized)) { - reportIfUnreachable(node); - } - }, - - WhileStatement: reportIfUnreachable, - WithStatement: reportIfUnreachable, - ExportNamedDeclaration: reportIfUnreachable, - ExportDefaultDeclaration: reportIfUnreachable, - ExportAllDeclaration: reportIfUnreachable, - - "Program:exit"() { - reportIfUnreachable(); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-unsafe-finally.js b/tools/node_modules/eslint/lib/rules/no-unsafe-finally.js deleted file mode 100644 index ab612ae6526f66..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-unsafe-finally.js +++ /dev/null @@ -1,110 +0,0 @@ -/** - * @fileoverview Rule to flag unsafe statements in finally block - * @author Onur Temizkan - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const SENTINEL_NODE_TYPE_RETURN_THROW = /^(?:Program|(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression)$/; -const SENTINEL_NODE_TYPE_BREAK = /^(?:Program|(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression|DoWhileStatement|WhileStatement|ForOfStatement|ForInStatement|ForStatement|SwitchStatement)$/; -const SENTINEL_NODE_TYPE_CONTINUE = /^(?:Program|(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression|DoWhileStatement|WhileStatement|ForOfStatement|ForInStatement|ForStatement)$/; - - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow control flow statements in `finally` blocks", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-unsafe-finally" - }, - - schema: [] - }, - create(context) { - - /** - * Checks if the node is the finalizer of a TryStatement - * - * @param {ASTNode} node - node to check. - * @returns {boolean} - true if the node is the finalizer of a TryStatement - */ - function isFinallyBlock(node) { - return node.parent.type === "TryStatement" && node.parent.finalizer === node; - } - - /** - * Climbs up the tree if the node is not a sentinel node - * - * @param {ASTNode} node - node to check. - * @param {string} label - label of the break or continue statement - * @returns {boolean} - return whether the node is a finally block or a sentinel node - */ - function isInFinallyBlock(node, label) { - let labelInside = false; - let sentinelNodeType; - - if (node.type === "BreakStatement" && !node.label) { - sentinelNodeType = SENTINEL_NODE_TYPE_BREAK; - } else if (node.type === "ContinueStatement") { - sentinelNodeType = SENTINEL_NODE_TYPE_CONTINUE; - } else { - sentinelNodeType = SENTINEL_NODE_TYPE_RETURN_THROW; - } - - for ( - let currentNode = node; - currentNode && !sentinelNodeType.test(currentNode.type); - currentNode = currentNode.parent - ) { - if (currentNode.parent.label && label && (currentNode.parent.label.name === label.name)) { - labelInside = true; - } - if (isFinallyBlock(currentNode)) { - if (label && labelInside) { - return false; - } - return true; - } - } - return false; - } - - /** - * Checks whether the possibly-unsafe statement is inside a finally block. - * - * @param {ASTNode} node - node to check. - * @returns {void} - */ - function check(node) { - if (isInFinallyBlock(node, node.label)) { - context.report({ - message: "Unsafe usage of {{nodeType}}.", - data: { - nodeType: node.type - }, - node, - line: node.loc.line, - column: node.loc.column - }); - } - } - - return { - ReturnStatement: check, - ThrowStatement: check, - BreakStatement: check, - ContinueStatement: check - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-unsafe-negation.js b/tools/node_modules/eslint/lib/rules/no-unsafe-negation.js deleted file mode 100644 index 3b5b367e42e1ad..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-unsafe-negation.js +++ /dev/null @@ -1,87 +0,0 @@ -/** - * @fileoverview Rule to disallow negating the left operand of relational operators - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks whether the given operator is a relational operator or not. - * - * @param {string} op - The operator type to check. - * @returns {boolean} `true` if the operator is a relational operator. - */ -function isRelationalOperator(op) { - return op === "in" || op === "instanceof"; -} - -/** - * Checks whether the given node is a logical negation expression or not. - * - * @param {ASTNode} node - The node to check. - * @returns {boolean} `true` if the node is a logical negation expression. - */ -function isNegation(node) { - return node.type === "UnaryExpression" && node.operator === "!"; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow negating the left operand of relational operators", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-unsafe-negation" - }, - - schema: [], - fixable: "code", - messages: { - unexpected: "Unexpected negating the left operand of '{{operator}}' operator." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - return { - BinaryExpression(node) { - if (isRelationalOperator(node.operator) && - isNegation(node.left) && - !astUtils.isParenthesised(sourceCode, node.left) - ) { - context.report({ - node, - loc: node.left.loc, - messageId: "unexpected", - data: { operator: node.operator }, - - fix(fixer) { - const negationToken = sourceCode.getFirstToken(node.left); - const fixRange = [negationToken.range[1], node.range[1]]; - const text = sourceCode.text.slice(fixRange[0], fixRange[1]); - - return fixer.replaceTextRange(fixRange, `(${text})`); - } - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-unused-expressions.js b/tools/node_modules/eslint/lib/rules/no-unused-expressions.js deleted file mode 100644 index 25c21775b0de05..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-unused-expressions.js +++ /dev/null @@ -1,132 +0,0 @@ -/** - * @fileoverview Flag expressions in statement position that do not side effect - * @author Michael Ficarra - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow unused expressions", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-unused-expressions" - }, - - schema: [ - { - type: "object", - properties: { - allowShortCircuit: { - type: "boolean", - default: false - }, - allowTernary: { - type: "boolean", - default: false - }, - allowTaggedTemplates: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ] - }, - - create(context) { - const config = context.options[0] || {}, - allowShortCircuit = config.allowShortCircuit || false, - allowTernary = config.allowTernary || false, - allowTaggedTemplates = config.allowTaggedTemplates || false; - - /** - * @param {ASTNode} node - any node - * @returns {boolean} whether the given node structurally represents a directive - */ - function looksLikeDirective(node) { - return node.type === "ExpressionStatement" && - node.expression.type === "Literal" && typeof node.expression.value === "string"; - } - - /** - * @param {Function} predicate - ([a] -> Boolean) the function used to make the determination - * @param {a[]} list - the input list - * @returns {a[]} the leading sequence of members in the given list that pass the given predicate - */ - function takeWhile(predicate, list) { - for (let i = 0; i < list.length; ++i) { - if (!predicate(list[i])) { - return list.slice(0, i); - } - } - return list.slice(); - } - - /** - * @param {ASTNode} node - a Program or BlockStatement node - * @returns {ASTNode[]} the leading sequence of directive nodes in the given node's body - */ - function directives(node) { - return takeWhile(looksLikeDirective, node.body); - } - - /** - * @param {ASTNode} node - any node - * @param {ASTNode[]} ancestors - the given node's ancestors - * @returns {boolean} whether the given node is considered a directive in its current position - */ - function isDirective(node, ancestors) { - const parent = ancestors[ancestors.length - 1], - grandparent = ancestors[ancestors.length - 2]; - - return (parent.type === "Program" || parent.type === "BlockStatement" && - (/Function/.test(grandparent.type))) && - directives(parent).indexOf(node) >= 0; - } - - /** - * Determines whether or not a given node is a valid expression. Recurses on short circuit eval and ternary nodes if enabled by flags. - * @param {ASTNode} node - any node - * @returns {boolean} whether the given node is a valid expression - */ - function isValidExpression(node) { - if (allowTernary) { - - // Recursive check for ternary and logical expressions - if (node.type === "ConditionalExpression") { - return isValidExpression(node.consequent) && isValidExpression(node.alternate); - } - } - - if (allowShortCircuit) { - if (node.type === "LogicalExpression") { - return isValidExpression(node.right); - } - } - - if (allowTaggedTemplates && node.type === "TaggedTemplateExpression") { - return true; - } - - return /^(?:Assignment|Call|New|Update|Yield|Await)Expression$/.test(node.type) || - (node.type === "UnaryExpression" && ["delete", "void"].indexOf(node.operator) >= 0); - } - - return { - ExpressionStatement(node) { - if (!isValidExpression(node.expression) && !isDirective(node, context.getAncestors())) { - context.report({ node, message: "Expected an assignment or function call and instead saw an expression." }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-unused-labels.js b/tools/node_modules/eslint/lib/rules/no-unused-labels.js deleted file mode 100644 index 1ba1d05d5c6ae7..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-unused-labels.js +++ /dev/null @@ -1,113 +0,0 @@ -/** - * @fileoverview Rule to disallow unused labels. - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow unused labels", - category: "Best Practices", - recommended: true, - url: "https://eslint.org/docs/rules/no-unused-labels" - }, - - schema: [], - - fixable: "code", - - messages: { - unused: "'{{name}}:' is defined but never used." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - let scopeInfo = null; - - /** - * Adds a scope info to the stack. - * - * @param {ASTNode} node - A node to add. This is a LabeledStatement. - * @returns {void} - */ - function enterLabeledScope(node) { - scopeInfo = { - label: node.label.name, - used: false, - upper: scopeInfo - }; - } - - /** - * Removes the top of the stack. - * At the same time, this reports the label if it's never used. - * - * @param {ASTNode} node - A node to report. This is a LabeledStatement. - * @returns {void} - */ - function exitLabeledScope(node) { - if (!scopeInfo.used) { - context.report({ - node: node.label, - messageId: "unused", - data: node.label, - fix(fixer) { - - /* - * Only perform a fix if there are no comments between the label and the body. This will be the case - * when there is exactly one token/comment (the ":") between the label and the body. - */ - if (sourceCode.getTokenAfter(node.label, { includeComments: true }) === - sourceCode.getTokenBefore(node.body, { includeComments: true })) { - return fixer.removeRange([node.range[0], node.body.range[0]]); - } - - return null; - } - }); - } - - scopeInfo = scopeInfo.upper; - } - - /** - * Marks the label of a given node as used. - * - * @param {ASTNode} node - A node to mark. This is a BreakStatement or - * ContinueStatement. - * @returns {void} - */ - function markAsUsed(node) { - if (!node.label) { - return; - } - - const label = node.label.name; - let info = scopeInfo; - - while (info) { - if (info.label === label) { - info.used = true; - break; - } - info = info.upper; - } - } - - return { - LabeledStatement: enterLabeledScope, - "LabeledStatement:exit": exitLabeledScope, - BreakStatement: markAsUsed, - ContinueStatement: markAsUsed - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-unused-vars.js b/tools/node_modules/eslint/lib/rules/no-unused-vars.js deleted file mode 100644 index e56ba221bbc841..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-unused-vars.js +++ /dev/null @@ -1,660 +0,0 @@ -/** - * @fileoverview Rule to flag declared but unused variables - * @author Ilya Volodin - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const lodash = require("lodash"); -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow unused variables", - category: "Variables", - recommended: true, - url: "https://eslint.org/docs/rules/no-unused-vars" - }, - - schema: [ - { - oneOf: [ - { - enum: ["all", "local"] - }, - { - type: "object", - properties: { - vars: { - enum: ["all", "local"], - default: "all" - }, - varsIgnorePattern: { - type: "string" - }, - args: { - enum: ["all", "after-used", "none"], - default: "after-used" - }, - ignoreRestSiblings: { - type: "boolean", - default: false - }, - argsIgnorePattern: { - type: "string" - }, - caughtErrors: { - enum: ["all", "none"], - default: "none" - }, - caughtErrorsIgnorePattern: { - type: "string" - } - } - } - ] - } - ] - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - const REST_PROPERTY_TYPE = /^(?:RestElement|(?:Experimental)?RestProperty)$/; - - const config = { - vars: "all", - args: "after-used", - ignoreRestSiblings: false, - caughtErrors: "none" - }; - - const firstOption = context.options[0]; - - if (firstOption) { - if (typeof firstOption === "string") { - config.vars = firstOption; - } else { - config.vars = firstOption.vars || config.vars; - config.args = firstOption.args || config.args; - config.ignoreRestSiblings = firstOption.ignoreRestSiblings || config.ignoreRestSiblings; - config.caughtErrors = firstOption.caughtErrors || config.caughtErrors; - - if (firstOption.varsIgnorePattern) { - config.varsIgnorePattern = new RegExp(firstOption.varsIgnorePattern); - } - - if (firstOption.argsIgnorePattern) { - config.argsIgnorePattern = new RegExp(firstOption.argsIgnorePattern); - } - - if (firstOption.caughtErrorsIgnorePattern) { - config.caughtErrorsIgnorePattern = new RegExp(firstOption.caughtErrorsIgnorePattern); - } - } - } - - /** - * Generate the warning message about the variable being - * defined and unused, including the ignore pattern if configured. - * @param {Variable} unusedVar - eslint-scope variable object. - * @returns {string} The warning message to be used with this unused variable. - */ - function getDefinedMessage(unusedVar) { - const defType = unusedVar.defs && unusedVar.defs[0] && unusedVar.defs[0].type; - let type; - let pattern; - - if (defType === "CatchClause" && config.caughtErrorsIgnorePattern) { - type = "args"; - pattern = config.caughtErrorsIgnorePattern.toString(); - } else if (defType === "Parameter" && config.argsIgnorePattern) { - type = "args"; - pattern = config.argsIgnorePattern.toString(); - } else if (defType !== "Parameter" && config.varsIgnorePattern) { - type = "vars"; - pattern = config.varsIgnorePattern.toString(); - } - - const additional = type ? ` Allowed unused ${type} must match ${pattern}.` : ""; - - return `'{{name}}' is defined but never used.${additional}`; - } - - /** - * Generate the warning message about the variable being - * assigned and unused, including the ignore pattern if configured. - * @returns {string} The warning message to be used with this unused variable. - */ - function getAssignedMessage() { - const additional = config.varsIgnorePattern ? ` Allowed unused vars must match ${config.varsIgnorePattern.toString()}.` : ""; - - return `'{{name}}' is assigned a value but never used.${additional}`; - } - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - const STATEMENT_TYPE = /(?:Statement|Declaration)$/; - - /** - * Determines if a given variable is being exported from a module. - * @param {Variable} variable - eslint-scope variable object. - * @returns {boolean} True if the variable is exported, false if not. - * @private - */ - function isExported(variable) { - - const definition = variable.defs[0]; - - if (definition) { - - let node = definition.node; - - if (node.type === "VariableDeclarator") { - node = node.parent; - } else if (definition.type === "Parameter") { - return false; - } - - return node.parent.type.indexOf("Export") === 0; - } - return false; - - } - - /** - * Determines if a variable has a sibling rest property - * @param {Variable} variable - eslint-scope variable object. - * @returns {boolean} True if the variable is exported, false if not. - * @private - */ - function hasRestSpreadSibling(variable) { - if (config.ignoreRestSiblings) { - return variable.defs.some(def => { - const propertyNode = def.name.parent; - const patternNode = propertyNode.parent; - - return ( - propertyNode.type === "Property" && - patternNode.type === "ObjectPattern" && - REST_PROPERTY_TYPE.test(patternNode.properties[patternNode.properties.length - 1].type) - ); - }); - } - - return false; - } - - /** - * Determines if a reference is a read operation. - * @param {Reference} ref - An eslint-scope Reference - * @returns {boolean} whether the given reference represents a read operation - * @private - */ - function isReadRef(ref) { - return ref.isRead(); - } - - /** - * Determine if an identifier is referencing an enclosing function name. - * @param {Reference} ref - The reference to check. - * @param {ASTNode[]} nodes - The candidate function nodes. - * @returns {boolean} True if it's a self-reference, false if not. - * @private - */ - function isSelfReference(ref, nodes) { - let scope = ref.from; - - while (scope) { - if (nodes.indexOf(scope.block) >= 0) { - return true; - } - - scope = scope.upper; - } - - return false; - } - - /** - * Gets a list of function definitions for a specified variable. - * @param {Variable} variable - eslint-scope variable object. - * @returns {ASTNode[]} Function nodes. - * @private - */ - function getFunctionDefinitions(variable) { - const functionDefinitions = []; - - variable.defs.forEach(def => { - const { type, node } = def; - - // FunctionDeclarations - if (type === "FunctionName") { - functionDefinitions.push(node); - } - - // FunctionExpressions - if (type === "Variable" && node.init && - (node.init.type === "FunctionExpression" || node.init.type === "ArrowFunctionExpression")) { - functionDefinitions.push(node.init); - } - }); - return functionDefinitions; - } - - /** - * Checks the position of given nodes. - * - * @param {ASTNode} inner - A node which is expected as inside. - * @param {ASTNode} outer - A node which is expected as outside. - * @returns {boolean} `true` if the `inner` node exists in the `outer` node. - * @private - */ - function isInside(inner, outer) { - return ( - inner.range[0] >= outer.range[0] && - inner.range[1] <= outer.range[1] - ); - } - - /** - * If a given reference is left-hand side of an assignment, this gets - * the right-hand side node of the assignment. - * - * In the following cases, this returns null. - * - * - The reference is not the LHS of an assignment expression. - * - The reference is inside of a loop. - * - The reference is inside of a function scope which is different from - * the declaration. - * - * @param {eslint-scope.Reference} ref - A reference to check. - * @param {ASTNode} prevRhsNode - The previous RHS node. - * @returns {ASTNode|null} The RHS node or null. - * @private - */ - function getRhsNode(ref, prevRhsNode) { - const id = ref.identifier; - const parent = id.parent; - const granpa = parent.parent; - const refScope = ref.from.variableScope; - const varScope = ref.resolved.scope.variableScope; - const canBeUsedLater = refScope !== varScope || astUtils.isInLoop(id); - - /* - * Inherits the previous node if this reference is in the node. - * This is for `a = a + a`-like code. - */ - if (prevRhsNode && isInside(id, prevRhsNode)) { - return prevRhsNode; - } - - if (parent.type === "AssignmentExpression" && - granpa.type === "ExpressionStatement" && - id === parent.left && - !canBeUsedLater - ) { - return parent.right; - } - return null; - } - - /** - * Checks whether a given function node is stored to somewhere or not. - * If the function node is stored, the function can be used later. - * - * @param {ASTNode} funcNode - A function node to check. - * @param {ASTNode} rhsNode - The RHS node of the previous assignment. - * @returns {boolean} `true` if under the following conditions: - * - the funcNode is assigned to a variable. - * - the funcNode is bound as an argument of a function call. - * - the function is bound to a property and the object satisfies above conditions. - * @private - */ - function isStorableFunction(funcNode, rhsNode) { - let node = funcNode; - let parent = funcNode.parent; - - while (parent && isInside(parent, rhsNode)) { - switch (parent.type) { - case "SequenceExpression": - if (parent.expressions[parent.expressions.length - 1] !== node) { - return false; - } - break; - - case "CallExpression": - case "NewExpression": - return parent.callee !== node; - - case "AssignmentExpression": - case "TaggedTemplateExpression": - case "YieldExpression": - return true; - - default: - if (STATEMENT_TYPE.test(parent.type)) { - - /* - * If it encountered statements, this is a complex pattern. - * Since analyzeing complex patterns is hard, this returns `true` to avoid false positive. - */ - return true; - } - } - - node = parent; - parent = parent.parent; - } - - return false; - } - - /** - * Checks whether a given Identifier node exists inside of a function node which can be used later. - * - * "can be used later" means: - * - the function is assigned to a variable. - * - the function is bound to a property and the object can be used later. - * - the function is bound as an argument of a function call. - * - * If a reference exists in a function which can be used later, the reference is read when the function is called. - * - * @param {ASTNode} id - An Identifier node to check. - * @param {ASTNode} rhsNode - The RHS node of the previous assignment. - * @returns {boolean} `true` if the `id` node exists inside of a function node which can be used later. - * @private - */ - function isInsideOfStorableFunction(id, rhsNode) { - const funcNode = astUtils.getUpperFunction(id); - - return ( - funcNode && - isInside(funcNode, rhsNode) && - isStorableFunction(funcNode, rhsNode) - ); - } - - /** - * Checks whether a given reference is a read to update itself or not. - * - * @param {eslint-scope.Reference} ref - A reference to check. - * @param {ASTNode} rhsNode - The RHS node of the previous assignment. - * @returns {boolean} The reference is a read to update itself. - * @private - */ - function isReadForItself(ref, rhsNode) { - const id = ref.identifier; - const parent = id.parent; - const granpa = parent.parent; - - return ref.isRead() && ( - - // self update. e.g. `a += 1`, `a++` - (// in RHS of an assignment for itself. e.g. `a = a + 1` - (( - parent.type === "AssignmentExpression" && - granpa.type === "ExpressionStatement" && - parent.left === id - ) || - ( - parent.type === "UpdateExpression" && - granpa.type === "ExpressionStatement" - ) || rhsNode && - isInside(id, rhsNode) && - !isInsideOfStorableFunction(id, rhsNode))) - ); - } - - /** - * Determine if an identifier is used either in for-in loops. - * - * @param {Reference} ref - The reference to check. - * @returns {boolean} whether reference is used in the for-in loops - * @private - */ - function isForInRef(ref) { - let target = ref.identifier.parent; - - - // "for (var ...) { return; }" - if (target.type === "VariableDeclarator") { - target = target.parent.parent; - } - - if (target.type !== "ForInStatement") { - return false; - } - - // "for (...) { return; }" - if (target.body.type === "BlockStatement") { - target = target.body.body[0]; - - // "for (...) return;" - } else { - target = target.body; - } - - // For empty loop body - if (!target) { - return false; - } - - return target.type === "ReturnStatement"; - } - - /** - * Determines if the variable is used. - * @param {Variable} variable - The variable to check. - * @returns {boolean} True if the variable is used - * @private - */ - function isUsedVariable(variable) { - const functionNodes = getFunctionDefinitions(variable), - isFunctionDefinition = functionNodes.length > 0; - let rhsNode = null; - - return variable.references.some(ref => { - if (isForInRef(ref)) { - return true; - } - - const forItself = isReadForItself(ref, rhsNode); - - rhsNode = getRhsNode(ref, rhsNode); - - return ( - isReadRef(ref) && - !forItself && - !(isFunctionDefinition && isSelfReference(ref, functionNodes)) - ); - }); - } - - /** - * Checks whether the given variable is after the last used parameter. - * - * @param {eslint-scope.Variable} variable - The variable to check. - * @returns {boolean} `true` if the variable is defined after the last - * used parameter. - */ - function isAfterLastUsedArg(variable) { - const def = variable.defs[0]; - const params = context.getDeclaredVariables(def.node); - const posteriorParams = params.slice(params.indexOf(variable) + 1); - - // If any used parameters occur after this parameter, do not report. - return !posteriorParams.some(v => v.references.length > 0 || v.eslintUsed); - } - - /** - * Gets an array of variables without read references. - * @param {Scope} scope - an eslint-scope Scope object. - * @param {Variable[]} unusedVars - an array that saving result. - * @returns {Variable[]} unused variables of the scope and descendant scopes. - * @private - */ - function collectUnusedVariables(scope, unusedVars) { - const variables = scope.variables; - const childScopes = scope.childScopes; - let i, l; - - if (scope.type !== "TDZ" && (scope.type !== "global" || config.vars === "all")) { - for (i = 0, l = variables.length; i < l; ++i) { - const variable = variables[i]; - - // skip a variable of class itself name in the class scope - if (scope.type === "class" && scope.block.id === variable.identifiers[0]) { - continue; - } - - // skip function expression names and variables marked with markVariableAsUsed() - if (scope.functionExpressionScope || variable.eslintUsed) { - continue; - } - - // skip implicit "arguments" variable - if (scope.type === "function" && variable.name === "arguments" && variable.identifiers.length === 0) { - continue; - } - - // explicit global variables don't have definitions. - const def = variable.defs[0]; - - if (def) { - const type = def.type; - - // skip catch variables - if (type === "CatchClause") { - if (config.caughtErrors === "none") { - continue; - } - - // skip ignored parameters - if (config.caughtErrorsIgnorePattern && config.caughtErrorsIgnorePattern.test(def.name.name)) { - continue; - } - } - - if (type === "Parameter") { - - // skip any setter argument - if ((def.node.parent.type === "Property" || def.node.parent.type === "MethodDefinition") && def.node.parent.kind === "set") { - continue; - } - - // if "args" option is "none", skip any parameter - if (config.args === "none") { - continue; - } - - // skip ignored parameters - if (config.argsIgnorePattern && config.argsIgnorePattern.test(def.name.name)) { - continue; - } - - // if "args" option is "after-used", skip used variables - if (config.args === "after-used" && astUtils.isFunction(def.name.parent) && !isAfterLastUsedArg(variable)) { - continue; - } - } else { - - // skip ignored variables - if (config.varsIgnorePattern && config.varsIgnorePattern.test(def.name.name)) { - continue; - } - } - } - - if (!isUsedVariable(variable) && !isExported(variable) && !hasRestSpreadSibling(variable)) { - unusedVars.push(variable); - } - } - } - - for (i = 0, l = childScopes.length; i < l; ++i) { - collectUnusedVariables(childScopes[i], unusedVars); - } - - return unusedVars; - } - - /** - * Gets the index of a given variable name in a given comment. - * @param {eslint-scope.Variable} variable - A variable to get. - * @param {ASTNode} comment - A comment node which includes the variable name. - * @returns {number} The index of the variable name's location. - * @private - */ - function getColumnInComment(variable, comment) { - const namePattern = new RegExp(`[\\s,]${lodash.escapeRegExp(variable.name)}(?:$|[\\s,:])`, "g"); - - // To ignore the first text "global". - namePattern.lastIndex = comment.value.indexOf("global") + 6; - - // Search a given variable name. - const match = namePattern.exec(comment.value); - - return match ? match.index + 1 : 0; - } - - /** - * Creates the correct location of a given variables. - * The location is at its name string in a `/*global` comment. - * - * @param {eslint-scope.Variable} variable - A variable to get its location. - * @returns {{line: number, column: number}} The location object for the variable. - * @private - */ - function getLocation(variable) { - const comment = variable.eslintExplicitGlobalComment; - - return sourceCode.getLocFromIndex(comment.range[0] + 2 + getColumnInComment(variable, comment)); - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - "Program:exit"(programNode) { - const unusedVars = collectUnusedVariables(context.getScope(), []); - - for (let i = 0, l = unusedVars.length; i < l; ++i) { - const unusedVar = unusedVars[i]; - - if (unusedVar.eslintExplicitGlobal) { - context.report({ - node: programNode, - loc: getLocation(unusedVar), - message: getDefinedMessage(unusedVar), - data: unusedVar - }); - } else if (unusedVar.defs.length > 0) { - context.report({ - node: unusedVar.identifiers[0], - message: unusedVar.references.some(ref => ref.isWrite()) - ? getAssignedMessage() - : getDefinedMessage(unusedVar), - data: unusedVar - }); - } - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-use-before-define.js b/tools/node_modules/eslint/lib/rules/no-use-before-define.js deleted file mode 100644 index e0b2d23a7e6c94..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-use-before-define.js +++ /dev/null @@ -1,234 +0,0 @@ -/** - * @fileoverview Rule to flag use of variables before they are defined - * @author Ilya Volodin - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const SENTINEL_TYPE = /^(?:(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression|CatchClause|ImportDeclaration|ExportNamedDeclaration)$/; -const FOR_IN_OF_TYPE = /^For(?:In|Of)Statement$/; - -/** - * Parses a given value as options. - * - * @param {any} options - A value to parse. - * @returns {Object} The parsed options. - */ -function parseOptions(options) { - let functions = true; - let classes = true; - let variables = true; - - if (typeof options === "string") { - functions = (options !== "nofunc"); - } else if (typeof options === "object" && options !== null) { - functions = options.functions !== false; - classes = options.classes !== false; - variables = options.variables !== false; - } - - return { functions, classes, variables }; -} - -/** - * Checks whether or not a given variable is a function declaration. - * - * @param {eslint-scope.Variable} variable - A variable to check. - * @returns {boolean} `true` if the variable is a function declaration. - */ -function isFunction(variable) { - return variable.defs[0].type === "FunctionName"; -} - -/** - * Checks whether or not a given variable is a class declaration in an upper function scope. - * - * @param {eslint-scope.Variable} variable - A variable to check. - * @param {eslint-scope.Reference} reference - A reference to check. - * @returns {boolean} `true` if the variable is a class declaration. - */ -function isOuterClass(variable, reference) { - return ( - variable.defs[0].type === "ClassName" && - variable.scope.variableScope !== reference.from.variableScope - ); -} - -/** - * Checks whether or not a given variable is a variable declaration in an upper function scope. - * @param {eslint-scope.Variable} variable - A variable to check. - * @param {eslint-scope.Reference} reference - A reference to check. - * @returns {boolean} `true` if the variable is a variable declaration. - */ -function isOuterVariable(variable, reference) { - return ( - variable.defs[0].type === "Variable" && - variable.scope.variableScope !== reference.from.variableScope - ); -} - -/** - * Checks whether or not a given location is inside of the range of a given node. - * - * @param {ASTNode} node - An node to check. - * @param {number} location - A location to check. - * @returns {boolean} `true` if the location is inside of the range of the node. - */ -function isInRange(node, location) { - return node && node.range[0] <= location && location <= node.range[1]; -} - -/** - * Checks whether or not a given reference is inside of the initializers of a given variable. - * - * This returns `true` in the following cases: - * - * var a = a - * var [a = a] = list - * var {a = a} = obj - * for (var a in a) {} - * for (var a of a) {} - * - * @param {Variable} variable - A variable to check. - * @param {Reference} reference - A reference to check. - * @returns {boolean} `true` if the reference is inside of the initializers. - */ -function isInInitializer(variable, reference) { - if (variable.scope !== reference.from) { - return false; - } - - let node = variable.identifiers[0].parent; - const location = reference.identifier.range[1]; - - while (node) { - if (node.type === "VariableDeclarator") { - if (isInRange(node.init, location)) { - return true; - } - if (FOR_IN_OF_TYPE.test(node.parent.parent.type) && - isInRange(node.parent.parent.right, location) - ) { - return true; - } - break; - } else if (node.type === "AssignmentPattern") { - if (isInRange(node.right, location)) { - return true; - } - } else if (SENTINEL_TYPE.test(node.type)) { - break; - } - - node = node.parent; - } - - return false; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow the use of variables before they are defined", - category: "Variables", - recommended: false, - url: "https://eslint.org/docs/rules/no-use-before-define" - }, - - schema: [ - { - oneOf: [ - { - enum: ["nofunc"] - }, - { - type: "object", - properties: { - functions: { type: "boolean", default: true }, - classes: { type: "boolean", default: true }, - variables: { type: "boolean", default: true } - }, - additionalProperties: false - } - ] - } - ] - }, - - create(context) { - const options = parseOptions(context.options[0]); - - /** - * Determines whether a given use-before-define case should be reported according to the options. - * @param {eslint-scope.Variable} variable The variable that gets used before being defined - * @param {eslint-scope.Reference} reference The reference to the variable - * @returns {boolean} `true` if the usage should be reported - */ - function isForbidden(variable, reference) { - if (isFunction(variable)) { - return options.functions; - } - if (isOuterClass(variable, reference)) { - return options.classes; - } - if (isOuterVariable(variable, reference)) { - return options.variables; - } - return true; - } - - /** - * Finds and validates all variables in a given scope. - * @param {Scope} scope The scope object. - * @returns {void} - * @private - */ - function findVariablesInScope(scope) { - scope.references.forEach(reference => { - const variable = reference.resolved; - - /* - * Skips when the reference is: - * - initialization's. - * - referring to an undefined variable. - * - referring to a global environment variable (there're no identifiers). - * - located preceded by the variable (except in initializers). - * - allowed by options. - */ - if (reference.init || - !variable || - variable.identifiers.length === 0 || - (variable.identifiers[0].range[1] < reference.identifier.range[1] && !isInInitializer(variable, reference)) || - !isForbidden(variable, reference) - ) { - return; - } - - // Reports. - context.report({ - node: reference.identifier, - message: "'{{name}}' was used before it was defined.", - data: reference.identifier - }); - }); - - scope.childScopes.forEach(findVariablesInScope); - } - - return { - Program() { - findVariablesInScope(context.getScope()); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-useless-call.js b/tools/node_modules/eslint/lib/rules/no-useless-call.js deleted file mode 100644 index 74e8bec08bcf3b..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-useless-call.js +++ /dev/null @@ -1,83 +0,0 @@ -/** - * @fileoverview A rule to disallow unnecessary `.call()` and `.apply()`. - * @author Toru Nagashima - */ - -"use strict"; - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks whether or not a node is a `.call()`/`.apply()`. - * @param {ASTNode} node - A CallExpression node to check. - * @returns {boolean} Whether or not the node is a `.call()`/`.apply()`. - */ -function isCallOrNonVariadicApply(node) { - return ( - node.callee.type === "MemberExpression" && - node.callee.property.type === "Identifier" && - node.callee.computed === false && - ( - (node.callee.property.name === "call" && node.arguments.length >= 1) || - (node.callee.property.name === "apply" && node.arguments.length === 2 && node.arguments[1].type === "ArrayExpression") - ) - ); -} - - -/** - * Checks whether or not `thisArg` is not changed by `.call()`/`.apply()`. - * @param {ASTNode|null} expectedThis - The node that is the owner of the applied function. - * @param {ASTNode} thisArg - The node that is given to the first argument of the `.call()`/`.apply()`. - * @param {SourceCode} sourceCode - The ESLint source code object. - * @returns {boolean} Whether or not `thisArg` is not changed by `.call()`/`.apply()`. - */ -function isValidThisArg(expectedThis, thisArg, sourceCode) { - if (!expectedThis) { - return astUtils.isNullOrUndefined(thisArg); - } - return astUtils.equalTokens(expectedThis, thisArg, sourceCode); -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow unnecessary calls to `.call()` and `.apply()`", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-useless-call" - }, - - schema: [] - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - return { - CallExpression(node) { - if (!isCallOrNonVariadicApply(node)) { - return; - } - - const applied = node.callee.object; - const expectedThis = (applied.type === "MemberExpression") ? applied.object : null; - const thisArg = node.arguments[0]; - - if (isValidThisArg(expectedThis, thisArg, sourceCode)) { - context.report({ node, message: "unnecessary '.{{name}}()'.", data: { name: node.callee.property.name } }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-useless-catch.js b/tools/node_modules/eslint/lib/rules/no-useless-catch.js deleted file mode 100644 index e4284cfb4f4307..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-useless-catch.js +++ /dev/null @@ -1,52 +0,0 @@ -/** - * @fileoverview Reports useless `catch` clauses that just rethrow their error. - * @author Teddy Katz - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow unnecessary `catch` clauses", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-useless-catch" - }, - - schema: [] - }, - - create(context) { - return { - CatchClause(node) { - if ( - node.param && - node.param.type === "Identifier" && - node.body.body.length && - node.body.body[0].type === "ThrowStatement" && - node.body.body[0].argument.type === "Identifier" && - node.body.body[0].argument.name === node.param.name - ) { - if (node.parent.finalizer) { - context.report({ - node, - message: "Unnecessary catch clause." - }); - } else { - context.report({ - node: node.parent, - message: "Unnecessary try/catch wrapper." - }); - } - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-useless-computed-key.js b/tools/node_modules/eslint/lib/rules/no-useless-computed-key.js deleted file mode 100644 index ef1f856f3efc5a..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-useless-computed-key.js +++ /dev/null @@ -1,77 +0,0 @@ -/** - * @fileoverview Rule to disallow unnecessary computed property keys in object literals - * @author Burak Yigit Kaya - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -const MESSAGE_UNNECESSARY_COMPUTED = "Unnecessarily computed property [{{property}}] found."; - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow unnecessary computed property keys in object literals", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/no-useless-computed-key" - }, - - schema: [], - fixable: "code" - }, - create(context) { - const sourceCode = context.getSourceCode(); - - return { - Property(node) { - if (!node.computed) { - return; - } - - const key = node.key, - nodeType = typeof key.value; - - if (key.type === "Literal" && (nodeType === "string" || nodeType === "number") && key.value !== "__proto__") { - context.report({ - node, - message: MESSAGE_UNNECESSARY_COMPUTED, - data: { property: sourceCode.getText(key) }, - fix(fixer) { - const leftSquareBracket = sourceCode.getFirstToken(node, astUtils.isOpeningBracketToken); - const rightSquareBracket = sourceCode.getFirstTokenBetween(node.key, node.value, astUtils.isClosingBracketToken); - const tokensBetween = sourceCode.getTokensBetween(leftSquareBracket, rightSquareBracket, 1); - - if (tokensBetween.slice(0, -1).some((token, index) => - sourceCode.getText().slice(token.range[1], tokensBetween[index + 1].range[0]).trim())) { - - // If there are comments between the brackets and the property name, don't do a fix. - return null; - } - - const tokenBeforeLeftBracket = sourceCode.getTokenBefore(leftSquareBracket); - - // Insert a space before the key to avoid changing identifiers, e.g. ({ get[2]() {} }) to ({ get2() {} }) - const needsSpaceBeforeKey = tokenBeforeLeftBracket.range[1] === leftSquareBracket.range[0] && - !astUtils.canTokensBeAdjacent(tokenBeforeLeftBracket, sourceCode.getFirstToken(key)); - - const replacementKey = (needsSpaceBeforeKey ? " " : "") + key.raw; - - return fixer.replaceTextRange([leftSquareBracket.range[0], rightSquareBracket.range[1]], replacementKey); - } - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-useless-concat.js b/tools/node_modules/eslint/lib/rules/no-useless-concat.js deleted file mode 100644 index df310119032979..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-useless-concat.js +++ /dev/null @@ -1,111 +0,0 @@ -/** - * @fileoverview disallow unncessary concatenation of template strings - * @author Henry Zhu - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks whether or not a given node is a concatenation. - * @param {ASTNode} node - A node to check. - * @returns {boolean} `true` if the node is a concatenation. - */ -function isConcatenation(node) { - return node.type === "BinaryExpression" && node.operator === "+"; -} - -/** - * Checks if the given token is a `+` token or not. - * @param {Token} token - The token to check. - * @returns {boolean} `true` if the token is a `+` token. - */ -function isConcatOperatorToken(token) { - return token.value === "+" && token.type === "Punctuator"; -} - -/** - * Get's the right most node on the left side of a BinaryExpression with + operator. - * @param {ASTNode} node - A BinaryExpression node to check. - * @returns {ASTNode} node - */ -function getLeft(node) { - let left = node.left; - - while (isConcatenation(left)) { - left = left.right; - } - return left; -} - -/** - * Get's the left most node on the right side of a BinaryExpression with + operator. - * @param {ASTNode} node - A BinaryExpression node to check. - * @returns {ASTNode} node - */ -function getRight(node) { - let right = node.right; - - while (isConcatenation(right)) { - right = right.left; - } - return right; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow unnecessary concatenation of literals or template literals", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-useless-concat" - }, - - schema: [] - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - return { - BinaryExpression(node) { - - // check if not concatenation - if (node.operator !== "+") { - return; - } - - // account for the `foo + "a" + "b"` case - const left = getLeft(node); - const right = getRight(node); - - if (astUtils.isStringLiteral(left) && - astUtils.isStringLiteral(right) && - astUtils.isTokenOnSameLine(left, right) - ) { - const operatorToken = sourceCode.getFirstTokenBetween(left, right, isConcatOperatorToken); - - context.report({ - node, - loc: operatorToken.loc.start, - message: "Unexpected string concatenation of literals." - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-useless-constructor.js b/tools/node_modules/eslint/lib/rules/no-useless-constructor.js deleted file mode 100644 index c10376450eb5b5..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-useless-constructor.js +++ /dev/null @@ -1,185 +0,0 @@ -/** - * @fileoverview Rule to flag the use of redundant constructors in classes. - * @author Alberto Rodríguez - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks whether a given array of statements is a single call of `super`. - * - * @param {ASTNode[]} body - An array of statements to check. - * @returns {boolean} `true` if the body is a single call of `super`. - */ -function isSingleSuperCall(body) { - return ( - body.length === 1 && - body[0].type === "ExpressionStatement" && - body[0].expression.type === "CallExpression" && - body[0].expression.callee.type === "Super" - ); -} - -/** - * Checks whether a given node is a pattern which doesn't have any side effects. - * Default parameters and Destructuring parameters can have side effects. - * - * @param {ASTNode} node - A pattern node. - * @returns {boolean} `true` if the node doesn't have any side effects. - */ -function isSimple(node) { - return node.type === "Identifier" || node.type === "RestElement"; -} - -/** - * Checks whether a given array of expressions is `...arguments` or not. - * `super(...arguments)` passes all arguments through. - * - * @param {ASTNode[]} superArgs - An array of expressions to check. - * @returns {boolean} `true` if the superArgs is `...arguments`. - */ -function isSpreadArguments(superArgs) { - return ( - superArgs.length === 1 && - superArgs[0].type === "SpreadElement" && - superArgs[0].argument.type === "Identifier" && - superArgs[0].argument.name === "arguments" - ); -} - -/** - * Checks whether given 2 nodes are identifiers which have the same name or not. - * - * @param {ASTNode} ctorParam - A node to check. - * @param {ASTNode} superArg - A node to check. - * @returns {boolean} `true` if the nodes are identifiers which have the same - * name. - */ -function isValidIdentifierPair(ctorParam, superArg) { - return ( - ctorParam.type === "Identifier" && - superArg.type === "Identifier" && - ctorParam.name === superArg.name - ); -} - -/** - * Checks whether given 2 nodes are a rest/spread pair which has the same values. - * - * @param {ASTNode} ctorParam - A node to check. - * @param {ASTNode} superArg - A node to check. - * @returns {boolean} `true` if the nodes are a rest/spread pair which has the - * same values. - */ -function isValidRestSpreadPair(ctorParam, superArg) { - return ( - ctorParam.type === "RestElement" && - superArg.type === "SpreadElement" && - isValidIdentifierPair(ctorParam.argument, superArg.argument) - ); -} - -/** - * Checks whether given 2 nodes have the same value or not. - * - * @param {ASTNode} ctorParam - A node to check. - * @param {ASTNode} superArg - A node to check. - * @returns {boolean} `true` if the nodes have the same value or not. - */ -function isValidPair(ctorParam, superArg) { - return ( - isValidIdentifierPair(ctorParam, superArg) || - isValidRestSpreadPair(ctorParam, superArg) - ); -} - -/** - * Checks whether the parameters of a constructor and the arguments of `super()` - * have the same values or not. - * - * @param {ASTNode} ctorParams - The parameters of a constructor to check. - * @param {ASTNode} superArgs - The arguments of `super()` to check. - * @returns {boolean} `true` if those have the same values. - */ -function isPassingThrough(ctorParams, superArgs) { - if (ctorParams.length !== superArgs.length) { - return false; - } - - for (let i = 0; i < ctorParams.length; ++i) { - if (!isValidPair(ctorParams[i], superArgs[i])) { - return false; - } - } - - return true; -} - -/** - * Checks whether the constructor body is a redundant super call. - * - * @param {Array} body - constructor body content. - * @param {Array} ctorParams - The params to check against super call. - * @returns {boolean} true if the construtor body is redundant - */ -function isRedundantSuperCall(body, ctorParams) { - return ( - isSingleSuperCall(body) && - ctorParams.every(isSimple) && - ( - isSpreadArguments(body[0].expression.arguments) || - isPassingThrough(ctorParams, body[0].expression.arguments) - ) - ); -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow unnecessary constructors", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/no-useless-constructor" - }, - - schema: [] - }, - - create(context) { - - /** - * Checks whether a node is a redundant constructor - * @param {ASTNode} node - node to check - * @returns {void} - */ - function checkForConstructor(node) { - if (node.kind !== "constructor") { - return; - } - - const body = node.value.body.body; - const ctorParams = node.value.params; - const superClass = node.parent.parent.superClass; - - if (superClass ? isRedundantSuperCall(body, ctorParams) : (body.length === 0)) { - context.report({ - node, - message: "Useless constructor." - }); - } - } - - return { - MethodDefinition: checkForConstructor - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-useless-escape.js b/tools/node_modules/eslint/lib/rules/no-useless-escape.js deleted file mode 100644 index c3c0421cc0c5b2..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-useless-escape.js +++ /dev/null @@ -1,226 +0,0 @@ -/** - * @fileoverview Look for useless escapes in strings and regexes - * @author Onur Temizkan - */ - -"use strict"; - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -/** - * 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 = union(new Set("\\nrvtbfux"), astUtils.LINEBREAKS); -const REGEX_GENERAL_ESCAPES = new Set("\\bcdDfnpPrsStvwWxu0123456789]"); -const REGEX_NON_CHARCLASS_ESCAPES = union(REGEX_GENERAL_ESCAPES, new Set("^/.$*+?[{}|()Bk")); - -/** - * 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: { - type: "suggestion", - - docs: { - description: "disallow unnecessary escape characters", - category: "Best Practices", - recommended: true, - url: "https://eslint.org/docs/rules/no-useless-escape" - }, - - schema: [] - }, - - 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: sourceCode.getLocFromIndex(sourceCode.getIndexFromLoc(node.loc.start) + startOffset), - message: "Unnecessary escape character: \\{{character}}.", - data: { character } - }); - } - - /** - * Checks if the escape character in given string slice is unnecessary. - * - * @private - * @param {ASTNode} node - node to validate. - * @param {string} match - string slice to validate. - * @returns {void} - */ - function validateString(node, match) { - const isTemplateElement = node.type === "TemplateElement"; - const escapedChar = match[0][1]; - let isUnnecessaryEscape = !VALID_STRING_ESCAPES.has(escapedChar); - let isQuoteEscape; - - if (isTemplateElement) { - isQuoteEscape = escapedChar === "`"; - - if (escapedChar === "$") { - - // Warn if `\$` is not followed by `{` - isUnnecessaryEscape = match.input[match.index + 2] !== "{"; - } else if (escapedChar === "{") { - - /* - * Warn if `\{` is not preceded by `$`. If preceded by `$`, escaping - * is necessary and the rule should not warn. If preceded by `/$`, the rule - * will warn for the `/$` instead, as it is the first unnecessarily escaped character. - */ - isUnnecessaryEscape = match.input[match.index - 1] !== "$"; - } - } else { - isQuoteEscape = escapedChar === node.raw[0]; - } - - if (isUnnecessaryEscape && !isQuoteEscape) { - report(node, match.index + 1, match[0].slice(1)); - } - } - - /** - * Checks if a node has an escape. - * - * @param {ASTNode} node - node to check. - * @returns {void} - */ - function check(node) { - const isTemplateElement = node.type === "TemplateElement"; - - if ( - isTemplateElement && - node.parent && - node.parent.parent && - node.parent.parent.type === "TaggedTemplateExpression" && - node.parent === node.parent.parent.quasi - ) { - - // Don't report tagged template literals, because the backslash character is accessible to the tag function. - return; - } - - if (typeof node.value === "string" || isTemplateElement) { - - /* - * 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" || node.parent.type === "JSXElement" || node.parent.type === "JSXFragment") { - return; - } - - 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) { - parseRegExp(node.regex.pattern) - - /* - * 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 { - Literal: check, - TemplateElement: check - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-useless-rename.js b/tools/node_modules/eslint/lib/rules/no-useless-rename.js deleted file mode 100644 index c1860645ea698e..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-useless-rename.js +++ /dev/null @@ -1,152 +0,0 @@ -/** - * @fileoverview Disallow renaming import, export, and destructured assignments to the same name. - * @author Kai Cataldo - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow renaming import, export, and destructured assignments to the same name", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/no-useless-rename" - }, - - fixable: "code", - - schema: [ - { - type: "object", - properties: { - ignoreDestructuring: { type: "boolean", default: false }, - ignoreImport: { type: "boolean", default: false }, - ignoreExport: { type: "boolean", default: false } - }, - additionalProperties: false - } - ] - }, - - create(context) { - const options = context.options[0] || {}, - ignoreDestructuring = options.ignoreDestructuring === true, - ignoreImport = options.ignoreImport === true, - ignoreExport = options.ignoreExport === true; - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Reports error for unnecessarily renamed assignments - * @param {ASTNode} node - node to report - * @param {ASTNode} initial - node with initial name value - * @param {ASTNode} result - node with new name value - * @param {string} type - the type of the offending node - * @returns {void} - */ - function reportError(node, initial, result, type) { - const name = initial.type === "Identifier" ? initial.name : initial.value; - - return context.report({ - node, - message: "{{type}} {{name}} unnecessarily renamed.", - data: { - name, - type - }, - fix(fixer) { - return fixer.replaceTextRange([ - initial.range[0], - result.range[1] - ], name); - } - }); - } - - /** - * Checks whether a destructured assignment is unnecessarily renamed - * @param {ASTNode} node - node to check - * @returns {void} - */ - function checkDestructured(node) { - if (ignoreDestructuring) { - return; - } - - const properties = node.properties; - - for (let i = 0; i < properties.length; i++) { - if (properties[i].shorthand) { - continue; - } - - /** - * If an ObjectPattern property is computed, we have no idea - * if a rename is useless or not. If an ObjectPattern property - * lacks a key, it is likely an ExperimentalRestProperty and - * so there is no "renaming" occurring here. - */ - if (properties[i].computed || !properties[i].key) { - continue; - } - - if (properties[i].key.type === "Identifier" && properties[i].key.name === properties[i].value.name || - properties[i].key.type === "Literal" && properties[i].key.value === properties[i].value.name) { - reportError(properties[i], properties[i].key, properties[i].value, "Destructuring assignment"); - } - } - } - - /** - * Checks whether an import is unnecessarily renamed - * @param {ASTNode} node - node to check - * @returns {void} - */ - function checkImport(node) { - if (ignoreImport) { - return; - } - - if (node.imported.name === node.local.name && - node.imported.range[0] !== node.local.range[0]) { - reportError(node, node.imported, node.local, "Import"); - } - } - - /** - * Checks whether an export is unnecessarily renamed - * @param {ASTNode} node - node to check - * @returns {void} - */ - function checkExport(node) { - if (ignoreExport) { - return; - } - - if (node.local.name === node.exported.name && - node.local.range[0] !== node.exported.range[0]) { - reportError(node, node.local, node.exported, "Export"); - } - - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - ObjectPattern: checkDestructured, - ImportSpecifier: checkImport, - ExportSpecifier: checkExport - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-useless-return.js b/tools/node_modules/eslint/lib/rules/no-useless-return.js deleted file mode 100644 index bb11b4b3619c8e..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-useless-return.js +++ /dev/null @@ -1,300 +0,0 @@ -/** - * @fileoverview Disallow redundant return statements - * @author Teddy Katz - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"), - FixTracker = require("../util/fix-tracker"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * 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) { - return astUtils.STATEMENT_LIST_PARENTS.has(node.parent.type); -} - -/** - * 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) { - for ( - let currentNode = node; - currentNode && currentNode.parent && !astUtils.isFunction(currentNode); - currentNode = currentNode.parent - ) { - if (currentNode.parent.type === "TryStatement" && currentNode.parent.finalizer === currentNode) { - return true; - } - } - - return false; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow redundant return statements", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-useless-return" - }, - - 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} [providedTraversedSegments] A set of segments that have already been traversed in this call - * @returns {ASTNode[]} `uselessReturns`. - */ - function getUselessReturns(uselessReturns, prevSegments, providedTraversedSegments) { - const traversedSegments = providedTraversedSegments || 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; - } - - uselessReturns.push(...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) { - if (isRemovable(node)) { - - /* - * Extend the replacement range to include the - * entire function to avoid conflicting with - * no-else-return. - * https://github.com/eslint/eslint/issues/8026 - */ - return new FixTracker(fixer, context.getSourceCode()) - .retainEnclosingFunction(node) - .remove(node); - } - return 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/node_modules/eslint/lib/rules/no-var.js b/tools/node_modules/eslint/lib/rules/no-var.js deleted file mode 100644 index edaed98f62e9d3..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-var.js +++ /dev/null @@ -1,331 +0,0 @@ -/** - * @fileoverview Rule to check for the usage of var. - * @author Jamund Ferguson - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Check whether a given variable is a global variable or not. - * @param {eslint-scope.Variable} variable The variable to check. - * @returns {boolean} `true` if the variable is a global variable. - */ -function isGlobal(variable) { - return Boolean(variable.scope) && variable.scope.type === "global"; -} - -/** - * Finds the nearest function scope or global scope walking up the scope - * hierarchy. - * - * @param {eslint-scope.Scope} scope - The scope to traverse. - * @returns {eslint-scope.Scope} a function scope or global scope containing the given - * scope. - */ -function getEnclosingFunctionScope(scope) { - let currentScope = scope; - - while (currentScope.type !== "function" && currentScope.type !== "global") { - currentScope = currentScope.upper; - } - return currentScope; -} - -/** - * Checks whether the given variable has any references from a more specific - * function expression (i.e. a closure). - * - * @param {eslint-scope.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)$/; - -/** - * Gets the scope node which directly contains a given node. - * - * @param {ASTNode} node - A node to get. This is a `VariableDeclaration` or - * an `Identifier`. - * @returns {ASTNode} A scope node. This is one of `Program`, `BlockStatement`, - * `SwitchStatement`, `ForStatement`, `ForInStatement`, and - * `ForOfStatement`. - */ -function getScopeNode(node) { - for (let currentNode = node; currentNode; currentNode = currentNode.parent) { - if (SCOPE_NODE_TYPE.test(currentNode.type)) { - return currentNode; - } - } - - /* istanbul ignore next : unreachable */ - return null; -} - -/** - * Checks whether a given variable is redeclared or not. - * - * @param {eslint-scope.Variable} variable - A variable to check. - * @returns {boolean} `true` if the variable is redeclared. - */ -function isRedeclared(variable) { - return variable.defs.length >= 2; -} - -/** - * Checks whether a given variable is used from outside of the specified scope. - * - * @param {ASTNode} scopeNode - A scope node to check. - * @returns {Function} The predicate function which checks whether a given - * variable is used from outside of the specified scope. - */ -function isUsedFromOutsideOf(scopeNode) { - - /** - * Checks whether a given reference is inside of the specified scope or not. - * - * @param {eslint-scope.Reference} reference - A reference to check. - * @returns {boolean} `true` if the reference is inside of the specified - * scope. - */ - function isOutsideOfScope(reference) { - const scope = scopeNode.range; - const id = reference.identifier.range; - - return id[0] < scope[0] || id[1] > scope[1]; - } - - return function(variable) { - return variable.references.some(isOutsideOfScope); - }; -} - -/** - * Creates the predicate function which checks whether a variable has their references in TDZ. - * - * The predicate function would return `true`: - * - * - if a reference is before the declarator. E.g. (var a = b, b = 1;)(var {a = b, b} = {};) - * - if a reference is in the expression of their default value. E.g. (var {a = a} = {};) - * - if a reference is in the expression of their initializer. E.g. (var a = a;) - * - * @param {ASTNode} node - The initializer node of VariableDeclarator. - * @returns {Function} The predicate function. - * @private - */ -function hasReferenceInTDZ(node) { - const initStart = node.range[0]; - const initEnd = node.range[1]; - - return variable => { - const id = variable.defs[0].name; - const idStart = id.range[0]; - const defaultValue = (id.parent.type === "AssignmentPattern" ? id.parent.right : null); - const defaultStart = defaultValue && defaultValue.range[0]; - const defaultEnd = defaultValue && defaultValue.range[1]; - - return variable.references.some(reference => { - const start = reference.identifier.range[0]; - const end = reference.identifier.range[1]; - - return !reference.init && ( - start < idStart || - (defaultValue !== null && start >= defaultStart && end <= defaultEnd) || - (start >= initStart && end <= initEnd) - ); - }); - }; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require `let` or `const` instead of `var`", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/no-var" - }, - - schema: [], - fixable: "code" - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - /** - * Checks whether the variables which are defined by the given declarator node have their references in TDZ. - * - * @param {ASTNode} declarator - The VariableDeclarator node to check. - * @returns {boolean} `true` if one of the variables which are defined by the given declarator node have their references in TDZ. - */ - function hasSelfReferenceInTDZ(declarator) { - if (!declarator.init) { - return false; - } - const variables = context.getDeclaredVariables(declarator); - - return variables.some(hasReferenceInTDZ(declarator.init)); - } - - /** - * Checks whether it can fix a given variable declaration or not. - * It cannot fix if the following cases: - * - * - A variable is a global variable. - * - 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 might be used in TDZ. - * - A variable is declared in statement position (e.g. a single-line `IfStatement`) - * - * ## A variable is declared on a SwitchCase node. - * - * If this rule modifies 'var' declarations on a SwitchCase node, it - * would generate the warnings of 'no-case-declarations' rule. And the - * 'eslint:recommended' preset includes 'no-case-declarations' rule, so - * this rule doesn't modify those declarations. - * - * ## A variable is redeclared. - * - * The language spec disallows redeclarations of `let` declarations. - * Those variables would cause syntax errors. - * - * ## A variable is used from outside the scope. - * - * 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. - */ - function canFix(node) { - const variables = context.getDeclaredVariables(node); - const scopeNode = getScopeNode(node); - - if (node.parent.type === "SwitchCase" || - node.declarations.some(hasSelfReferenceInTDZ) || - variables.some(isGlobal) || - 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; - } - } - - if ( - !isLoopAssignee(node) && - !(node.parent.type === "ForStatement" && node.parent.init === node) && - !astUtils.STATEMENT_LIST_PARENTS.has(node.parent.type) - ) { - - // If the declaration is not in a block, e.g. `if (foo) var bar = 1;`, then it can't be fixed. - return false; - } - - return true; - } - - /** - * Reports a given variable declaration node. - * - * @param {ASTNode} node - A variable declaration node to report. - * @returns {void} - */ - function report(node) { - const varToken = sourceCode.getFirstToken(node); - - context.report({ - node, - message: "Unexpected var, use let or const instead.", - - fix(fixer) { - if (canFix(node)) { - return fixer.replaceText(varToken, "let"); - } - return null; - } - }); - } - - return { - "VariableDeclaration:exit"(node) { - if (node.kind === "var") { - report(node); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-void.js b/tools/node_modules/eslint/lib/rules/no-void.js deleted file mode 100644 index d2b5d2f9631dff..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-void.js +++ /dev/null @@ -1,40 +0,0 @@ -/** - * @fileoverview Rule to disallow use of void operator. - * @author Mike Sidorov - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow `void` operators", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-void" - }, - - schema: [] - }, - - create(context) { - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - UnaryExpression(node) { - if (node.operator === "void") { - context.report({ node, message: "Expected 'undefined' and instead saw 'void'." }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-warning-comments.js b/tools/node_modules/eslint/lib/rules/no-warning-comments.js deleted file mode 100644 index 9ea39b490f824d..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-warning-comments.js +++ /dev/null @@ -1,159 +0,0 @@ -/** - * @fileoverview Rule that warns about used warning comments - * @author Alexander Schmidt - */ - -"use strict"; - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow specified warning terms in comments", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-warning-comments" - }, - - schema: [ - { - type: "object", - properties: { - terms: { - type: "array", - items: { - type: "string" - } - }, - location: { - enum: ["start", "anywhere"] - } - }, - additionalProperties: false - } - ] - }, - - create(context) { - - const sourceCode = context.getSourceCode(), - configuration = context.options[0] || {}, - warningTerms = configuration.terms || ["todo", "fixme", "xxx"], - location = configuration.location || "start", - selfConfigRegEx = /\bno-warning-comments\b/; - - /** - * Convert a warning term into a RegExp which will match a comment containing that whole word in the specified - * location ("start" or "anywhere"). If the term starts or ends with non word characters, then the match will not - * require word boundaries on that side. - * - * @param {string} term A term to convert to a RegExp - * @returns {RegExp} The term converted to a RegExp - */ - function convertToRegExp(term) { - const escaped = term.replace(/[-/\\$^*+?.()|[\]{}]/g, "\\$&"); - const wordBoundary = "\\b"; - const eitherOrWordBoundary = `|${wordBoundary}`; - let prefix; - - /* - * If the term ends in a word character (a-z0-9_), ensure a word - * boundary at the end, so that substrings do not get falsely - * matched. eg "todo" in a string such as "mastodon". - * If the term ends in a non-word character, then \b won't match on - * the boundary to the next non-word character, which would likely - * be a space. For example `/\bFIX!\b/.test('FIX! blah') === false`. - * In these cases, use no bounding match. Same applies for the - * prefix, handled below. - */ - const suffix = /\w$/.test(term) ? "\\b" : ""; - - if (location === "start") { - - /* - * When matching at the start, ignore leading whitespace, and - * there's no need to worry about word boundaries. - */ - prefix = "^\\s*"; - } else if (/^\w/.test(term)) { - prefix = wordBoundary; - } else { - prefix = ""; - } - - if (location === "start") { - - /* - * For location "start" the regex should be - * ^\s*TERM\b. This checks the word boundary - * at the beginning of the comment. - */ - return new RegExp(prefix + escaped + suffix, "i"); - } - - /* - * For location "anywhere" the regex should be - * \bTERM\b|\bTERM\b, this checks the entire comment - * for the term. - */ - return new RegExp(prefix + escaped + suffix + eitherOrWordBoundary + term + wordBoundary, "i"); - } - - const warningRegExps = warningTerms.map(convertToRegExp); - - /** - * Checks the specified comment for matches of the configured warning terms and returns the matches. - * @param {string} comment The comment which is checked. - * @returns {Array} All matched warning terms for this comment. - */ - function commentContainsWarningTerm(comment) { - const matches = []; - - warningRegExps.forEach((regex, index) => { - if (regex.test(comment)) { - matches.push(warningTerms[index]); - } - }); - - return matches; - } - - /** - * Checks the specified node for matching warning comments and reports them. - * @param {ASTNode} node The AST node being checked. - * @returns {void} undefined. - */ - function checkComment(node) { - if (astUtils.isDirectiveComment(node) && selfConfigRegEx.test(node.value)) { - return; - } - - const matches = commentContainsWarningTerm(node.value); - - matches.forEach(matchedTerm => { - context.report({ - node, - message: "Unexpected '{{matchedTerm}}' comment.", - data: { - matchedTerm - } - }); - }); - } - - return { - Program() { - const comments = sourceCode.getAllComments(); - - comments.filter(token => token.type !== "Shebang").forEach(checkComment); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-whitespace-before-property.js b/tools/node_modules/eslint/lib/rules/no-whitespace-before-property.js deleted file mode 100644 index 1ecc51db67c030..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-whitespace-before-property.js +++ /dev/null @@ -1,97 +0,0 @@ -/** - * @fileoverview Rule to disallow whitespace before properties - * @author Kai Cataldo - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "disallow whitespace before properties", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/no-whitespace-before-property" - }, - - fixable: "whitespace", - schema: [] - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Reports whitespace before property token - * @param {ASTNode} node - the node to report in the event of an error - * @param {Token} leftToken - the left token - * @param {Token} rightToken - the right token - * @returns {void} - * @private - */ - function reportError(node, leftToken, rightToken) { - const replacementText = node.computed ? "" : "."; - - context.report({ - node, - message: "Unexpected whitespace before property {{propName}}.", - data: { - propName: sourceCode.getText(node.property) - }, - fix(fixer) { - if (!node.computed && astUtils.isDecimalInteger(node.object)) { - - /* - * If the object is a number literal, fixing it to something like 5.toString() would cause a SyntaxError. - * Don't fix this case. - */ - return null; - } - return fixer.replaceTextRange([leftToken.range[1], rightToken.range[0]], replacementText); - } - }); - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - MemberExpression(node) { - let rightToken; - let leftToken; - - if (!astUtils.isTokenOnSameLine(node.object, node.property)) { - return; - } - - if (node.computed) { - rightToken = sourceCode.getTokenBefore(node.property, astUtils.isOpeningBracketToken); - leftToken = sourceCode.getTokenBefore(rightToken); - } else { - rightToken = sourceCode.getFirstToken(node.property); - leftToken = sourceCode.getTokenBefore(rightToken, 1); - } - - if (sourceCode.isSpaceBetweenTokens(leftToken, rightToken)) { - reportError(node, leftToken, rightToken); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-with.js b/tools/node_modules/eslint/lib/rules/no-with.js deleted file mode 100644 index ecdf22c7d91d6a..00000000000000 --- a/tools/node_modules/eslint/lib/rules/no-with.js +++ /dev/null @@ -1,35 +0,0 @@ -/** - * @fileoverview Rule to flag use of with statement - * @author Nicholas C. Zakas - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow `with` statements", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-with" - }, - - schema: [] - }, - - create(context) { - - return { - WithStatement(node) { - context.report({ node, message: "Unexpected use of 'with' statement." }); - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/nonblock-statement-body-position.js b/tools/node_modules/eslint/lib/rules/nonblock-statement-body-position.js deleted file mode 100644 index 01763cea92f381..00000000000000 --- a/tools/node_modules/eslint/lib/rules/nonblock-statement-body-position.js +++ /dev/null @@ -1,119 +0,0 @@ -/** - * @fileoverview enforce the location of single-line statements - * @author Teddy Katz - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -const POSITION_SCHEMA = { enum: ["beside", "below", "any"] }; - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce the location of single-line statements", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/nonblock-statement-body-position" - }, - - fixable: "whitespace", - - schema: [ - POSITION_SCHEMA, - { - properties: { - overrides: { - properties: { - if: POSITION_SCHEMA, - else: POSITION_SCHEMA, - while: POSITION_SCHEMA, - do: POSITION_SCHEMA, - for: POSITION_SCHEMA - }, - additionalProperties: false - } - }, - additionalProperties: false - } - ] - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - //---------------------------------------------------------------------- - // Helpers - //---------------------------------------------------------------------- - - /** - * Gets the applicable preference for a particular keyword - * @param {string} keywordName The name of a keyword, e.g. 'if' - * @returns {string} The applicable option for the keyword, e.g. 'beside' - */ - function getOption(keywordName) { - return context.options[1] && context.options[1].overrides && context.options[1].overrides[keywordName] || - context.options[0] || - "beside"; - } - - /** - * Validates the location of a single-line statement - * @param {ASTNode} node The single-line statement - * @param {string} keywordName The applicable keyword name for the single-line statement - * @returns {void} - */ - function validateStatement(node, keywordName) { - const option = getOption(keywordName); - - if (node.type === "BlockStatement" || option === "any") { - return; - } - - const tokenBefore = sourceCode.getTokenBefore(node); - - if (tokenBefore.loc.end.line === node.loc.start.line && option === "below") { - context.report({ - node, - message: "Expected a linebreak before this statement.", - fix: fixer => fixer.insertTextBefore(node, "\n") - }); - } else if (tokenBefore.loc.end.line !== node.loc.start.line && option === "beside") { - context.report({ - node, - message: "Expected no linebreak before this statement.", - fix(fixer) { - if (sourceCode.getText().slice(tokenBefore.range[1], node.range[0]).trim()) { - return null; - } - return fixer.replaceTextRange([tokenBefore.range[1], node.range[0]], " "); - } - }); - } - } - - //---------------------------------------------------------------------- - // Public - //---------------------------------------------------------------------- - - return { - IfStatement(node) { - validateStatement(node.consequent, "if"); - - // Check the `else` node, but don't check 'else if' statements. - if (node.alternate && node.alternate.type !== "IfStatement") { - validateStatement(node.alternate, "else"); - } - }, - WhileStatement: node => validateStatement(node.body, "while"), - DoWhileStatement: node => validateStatement(node.body, "do"), - ForStatement: node => validateStatement(node.body, "for"), - ForInStatement: node => validateStatement(node.body, "for"), - ForOfStatement: node => validateStatement(node.body, "for") - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/object-curly-newline.js b/tools/node_modules/eslint/lib/rules/object-curly-newline.js deleted file mode 100644 index d45620d53c568f..00000000000000 --- a/tools/node_modules/eslint/lib/rules/object-curly-newline.js +++ /dev/null @@ -1,304 +0,0 @@ -/** - * @fileoverview Rule to require or disallow line breaks inside braces. - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); -const lodash = require("lodash"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -// Schema objects. -const OPTION_VALUE = { - oneOf: [ - { - enum: ["always", "never"] - }, - { - type: "object", - properties: { - multiline: { - type: "boolean", - default: false - }, - minProperties: { - type: "integer", - minimum: 0 - }, - consistent: { - type: "boolean", - default: false - } - }, - additionalProperties: false, - minProperties: 1 - } - ] -}; - -/** - * Normalizes a given option value. - * - * @param {string|Object|undefined} value - An option value to parse. - * @returns {{multiline: boolean, minProperties: number, consistent: boolean}} Normalized option object. - */ -function normalizeOptionValue(value) { - let multiline = false; - let minProperties = Number.POSITIVE_INFINITY; - let consistent = false; - - if (value) { - if (value === "always") { - minProperties = 0; - } else if (value === "never") { - minProperties = Number.POSITIVE_INFINITY; - } else { - multiline = value.multiline; - minProperties = value.minProperties || Number.POSITIVE_INFINITY; - consistent = value.consistent; - } - } else { - consistent = true; - } - - return { multiline, minProperties, consistent }; -} - -/** - * Normalizes a given option value. - * - * @param {string|Object|undefined} options - An option value to parse. - * @returns {{ - * ObjectExpression: {multiline: boolean, minProperties: number, consistent: boolean}, - * ObjectPattern: {multiline: boolean, minProperties: number, consistent: boolean}, - * ImportDeclaration: {multiline: boolean, minProperties: number, consistent: boolean}, - * ExportNamedDeclaration : {multiline: boolean, minProperties: number, consistent: boolean} - * }} Normalized option object. - */ -function normalizeOptions(options) { - const isNodeSpecificOption = lodash.overSome([lodash.isPlainObject, lodash.isString]); - - if (lodash.isPlainObject(options) && lodash.some(options, isNodeSpecificOption)) { - return { - ObjectExpression: normalizeOptionValue(options.ObjectExpression), - ObjectPattern: normalizeOptionValue(options.ObjectPattern), - ImportDeclaration: normalizeOptionValue(options.ImportDeclaration), - ExportNamedDeclaration: normalizeOptionValue(options.ExportDeclaration) - }; - } - - const value = normalizeOptionValue(options); - - return { ObjectExpression: value, ObjectPattern: value, ImportDeclaration: value, ExportNamedDeclaration: value }; -} - -/** - * Determines if ObjectExpression, ObjectPattern, ImportDeclaration or ExportNamedDeclaration - * node needs to be checked for missing line breaks - * - * @param {ASTNode} node - Node under inspection - * @param {Object} options - option specific to node type - * @param {Token} first - First object property - * @param {Token} last - Last object property - * @returns {boolean} `true` if node needs to be checked for missing line breaks - */ -function areLineBreaksRequired(node, options, first, last) { - let objectProperties; - - if (node.type === "ObjectExpression" || node.type === "ObjectPattern") { - objectProperties = node.properties; - } else { - - // is ImportDeclaration or ExportNamedDeclaration - objectProperties = node.specifiers - .filter(s => s.type === "ImportSpecifier" || s.type === "ExportSpecifier"); - } - - return objectProperties.length >= options.minProperties || - ( - options.multiline && - objectProperties.length > 0 && - first.loc.start.line !== last.loc.end.line - ); -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce consistent line breaks inside braces", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/object-curly-newline" - }, - - fixable: "whitespace", - - schema: [ - { - oneOf: [ - OPTION_VALUE, - { - type: "object", - properties: { - ObjectExpression: OPTION_VALUE, - ObjectPattern: OPTION_VALUE, - ImportDeclaration: OPTION_VALUE, - ExportDeclaration: OPTION_VALUE - }, - additionalProperties: false, - minProperties: 1 - } - ] - } - ] - }, - - create(context) { - const sourceCode = context.getSourceCode(); - const normalizedOptions = normalizeOptions(context.options[0]); - - /** - * Reports a given node if it violated this rule. - * @param {ASTNode} node - A node to check. This is an ObjectExpression, ObjectPattern, ImportDeclaration or ExportNamedDeclaration node. - * @returns {void} - */ - function check(node) { - const options = normalizedOptions[node.type]; - - if ( - (node.type === "ImportDeclaration" && - !node.specifiers.some(specifier => specifier.type === "ImportSpecifier")) || - (node.type === "ExportNamedDeclaration" && - !node.specifiers.some(specifier => specifier.type === "ExportSpecifier")) - ) { - return; - } - - const openBrace = sourceCode.getFirstToken(node, token => token.value === "{"); - - let closeBrace; - - if (node.typeAnnotation) { - closeBrace = sourceCode.getTokenBefore(node.typeAnnotation); - } else { - closeBrace = sourceCode.getLastToken(node, token => token.value === "}"); - } - - let first = sourceCode.getTokenAfter(openBrace, { includeComments: true }); - let last = sourceCode.getTokenBefore(closeBrace, { includeComments: true }); - - const needsLineBreaks = areLineBreaksRequired(node, options, first, last); - - const hasCommentsFirstToken = astUtils.isCommentToken(first); - const hasCommentsLastToken = astUtils.isCommentToken(last); - - /* - * Use tokens or comments to check multiline or not. - * But use only tokens to check whether line breaks are needed. - * This allows: - * var obj = { // eslint-disable-line foo - * a: 1 - * } - */ - first = sourceCode.getTokenAfter(openBrace); - last = sourceCode.getTokenBefore(closeBrace); - - if (needsLineBreaks) { - if (astUtils.isTokenOnSameLine(openBrace, first)) { - context.report({ - message: "Expected a line break after this opening brace.", - node, - loc: openBrace.loc.start, - fix(fixer) { - if (hasCommentsFirstToken) { - return null; - } - - return fixer.insertTextAfter(openBrace, "\n"); - } - }); - } - if (astUtils.isTokenOnSameLine(last, closeBrace)) { - context.report({ - message: "Expected a line break before this closing brace.", - node, - loc: closeBrace.loc.start, - fix(fixer) { - if (hasCommentsLastToken) { - return null; - } - - return fixer.insertTextBefore(closeBrace, "\n"); - } - }); - } - } else { - const consistent = options.consistent; - const hasLineBreakBetweenOpenBraceAndFirst = !astUtils.isTokenOnSameLine(openBrace, first); - const hasLineBreakBetweenCloseBraceAndLast = !astUtils.isTokenOnSameLine(last, closeBrace); - - if ( - (!consistent && hasLineBreakBetweenOpenBraceAndFirst) || - (consistent && hasLineBreakBetweenOpenBraceAndFirst && !hasLineBreakBetweenCloseBraceAndLast) - ) { - context.report({ - message: "Unexpected line break after this opening brace.", - node, - loc: openBrace.loc.start, - fix(fixer) { - if (hasCommentsFirstToken) { - return null; - } - - return fixer.removeRange([ - openBrace.range[1], - first.range[0] - ]); - } - }); - } - if ( - (!consistent && hasLineBreakBetweenCloseBraceAndLast) || - (consistent && !hasLineBreakBetweenOpenBraceAndFirst && hasLineBreakBetweenCloseBraceAndLast) - ) { - context.report({ - message: "Unexpected line break before this closing brace.", - node, - loc: closeBrace.loc.start, - fix(fixer) { - if (hasCommentsLastToken) { - return null; - } - - return fixer.removeRange([ - last.range[1], - closeBrace.range[0] - ]); - } - }); - } - } - } - - return { - ObjectExpression: check, - ObjectPattern: check, - ImportDeclaration: check, - ExportNamedDeclaration: check - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/object-curly-spacing.js b/tools/node_modules/eslint/lib/rules/object-curly-spacing.js deleted file mode 100644 index bde4f14253eeec..00000000000000 --- a/tools/node_modules/eslint/lib/rules/object-curly-spacing.js +++ /dev/null @@ -1,302 +0,0 @@ -/** - * @fileoverview Disallows or enforces spaces inside of object literals. - * @author Jamund Ferguson - */ -"use strict"; - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce consistent spacing inside braces", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/object-curly-spacing" - }, - - fixable: "whitespace", - - schema: [ - { - enum: ["always", "never"] - }, - { - type: "object", - properties: { - arraysInObjects: { - type: "boolean" - }, - objectsInObjects: { - type: "boolean" - } - }, - additionalProperties: false - } - ] - }, - - create(context) { - const spaced = context.options[0] === "always", - sourceCode = context.getSourceCode(); - - /** - * Determines whether an option is set, relative to the spacing option. - * If spaced is "always", then check whether option is set to false. - * If spaced is "never", then check whether option is set to true. - * @param {Object} option - The option to exclude. - * @returns {boolean} Whether or not the property is excluded. - */ - function isOptionSet(option) { - return context.options[1] ? context.options[1][option] === !spaced : false; - } - - const options = { - spaced, - arraysInObjectsException: isOptionSet("arraysInObjects"), - objectsInObjectsException: isOptionSet("objectsInObjects") - }; - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Reports that there shouldn't be a space after the first token - * @param {ASTNode} node - The node to report in the event of an error. - * @param {Token} token - The token to use for the report. - * @returns {void} - */ - function reportNoBeginningSpace(node, token) { - context.report({ - node, - loc: token.loc.start, - message: "There should be no space after '{{token}}'.", - data: { - token: token.value - }, - fix(fixer) { - const nextToken = context.getSourceCode().getTokenAfter(token); - - return fixer.removeRange([token.range[1], nextToken.range[0]]); - } - }); - } - - /** - * Reports that there shouldn't be a space before the last token - * @param {ASTNode} node - The node to report in the event of an error. - * @param {Token} token - The token to use for the report. - * @returns {void} - */ - function reportNoEndingSpace(node, token) { - context.report({ - node, - loc: token.loc.start, - message: "There should be no space before '{{token}}'.", - data: { - token: token.value - }, - fix(fixer) { - const previousToken = context.getSourceCode().getTokenBefore(token); - - return fixer.removeRange([previousToken.range[1], token.range[0]]); - } - }); - } - - /** - * Reports that there should be a space after the first token - * @param {ASTNode} node - The node to report in the event of an error. - * @param {Token} token - The token to use for the report. - * @returns {void} - */ - function reportRequiredBeginningSpace(node, token) { - context.report({ - node, - loc: token.loc.start, - message: "A space is required after '{{token}}'.", - data: { - token: token.value - }, - fix(fixer) { - return fixer.insertTextAfter(token, " "); - } - }); - } - - /** - * Reports that there should be a space before the last token - * @param {ASTNode} node - The node to report in the event of an error. - * @param {Token} token - The token to use for the report. - * @returns {void} - */ - function reportRequiredEndingSpace(node, token) { - context.report({ - node, - loc: token.loc.start, - message: "A space is required before '{{token}}'.", - data: { - token: token.value - }, - fix(fixer) { - return fixer.insertTextBefore(token, " "); - } - }); - } - - /** - * Determines if spacing in curly braces is valid. - * @param {ASTNode} node The AST node to check. - * @param {Token} first The first token to check (should be the opening brace) - * @param {Token} second The second token to check (should be first after the opening brace) - * @param {Token} penultimate The penultimate token to check (should be last before closing brace) - * @param {Token} last The last token to check (should be closing brace) - * @returns {void} - */ - function validateBraceSpacing(node, first, second, penultimate, last) { - if (astUtils.isTokenOnSameLine(first, second)) { - const firstSpaced = sourceCode.isSpaceBetweenTokens(first, second); - - if (options.spaced && !firstSpaced) { - reportRequiredBeginningSpace(node, first); - } - if (!options.spaced && firstSpaced) { - reportNoBeginningSpace(node, first); - } - } - - if (astUtils.isTokenOnSameLine(penultimate, last)) { - const shouldCheckPenultimate = ( - options.arraysInObjectsException && astUtils.isClosingBracketToken(penultimate) || - options.objectsInObjectsException && astUtils.isClosingBraceToken(penultimate) - ); - const penultimateType = shouldCheckPenultimate && sourceCode.getNodeByRangeIndex(penultimate.range[0]).type; - - const closingCurlyBraceMustBeSpaced = ( - options.arraysInObjectsException && penultimateType === "ArrayExpression" || - options.objectsInObjectsException && (penultimateType === "ObjectExpression" || penultimateType === "ObjectPattern") - ) ? !options.spaced : options.spaced; - - const lastSpaced = sourceCode.isSpaceBetweenTokens(penultimate, last); - - if (closingCurlyBraceMustBeSpaced && !lastSpaced) { - reportRequiredEndingSpace(node, last); - } - if (!closingCurlyBraceMustBeSpaced && lastSpaced) { - reportNoEndingSpace(node, last); - } - } - } - - /** - * Gets '}' token of an object node. - * - * Because the last token of object patterns might be a type annotation, - * this traverses tokens preceded by the last property, then returns the - * first '}' token. - * - * @param {ASTNode} node - The node to get. This node is an - * ObjectExpression or an ObjectPattern. And this node has one or - * more properties. - * @returns {Token} '}' token. - */ - function getClosingBraceOfObject(node) { - const lastProperty = node.properties[node.properties.length - 1]; - - return sourceCode.getTokenAfter(lastProperty, astUtils.isClosingBraceToken); - } - - /** - * Reports a given object node if spacing in curly braces is invalid. - * @param {ASTNode} node - An ObjectExpression or ObjectPattern node to check. - * @returns {void} - */ - function checkForObject(node) { - if (node.properties.length === 0) { - return; - } - - const first = sourceCode.getFirstToken(node), - last = getClosingBraceOfObject(node), - second = sourceCode.getTokenAfter(first), - penultimate = sourceCode.getTokenBefore(last); - - validateBraceSpacing(node, first, second, penultimate, last); - } - - /** - * Reports a given import node if spacing in curly braces is invalid. - * @param {ASTNode} node - An ImportDeclaration node to check. - * @returns {void} - */ - function checkForImport(node) { - if (node.specifiers.length === 0) { - return; - } - - let firstSpecifier = node.specifiers[0]; - const lastSpecifier = node.specifiers[node.specifiers.length - 1]; - - if (lastSpecifier.type !== "ImportSpecifier") { - return; - } - if (firstSpecifier.type !== "ImportSpecifier") { - firstSpecifier = node.specifiers[1]; - } - - const first = sourceCode.getTokenBefore(firstSpecifier), - last = sourceCode.getTokenAfter(lastSpecifier, astUtils.isNotCommaToken), - second = sourceCode.getTokenAfter(first), - penultimate = sourceCode.getTokenBefore(last); - - validateBraceSpacing(node, first, second, penultimate, last); - } - - /** - * Reports a given export node if spacing in curly braces is invalid. - * @param {ASTNode} node - An ExportNamedDeclaration node to check. - * @returns {void} - */ - function checkForExport(node) { - if (node.specifiers.length === 0) { - return; - } - - const firstSpecifier = node.specifiers[0], - lastSpecifier = node.specifiers[node.specifiers.length - 1], - first = sourceCode.getTokenBefore(firstSpecifier), - last = sourceCode.getTokenAfter(lastSpecifier, astUtils.isNotCommaToken), - second = sourceCode.getTokenAfter(first), - penultimate = sourceCode.getTokenBefore(last); - - validateBraceSpacing(node, first, second, penultimate, last); - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - - // var {x} = y; - ObjectPattern: checkForObject, - - // var y = {x: 'y'} - ObjectExpression: checkForObject, - - // import {y} from 'x'; - ImportDeclaration: checkForImport, - - // export {name} from 'yo'; - ExportNamedDeclaration: checkForExport - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/object-property-newline.js b/tools/node_modules/eslint/lib/rules/object-property-newline.js deleted file mode 100644 index bf777b5ff65ba2..00000000000000 --- a/tools/node_modules/eslint/lib/rules/object-property-newline.js +++ /dev/null @@ -1,94 +0,0 @@ -/** - * @fileoverview Rule to enforce placing object properties on separate lines. - * @author Vitor Balocco - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce placing object properties on separate lines", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/object-property-newline" - }, - - schema: [ - { - type: "object", - properties: { - allowAllPropertiesOnSameLine: { - type: "boolean", - default: false - }, - allowMultiplePropertiesPerLine: { // Deprecated - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - - fixable: "whitespace" - }, - - create(context) { - const allowSameLine = context.options[0] && ( - (context.options[0].allowAllPropertiesOnSameLine || context.options[0].allowMultiplePropertiesPerLine /* Deprecated */) - ); - const errorMessage = allowSameLine - ? "Object properties must go on a new line if they aren't all on the same line." - : "Object properties must go on a new line."; - - const sourceCode = context.getSourceCode(); - - return { - ObjectExpression(node) { - if (allowSameLine) { - if (node.properties.length > 1) { - const firstTokenOfFirstProperty = sourceCode.getFirstToken(node.properties[0]); - const lastTokenOfLastProperty = sourceCode.getLastToken(node.properties[node.properties.length - 1]); - - if (firstTokenOfFirstProperty.loc.end.line === lastTokenOfLastProperty.loc.start.line) { - - // All keys and values are on the same line - return; - } - } - } - - for (let i = 1; i < node.properties.length; i++) { - const lastTokenOfPreviousProperty = sourceCode.getLastToken(node.properties[i - 1]); - const firstTokenOfCurrentProperty = sourceCode.getFirstToken(node.properties[i]); - - if (lastTokenOfPreviousProperty.loc.end.line === firstTokenOfCurrentProperty.loc.start.line) { - context.report({ - node, - loc: firstTokenOfCurrentProperty.loc.start, - 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/node_modules/eslint/lib/rules/object-shorthand.js b/tools/node_modules/eslint/lib/rules/object-shorthand.js deleted file mode 100644 index 98917fb6ee20ce..00000000000000 --- a/tools/node_modules/eslint/lib/rules/object-shorthand.js +++ /dev/null @@ -1,467 +0,0 @@ -/** - * @fileoverview Rule to enforce concise object methods and properties. - * @author Jamund Ferguson - */ - -"use strict"; - -const OPTIONS = { - always: "always", - never: "never", - methods: "methods", - properties: "properties", - consistent: "consistent", - consistentAsNeeded: "consistent-as-needed" -}; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require or disallow method and property shorthand syntax for object literals", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/object-shorthand" - }, - - fixable: "code", - - schema: { - anyOf: [ - { - type: "array", - items: [ - { - enum: ["always", "methods", "properties", "never", "consistent", "consistent-as-needed"] - } - ], - minItems: 0, - maxItems: 1 - }, - { - type: "array", - items: [ - { - enum: ["always", "methods", "properties"] - }, - { - type: "object", - properties: { - avoidQuotes: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - minItems: 0, - maxItems: 2 - }, - { - type: "array", - items: [ - { - enum: ["always", "methods"] - }, - { - type: "object", - properties: { - ignoreConstructors: { - type: "boolean", - default: false - }, - avoidQuotes: { - type: "boolean", - default: false - }, - avoidExplicitReturnArrows: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - minItems: 0, - maxItems: 2 - } - ] - } - }, - - create(context) { - const APPLY = context.options[0] || OPTIONS.always; - const APPLY_TO_METHODS = APPLY === OPTIONS.methods || APPLY === OPTIONS.always; - const APPLY_TO_PROPS = APPLY === OPTIONS.properties || APPLY === OPTIONS.always; - const APPLY_NEVER = APPLY === OPTIONS.never; - const APPLY_CONSISTENT = APPLY === OPTIONS.consistent; - const APPLY_CONSISTENT_AS_NEEDED = APPLY === OPTIONS.consistentAsNeeded; - - 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 - //-------------------------------------------------------------------------- - - /** - * Determines if the first character of the name is a capital letter. - * @param {string} name The name of the node to evaluate. - * @returns {boolean} True if the first character of the property name is a capital letter, false if not. - * @private - */ - function isConstructor(name) { - const firstChar = name.charAt(0); - - return firstChar === firstChar.toUpperCase(); - } - - /** - * Determines if the property can have a shorthand form. - * @param {ASTNode} property Property AST node - * @returns {boolean} True if the property can have a shorthand form - * @private - * - */ - function canHaveShorthand(property) { - return (property.kind !== "set" && property.kind !== "get" && property.type !== "SpreadElement" && property.type !== "SpreadProperty" && property.type !== "ExperimentalSpreadProperty"); - } - - /** - * Checks whether a node is a string literal. - * @param {ASTNode} node - Any AST node. - * @returns {boolean} `true` if it is a string literal. - */ - function isStringLiteral(node) { - return node.type === "Literal" && typeof node.value === "string"; - } - - /** - * Determines if the property is a shorthand or not. - * @param {ASTNode} property Property AST node - * @returns {boolean} True if the property is considered shorthand, false if not. - * @private - * - */ - function isShorthand(property) { - - // property.method is true when `{a(){}}`. - return (property.shorthand || property.method); - } - - /** - * Determines if the property's key and method or value are named equally. - * @param {ASTNode} property Property AST node - * @returns {boolean} True if the key and value are named equally, false if not. - * @private - * - */ - function isRedundant(property) { - const value = property.value; - - if (value.type === "FunctionExpression") { - return !value.id; // Only anonymous should be shorthand method. - } - if (value.type === "Identifier") { - return astUtils.getStaticPropertyName(property) === value.name; - } - - return false; - } - - /** - * Ensures that an object's properties are consistently shorthand, or not shorthand at all. - * @param {ASTNode} node Property AST node - * @param {boolean} checkRedundancy Whether to check longform redundancy - * @returns {void} - * - */ - function checkConsistency(node, checkRedundancy) { - - // We are excluding getters/setters and spread properties as they are considered neither longform nor shorthand. - const properties = node.properties.filter(canHaveShorthand); - - // Do we still have properties left after filtering the getters and setters? - if (properties.length > 0) { - const shorthandProperties = properties.filter(isShorthand); - - /* - * If we do not have an equal number of longform properties as - * shorthand properties, we are using the annotations inconsistently - */ - if (shorthandProperties.length !== properties.length) { - - // We have at least 1 shorthand property - if (shorthandProperties.length > 0) { - 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, - * all the keys are redundant. - */ - const canAlwaysUseShorthand = properties.every(isRedundant); - - if (canAlwaysUseShorthand) { - 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.getFirstToken(node, astUtils.isOpeningBracketToken) - : sourceCode.getFirstToken(node.key); - const lastKeyToken = node.computed - ? sourceCode.getFirstTokenBetween(node.key, node.value, astUtils.isClosingBracketToken) - : sourceCode.getLastToken(node.key); - const keyText = sourceCode.text.slice(firstKeyToken.range[0], lastKeyToken.range[1]); - let keyPrefix = ""; - - if (sourceCode.commentsExistBetween(lastKeyToken, node.value)) { - return null; - } - - if (node.value.async) { - keyPrefix += "async "; - } - if (node.value.generator) { - keyPrefix += "*"; - } - - 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], node.range[1]], - keyPrefix + keyText + sourceCode.text.slice(tokenBeforeParams.range[1], node.value.range[1]) - ); - } - const arrowToken = sourceCode.getTokenBefore(node.value.body, { filter: 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], node.range[1]], - keyPrefix + keyText + newParamText + sourceCode.text.slice(arrowToken.range[1], node.value.range[1]) - ); - - } - - /** - * 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.async) { - functionHeader = `async ${functionHeader}`; - } - if (node.value.generator) { - functionHeader = `${functionHeader}*`; - } - - 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); - } else if (APPLY_CONSISTENT_AS_NEEDED) { - checkConsistency(node, true); - } - }, - - "Property:exit"(node) { - const isConciseProperty = node.method || node.shorthand; - - // Ignore destructuring assignment - if (node.parent.type === "ObjectPattern") { - return; - } - - // getters and setters are ignored - if (node.kind === "get" || node.kind === "set") { - return; - } - - // only computed methods can fail the following checks - 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))) { - const message = APPLY_NEVER ? "Expected longform method syntax." : "Expected longform method syntax for string literal keys."; - - // { x() {} } should be written as { x: function() {} } - context.report({ - node, - message, - fix: fixer => makeFunctionLongform(fixer, node) - }); - } else if (APPLY_NEVER) { - - // { x } should be written as { x: x } - context.report({ - node, - message: "Expected longform property syntax.", - fix: fixer => fixer.insertTextAfter(node.key, `: ${node.key.name}`) - }); - } - } else if (APPLY_TO_METHODS && !node.value.id && (node.value.type === "FunctionExpression" || node.value.type === "ArrowFunctionExpression")) { - if (IGNORE_CONSTRUCTORS && node.key.type === "Identifier" && isConstructor(node.key.name)) { - return; - } - if (AVOID_QUOTES && isStringLiteral(node.key)) { - return; - } - - // {[x]: function(){}} should be written as {[x]() {}} - 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 => makeFunctionShorthand(fixer, node) - }); - } - } else if (node.value.type === "Identifier" && node.key.name === node.value.name && APPLY_TO_PROPS) { - - // {x: x} should be written as {x} - context.report({ - node, - message: "Expected property shorthand.", - fix(fixer) { - return fixer.replaceText(node, node.value.name); - } - }); - } else if (node.value.type === "Identifier" && node.key.type === "Literal" && node.key.value === node.value.name && APPLY_TO_PROPS) { - if (AVOID_QUOTES) { - return; - } - - // {"x": x} should be written as {x} - context.report({ - node, - message: "Expected property shorthand.", - fix(fixer) { - return fixer.replaceText(node, node.value.name); - } - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/one-var-declaration-per-line.js b/tools/node_modules/eslint/lib/rules/one-var-declaration-per-line.js deleted file mode 100644 index e7e40d66c0ced4..00000000000000 --- a/tools/node_modules/eslint/lib/rules/one-var-declaration-per-line.js +++ /dev/null @@ -1,89 +0,0 @@ -/** - * @fileoverview Rule to check multiple var declarations per line - * @author Alberto Rodríguez - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require or disallow newlines around variable declarations", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/one-var-declaration-per-line" - }, - - schema: [ - { - enum: ["always", "initializations"] - } - ], - - fixable: "whitespace" - }, - - create(context) { - - const ERROR_MESSAGE = "Expected variable declaration to be on a new line."; - const always = context.options[0] === "always"; - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - - /** - * Determine if provided keyword is a variant of for specifiers - * @private - * @param {string} keyword - keyword to test - * @returns {boolean} True if `keyword` is a variant of for specifier - */ - function isForTypeSpecifier(keyword) { - return keyword === "ForStatement" || keyword === "ForInStatement" || keyword === "ForOfStatement"; - } - - /** - * Checks newlines around variable declarations. - * @private - * @param {ASTNode} node - `VariableDeclaration` node to test - * @returns {void} - */ - function checkForNewLine(node) { - if (isForTypeSpecifier(node.parent.type)) { - return; - } - - const declarations = node.declarations; - let prev; - - declarations.forEach(current => { - if (prev && prev.loc.end.line === current.loc.start.line) { - if (always || prev.init || current.init) { - context.report({ - node, - message: ERROR_MESSAGE, - loc: current.loc.start, - fix: fixer => fixer.insertTextBefore(current, "\n") - }); - } - } - prev = current; - }); - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - VariableDeclaration: checkForNewLine - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/one-var.js b/tools/node_modules/eslint/lib/rules/one-var.js deleted file mode 100644 index 5a5c71b1874e01..00000000000000 --- a/tools/node_modules/eslint/lib/rules/one-var.js +++ /dev/null @@ -1,529 +0,0 @@ -/** - * @fileoverview A rule to control the use of single variable declarations. - * @author Ian Christian Myers - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce variables to be declared either together or separately in functions", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/one-var" - }, - - fixable: "code", - - schema: [ - { - oneOf: [ - { - enum: ["always", "never", "consecutive"] - }, - { - type: "object", - properties: { - separateRequires: { - type: "boolean", - default: false - }, - var: { - enum: ["always", "never", "consecutive"], - default: "always" - }, - let: { - enum: ["always", "never", "consecutive"], - default: "always" - }, - const: { - enum: ["always", "never", "consecutive"], - default: "always" - } - }, - additionalProperties: false - }, - { - type: "object", - properties: { - initialized: { - enum: ["always", "never", "consecutive"] - }, - uninitialized: { - enum: ["always", "never", "consecutive"] - } - }, - additionalProperties: false - } - ] - } - ] - }, - - create(context) { - const MODE_ALWAYS = "always"; - const MODE_NEVER = "never"; - const MODE_CONSECUTIVE = "consecutive"; - const mode = context.options[0] || MODE_ALWAYS; - - const options = {}; - - 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 }; - } else if (typeof mode === "object") { // options configuration is an object - options.separateRequires = mode.separateRequires; - options.var = { uninitialized: mode.var, initialized: mode.var }; - options.let = { uninitialized: mode.let, initialized: mode.let }; - options.const = { uninitialized: mode.const, initialized: mode.const }; - if (Object.prototype.hasOwnProperty.call(mode, "uninitialized")) { - options.var.uninitialized = mode.uninitialized; - options.let.uninitialized = mode.uninitialized; - options.const.uninitialized = mode.uninitialized; - } - if (Object.prototype.hasOwnProperty.call(mode, "initialized")) { - options.var.initialized = mode.initialized; - options.let.initialized = mode.initialized; - options.const.initialized = mode.initialized; - } - } - - const sourceCode = context.getSourceCode(); - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - const functionStack = []; - const blockStack = []; - - /** - * Increments the blockStack counter. - * @returns {void} - * @private - */ - function startBlock() { - blockStack.push({ - let: { initialized: false, uninitialized: false }, - const: { initialized: false, uninitialized: false } - }); - } - - /** - * Increments the functionStack counter. - * @returns {void} - * @private - */ - function startFunction() { - functionStack.push({ initialized: false, uninitialized: false }); - startBlock(); - } - - /** - * Decrements the blockStack counter. - * @returns {void} - * @private - */ - function endBlock() { - blockStack.pop(); - } - - /** - * Decrements the functionStack counter. - * @returns {void} - * @private - */ - function endFunction() { - functionStack.pop(); - endBlock(); - } - - /** - * Check if a variable declaration is a require. - * @param {ASTNode} decl variable declaration Node - * @returns {bool} if decl is a require, return true; else return false. - * @private - */ - function isRequire(decl) { - return decl.init && decl.init.type === "CallExpression" && decl.init.callee.name === "require"; - } - - /** - * Records whether initialized/uninitialized/required variables are defined in current scope. - * @param {string} statementType node.kind, one of: "var", "let", or "const" - * @param {ASTNode[]} declarations List of declarations - * @param {Object} currentScope The scope being investigated - * @returns {void} - * @private - */ - function recordTypes(statementType, declarations, currentScope) { - for (let i = 0; i < declarations.length; i++) { - if (declarations[i].init === null) { - if (options[statementType] && options[statementType].uninitialized === MODE_ALWAYS) { - currentScope.uninitialized = true; - } - } else { - if (options[statementType] && options[statementType].initialized === MODE_ALWAYS) { - if (options.separateRequires && isRequire(declarations[i])) { - currentScope.required = true; - } else { - currentScope.initialized = true; - } - } - } - } - } - - /** - * Determines the current scope (function or block) - * @param {string} statementType node.kind, one of: "var", "let", or "const" - * @returns {Object} The scope associated with statementType - */ - function getCurrentScope(statementType) { - let currentScope; - - if (statementType === "var") { - currentScope = functionStack[functionStack.length - 1]; - } else if (statementType === "let") { - currentScope = blockStack[blockStack.length - 1].let; - } else if (statementType === "const") { - currentScope = blockStack[blockStack.length - 1].const; - } - return currentScope; - } - - /** - * Counts the number of initialized and uninitialized declarations in a list of declarations - * @param {ASTNode[]} declarations List of declarations - * @returns {Object} Counts of 'uninitialized' and 'initialized' declarations - * @private - */ - function countDeclarations(declarations) { - const counts = { uninitialized: 0, initialized: 0 }; - - for (let i = 0; i < declarations.length; i++) { - if (declarations[i].init === null) { - counts.uninitialized++; - } else { - counts.initialized++; - } - } - return counts; - } - - /** - * Determines if there is more than one var statement in the current scope. - * @param {string} statementType node.kind, one of: "var", "let", or "const" - * @param {ASTNode[]} declarations List of declarations - * @returns {boolean} Returns true if it is the first var declaration, false if not. - * @private - */ - function hasOnlyOneStatement(statementType, declarations) { - - const declarationCounts = countDeclarations(declarations); - const currentOptions = options[statementType] || {}; - const currentScope = getCurrentScope(statementType); - const hasRequires = declarations.some(isRequire); - - if (currentOptions.uninitialized === MODE_ALWAYS && currentOptions.initialized === MODE_ALWAYS) { - if (currentScope.uninitialized || currentScope.initialized) { - if (!hasRequires) { - return false; - } - } - } - - if (declarationCounts.uninitialized > 0) { - if (currentOptions.uninitialized === MODE_ALWAYS && currentScope.uninitialized) { - return false; - } - } - if (declarationCounts.initialized > 0) { - if (currentOptions.initialized === MODE_ALWAYS && currentScope.initialized) { - if (!hasRequires) { - return false; - } - } - } - if (currentScope.required && hasRequires) { - return false; - } - recordTypes(statementType, declarations, currentScope); - return true; - } - - /** - * Fixer to join VariableDeclaration's into a single declaration - * @param {VariableDeclarator[]} declarations The `VariableDeclaration` to join - * @returns {Function} The fixer function - */ - function joinDeclarations(declarations) { - const declaration = declarations[0]; - const body = Array.isArray(declaration.parent.parent.body) ? declaration.parent.parent.body : []; - const currentIndex = body.findIndex(node => node.range[0] === declaration.parent.range[0]); - const previousNode = body[currentIndex - 1]; - - return fixer => { - const type = sourceCode.getTokenBefore(declaration); - const prevSemi = sourceCode.getTokenBefore(type); - const res = []; - - if (previousNode && previousNode.kind === sourceCode.getText(type)) { - if (prevSemi.value === ";") { - res.push(fixer.replaceText(prevSemi, ",")); - } else { - res.push(fixer.insertTextAfter(prevSemi, ",")); - } - res.push(fixer.replaceText(type, "")); - } - - return res; - }; - } - - /** - * Fixer to split a VariableDeclaration into individual declarations - * @param {VariableDeclaration} declaration The `VariableDeclaration` to split - * @returns {Function} The fixer function - */ - function splitDeclarations(declaration) { - return fixer => declaration.declarations.map(declarator => { - const tokenAfterDeclarator = sourceCode.getTokenAfter(declarator); - - if (tokenAfterDeclarator === null) { - return null; - } - - const afterComma = sourceCode.getTokenAfter(tokenAfterDeclarator, { includeComments: true }); - - if (tokenAfterDeclarator.value !== ",") { - return null; - } - - /* - * `var x,y` - * tokenAfterDeclarator ^^ afterComma - */ - if (afterComma.range[0] === tokenAfterDeclarator.range[1]) { - return fixer.replaceText(tokenAfterDeclarator, `; ${declaration.kind} `); - } - - /* - * `var x, - * tokenAfterDeclarator ^ - * y` - * ^ afterComma - */ - if ( - afterComma.loc.start.line > tokenAfterDeclarator.loc.end.line || - afterComma.type === "Line" || - afterComma.type === "Block" - ) { - let lastComment = afterComma; - - while (lastComment.type === "Line" || lastComment.type === "Block") { - lastComment = sourceCode.getTokenAfter(lastComment, { includeComments: true }); - } - - return fixer.replaceTextRange( - [tokenAfterDeclarator.range[0], lastComment.range[0]], - `;${sourceCode.text.slice(tokenAfterDeclarator.range[1], lastComment.range[0])}${declaration.kind} ` - ); - } - - return fixer.replaceText(tokenAfterDeclarator, `; ${declaration.kind}`); - }).filter(x => x); - } - - /** - * Checks a given VariableDeclaration node for errors. - * @param {ASTNode} node The VariableDeclaration node to check - * @returns {void} - * @private - */ - function checkVariableDeclaration(node) { - const parent = node.parent; - const type = node.kind; - - if (!options[type]) { - return; - } - - const declarations = node.declarations; - const declarationCounts = countDeclarations(declarations); - const mixedRequires = declarations.some(isRequire) && !declarations.every(isRequire); - - if (options[type].initialized === MODE_ALWAYS) { - if (options.separateRequires && mixedRequires) { - context.report({ - node, - message: "Split requires to be separated into a single block." - }); - } - } - - // consecutive - const nodeIndex = (parent.body && parent.body.length > 0 && parent.body.indexOf(node)) || 0; - - if (nodeIndex > 0) { - const previousNode = parent.body[nodeIndex - 1]; - const isPreviousNodeDeclaration = previousNode.type === "VariableDeclaration"; - const declarationsWithPrevious = declarations.concat(previousNode.declarations || []); - - if ( - isPreviousNodeDeclaration && - previousNode.kind === type && - !(declarationsWithPrevious.some(isRequire) && !declarationsWithPrevious.every(isRequire)) - ) { - const previousDeclCounts = countDeclarations(previousNode.declarations); - - if (options[type].initialized === MODE_CONSECUTIVE && options[type].uninitialized === MODE_CONSECUTIVE) { - context.report({ - node, - message: "Combine this with the previous '{{type}}' statement.", - data: { - type - }, - fix: joinDeclarations(declarations) - }); - } else if (options[type].initialized === MODE_CONSECUTIVE && declarationCounts.initialized > 0 && previousDeclCounts.initialized > 0) { - context.report({ - node, - message: "Combine this with the previous '{{type}}' statement with initialized variables.", - data: { - type - }, - fix: joinDeclarations(declarations) - }); - } else if (options[type].uninitialized === MODE_CONSECUTIVE && - declarationCounts.uninitialized > 0 && - previousDeclCounts.uninitialized > 0) { - context.report({ - node, - message: "Combine this with the previous '{{type}}' statement with uninitialized variables.", - data: { - type - }, - fix: joinDeclarations(declarations) - }); - } - } - } - - // always - if (!hasOnlyOneStatement(type, declarations)) { - if (options[type].initialized === MODE_ALWAYS && options[type].uninitialized === MODE_ALWAYS) { - context.report({ - node, - message: "Combine this with the previous '{{type}}' statement.", - data: { - type - }, - fix: joinDeclarations(declarations) - }); - } else { - if (options[type].initialized === MODE_ALWAYS && declarationCounts.initialized > 0) { - context.report({ - node, - message: "Combine this with the previous '{{type}}' statement with initialized variables.", - data: { - type - }, - fix: joinDeclarations(declarations) - }); - } - if (options[type].uninitialized === MODE_ALWAYS && declarationCounts.uninitialized > 0) { - if (node.parent.left === node && (node.parent.type === "ForInStatement" || node.parent.type === "ForOfStatement")) { - return; - } - context.report({ - node, - message: "Combine this with the previous '{{type}}' statement with uninitialized variables.", - data: { - type - }, - fix: joinDeclarations(declarations) - }); - } - } - } - - // never - if (parent.type !== "ForStatement" || parent.init !== node) { - const totalDeclarations = declarationCounts.uninitialized + declarationCounts.initialized; - - if (totalDeclarations > 1) { - if (options[type].initialized === MODE_NEVER && options[type].uninitialized === MODE_NEVER) { - - // both initialized and uninitialized - context.report({ - node, - message: "Split '{{type}}' declarations into multiple statements.", - data: { - type - }, - fix: splitDeclarations(node) - }); - } else if (options[type].initialized === MODE_NEVER && declarationCounts.initialized > 0) { - - // initialized - context.report({ - node, - message: "Split initialized '{{type}}' declarations into multiple statements.", - data: { - type - }, - fix: splitDeclarations(node) - }); - } else if (options[type].uninitialized === MODE_NEVER && declarationCounts.uninitialized > 0) { - - // uninitialized - context.report({ - node, - message: "Split uninitialized '{{type}}' declarations into multiple statements.", - data: { - type - }, - fix: splitDeclarations(node) - }); - } - } - } - } - - //-------------------------------------------------------------------------- - // Public API - //-------------------------------------------------------------------------- - - return { - Program: startFunction, - FunctionDeclaration: startFunction, - FunctionExpression: startFunction, - ArrowFunctionExpression: startFunction, - BlockStatement: startBlock, - ForStatement: startBlock, - ForInStatement: startBlock, - ForOfStatement: startBlock, - SwitchStatement: startBlock, - VariableDeclaration: checkVariableDeclaration, - "ForStatement:exit": endBlock, - "ForOfStatement:exit": endBlock, - "ForInStatement:exit": endBlock, - "SwitchStatement:exit": endBlock, - "BlockStatement:exit": endBlock, - "Program:exit": endFunction, - "FunctionDeclaration:exit": endFunction, - "FunctionExpression:exit": endFunction, - "ArrowFunctionExpression:exit": endFunction - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/operator-assignment.js b/tools/node_modules/eslint/lib/rules/operator-assignment.js deleted file mode 100644 index 94e85927344ce1..00000000000000 --- a/tools/node_modules/eslint/lib/rules/operator-assignment.js +++ /dev/null @@ -1,213 +0,0 @@ -/** - * @fileoverview Rule to replace assignment expressions with operator assignment - * @author Brandon Mills - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks whether an operator is commutative and has an operator assignment - * shorthand form. - * @param {string} operator Operator to check. - * @returns {boolean} True if the operator is commutative and has a - * shorthand form. - */ -function isCommutativeOperatorWithShorthand(operator) { - return ["*", "&", "^", "|"].indexOf(operator) >= 0; -} - -/** - * Checks whether an operator is not commuatative and has an operator assignment - * shorthand form. - * @param {string} operator Operator to check. - * @returns {boolean} True if the operator is not commuatative and has - * a shorthand form. - */ -function isNonCommutativeOperatorWithShorthand(operator) { - return ["+", "-", "/", "%", "<<", ">>", ">>>", "**"].indexOf(operator) >= 0; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -/** - * Checks whether two expressions reference the same value. For example: - * a = a - * a.b = a.b - * a[0] = a[0] - * a['b'] = a['b'] - * @param {ASTNode} a Left side of the comparison. - * @param {ASTNode} b Right side of the comparison. - * @returns {boolean} True if both sides match and reference the same value. - */ -function same(a, b) { - if (a.type !== b.type) { - return false; - } - - switch (a.type) { - case "Identifier": - return a.name === b.name; - - case "Literal": - return a.value === b.value; - - case "MemberExpression": - - /* - * x[0] = x[0] - * x[y] = x[y] - * x.y = x.y - */ - return same(a.object, b.object) && same(a.property, b.property); - - default: - return false; - } -} - -/** - * 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: { - type: "suggestion", - - docs: { - description: "require or disallow assignment operator shorthand where possible", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/operator-assignment" - }, - - schema: [ - { - enum: ["always", "never"] - } - ], - - fixable: "code", - messages: { - replaced: "Assignment can be replaced with operator assignment.", - unexpected: "Unexpected operator assignment shorthand." - } - }, - - 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.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator); - } - - /** - * Ensures that an assignment uses the shorthand form where possible. - * @param {ASTNode} node An AssignmentExpression node. - * @returns {void} - */ - function verify(node) { - if (node.operator !== "=" || node.right.type !== "BinaryExpression") { - return; - } - - const left = node.left; - const expr = node.right; - const operator = expr.operator; - - if (isCommutativeOperatorWithShorthand(operator) || isNonCommutativeOperatorWithShorthand(operator)) { - if (same(left, expr.left)) { - context.report({ - node, - messageId: "replaced", - 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.right.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, - messageId: "replaced" - }); - } - } - } - - /** - * Warns if an assignment expression uses operator assignment shorthand. - * @param {ASTNode} node An AssignmentExpression node. - * @returns {void} - */ - function prohibit(node) { - if (node.operator !== "=") { - context.report({ - node, - messageId: "unexpected", - fix(fixer) { - if (canBeFixed(node.left)) { - const operatorToken = getOperatorToken(node); - const leftText = sourceCode.getText().slice(node.range[0], operatorToken.range[0]); - const newOperator = node.operator.slice(0, -1); - let rightText; - - // If this change would modify precedence (e.g. `foo *= bar + 1` => `foo = foo * (bar + 1)`), parenthesize the right side. - if ( - astUtils.getPrecedence(node.right) <= astUtils.getPrecedence({ type: "BinaryExpression", operator: newOperator }) && - !astUtils.isParenthesised(sourceCode, node.right) - ) { - rightText = `${sourceCode.text.slice(operatorToken.range[1], node.right.range[0])}(${sourceCode.getText(node.right)})`; - } else { - rightText = sourceCode.text.slice(operatorToken.range[1], node.range[1]); - } - - return fixer.replaceText(node, `${leftText}= ${leftText}${newOperator}${rightText}`); - } - return null; - } - }); - } - } - - return { - AssignmentExpression: context.options[0] !== "never" ? verify : prohibit - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/operator-linebreak.js b/tools/node_modules/eslint/lib/rules/operator-linebreak.js deleted file mode 100644 index cd6e996b1b10bd..00000000000000 --- a/tools/node_modules/eslint/lib/rules/operator-linebreak.js +++ /dev/null @@ -1,255 +0,0 @@ -/** - * @fileoverview Operator linebreak - enforces operator linebreak style of two types: after and before - * @author Benoît Zugmeyer - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce consistent linebreak style for operators", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/operator-linebreak" - }, - - schema: [ - { - enum: ["after", "before", "none", null] - }, - { - type: "object", - properties: { - overrides: { - type: "object", - properties: { - anyOf: { - type: "string", - enum: ["after", "before", "none", "ignore"] - } - } - } - }, - additionalProperties: false - } - ], - - fixable: "code" - }, - - create(context) { - - const usedDefaultGlobal = !context.options[0]; - const globalStyle = context.options[0] || "after"; - const options = context.options[1] || {}; - const styleOverrides = options.overrides ? Object.assign({}, options.overrides) : {}; - - if (usedDefaultGlobal && !styleOverrides["?"]) { - styleOverrides["?"] = "before"; - } - - if (usedDefaultGlobal && !styleOverrides[":"]) { - styleOverrides[":"] = "before"; - } - - const sourceCode = context.getSourceCode(); - - //-------------------------------------------------------------------------- - // 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.getTokenBefore(operatorToken, { includeComments: true }) !== tokenBefore && - sourceCode.getTokenAfter(operatorToken, { includeComments: true }) !== 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 { - const LINEBREAK_REGEX = astUtils.createGlobalLinebreakMatcher(); - - // 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 - * @param {ASTNode} leftSide The node that comes before the operator in `node` - * @private - * @returns {void} - */ - function validateNode(node, leftSide) { - - /* - * When the left part of a binary expression is a single expression wrapped in - * parentheses (ex: `(a) + b`), leftToken will be the last token of the expression - * and operatorToken will be the closing parenthesis. - * The leftToken should be the last closing parenthesis, and the operatorToken - * should be the token right after that. - */ - const operatorToken = sourceCode.getTokenAfter(leftSide, astUtils.isNotClosingParenToken); - const leftToken = sourceCode.getTokenBefore(operatorToken); - const rightToken = sourceCode.getTokenAfter(operatorToken); - 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)) { - - // do nothing. - - } else if (operatorStyleOverride !== "ignore" && !astUtils.isTokenOnSameLine(leftToken, operatorToken) && - !astUtils.isTokenOnSameLine(operatorToken, rightToken)) { - - // lone operator - context.report({ - node, - loc: { - line: operatorToken.loc.end.line, - column: operatorToken.loc.end.column - }, - message: "Bad line breaking before and after '{{operator}}'.", - data: { - operator - }, - fix - }); - - } else if (style === "before" && astUtils.isTokenOnSameLine(leftToken, operatorToken)) { - - context.report({ - node, - loc: { - line: operatorToken.loc.end.line, - column: operatorToken.loc.end.column - }, - message: "'{{operator}}' should be placed at the beginning of the line.", - data: { - operator - }, - fix - }); - - } else if (style === "after" && astUtils.isTokenOnSameLine(operatorToken, rightToken)) { - - context.report({ - node, - loc: { - line: operatorToken.loc.end.line, - column: operatorToken.loc.end.column - }, - message: "'{{operator}}' should be placed at the end of the line.", - data: { - operator - }, - fix - }); - - } else if (style === "none") { - - context.report({ - node, - loc: { - line: operatorToken.loc.end.line, - column: operatorToken.loc.end.column - }, - message: "There should be no line break before or after '{{operator}}'.", - data: { - operator - }, - fix - }); - - } - } - - /** - * Validates a binary expression using `validateNode` - * @param {BinaryExpression|LogicalExpression|AssignmentExpression} node node to be validated - * @returns {void} - */ - function validateBinaryExpression(node) { - validateNode(node, node.left); - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - BinaryExpression: validateBinaryExpression, - LogicalExpression: validateBinaryExpression, - AssignmentExpression: validateBinaryExpression, - VariableDeclarator(node) { - if (node.init) { - validateNode(node, node.id); - } - }, - ConditionalExpression(node) { - validateNode(node, node.test); - validateNode(node, node.consequent); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/padded-blocks.js b/tools/node_modules/eslint/lib/rules/padded-blocks.js deleted file mode 100644 index e4dd37f4cdb42e..00000000000000 --- a/tools/node_modules/eslint/lib/rules/padded-blocks.js +++ /dev/null @@ -1,282 +0,0 @@ -/** - * @fileoverview A rule to ensure blank lines within blocks. - * @author Mathias Schreck - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "require or disallow padding within blocks", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/padded-blocks" - }, - - fixable: "whitespace", - - schema: [ - { - oneOf: [ - { - enum: ["always", "never"] - }, - { - type: "object", - properties: { - blocks: { - enum: ["always", "never"] - }, - switches: { - enum: ["always", "never"] - }, - classes: { - enum: ["always", "never"] - } - }, - additionalProperties: false, - minProperties: 1 - } - ] - }, - { - type: "object", - properties: { - allowSingleLineBlocks: { - type: "boolean" - } - } - } - ] - }, - - create(context) { - const options = {}; - const typeOptions = context.options[0] || "always"; - const exceptOptions = context.options[1] || {}; - - if (typeof typeOptions === "string") { - const shouldHavePadding = typeOptions === "always"; - - options.blocks = shouldHavePadding; - options.switches = shouldHavePadding; - options.classes = shouldHavePadding; - } else { - if (Object.prototype.hasOwnProperty.call(typeOptions, "blocks")) { - options.blocks = typeOptions.blocks === "always"; - } - if (Object.prototype.hasOwnProperty.call(typeOptions, "switches")) { - options.switches = typeOptions.switches === "always"; - } - if (Object.prototype.hasOwnProperty.call(typeOptions, "classes")) { - options.classes = typeOptions.classes === "always"; - } - } - - if (Object.prototype.hasOwnProperty.call(exceptOptions, "allowSingleLineBlocks")) { - options.allowSingleLineBlocks = exceptOptions.allowSingleLineBlocks === true; - } - - const ALWAYS_MESSAGE = "Block must be padded by blank lines.", - NEVER_MESSAGE = "Block must not be padded by blank lines."; - - const sourceCode = context.getSourceCode(); - - /** - * Gets the open brace token from a given node. - * @param {ASTNode} node - A BlockStatement or SwitchStatement node from which to get the open brace. - * @returns {Token} The token of the open brace. - */ - function getOpenBrace(node) { - if (node.type === "SwitchStatement") { - return sourceCode.getTokenBefore(node.cases[0]); - } - return sourceCode.getFirstToken(node); - } - - /** - * Checks if the given parameter is a comment node - * @param {ASTNode|Token} node An AST node or token - * @returns {boolean} True if node is a comment - */ - function isComment(node) { - return node.type === "Line" || node.type === "Block"; - } - - /** - * Checks if there is padding between two tokens - * @param {Token} first The first token - * @param {Token} second The second token - * @returns {boolean} True if there is at least a line between the tokens - */ - function isPaddingBetweenTokens(first, second) { - return second.loc.start.line - first.loc.end.line >= 2; - } - - - /** - * Checks if the given token has a blank line after it. - * @param {Token} token The token to check. - * @returns {boolean} Whether or not the token is followed by a blank line. - */ - function getFirstBlockToken(token) { - let prev, - first = token; - - do { - prev = first; - first = sourceCode.getTokenAfter(first, { includeComments: true }); - } while (isComment(first) && first.loc.start.line === prev.loc.end.line); - - return first; - } - - /** - * Checks if the given token is preceeded by a blank line. - * @param {Token} token The token to check - * @returns {boolean} Whether or not the token is preceeded by a blank line - */ - function getLastBlockToken(token) { - let last = token, - next; - - do { - next = last; - last = sourceCode.getTokenBefore(last, { includeComments: true }); - } while (isComment(last) && last.loc.end.line === next.loc.start.line); - - return last; - } - - /** - * Checks if a node should be padded, according to the rule config. - * @param {ASTNode} node The AST node to check. - * @returns {boolean} True if the node should be padded, false otherwise. - */ - function requirePaddingFor(node) { - switch (node.type) { - case "BlockStatement": - return options.blocks; - case "SwitchStatement": - return options.switches; - case "ClassBody": - return options.classes; - - /* istanbul ignore next */ - default: - throw new Error("unreachable"); - } - } - - /** - * Checks the given BlockStatement node to be padded if the block is not empty. - * @param {ASTNode} node The AST node of a BlockStatement. - * @returns {void} undefined. - */ - function checkPadding(node) { - const openBrace = getOpenBrace(node), - firstBlockToken = getFirstBlockToken(openBrace), - tokenBeforeFirst = sourceCode.getTokenBefore(firstBlockToken, { includeComments: true }), - closeBrace = sourceCode.getLastToken(node), - lastBlockToken = getLastBlockToken(closeBrace), - tokenAfterLast = sourceCode.getTokenAfter(lastBlockToken, { includeComments: true }), - blockHasTopPadding = isPaddingBetweenTokens(tokenBeforeFirst, firstBlockToken), - blockHasBottomPadding = isPaddingBetweenTokens(lastBlockToken, tokenAfterLast); - - if (options.allowSingleLineBlocks && astUtils.isTokenOnSameLine(tokenBeforeFirst, tokenAfterLast)) { - return; - } - - if (requirePaddingFor(node)) { - if (!blockHasTopPadding) { - context.report({ - node, - loc: { line: tokenBeforeFirst.loc.start.line, column: tokenBeforeFirst.loc.start.column }, - fix(fixer) { - return fixer.insertTextAfter(tokenBeforeFirst, "\n"); - }, - message: ALWAYS_MESSAGE - }); - } - if (!blockHasBottomPadding) { - context.report({ - node, - loc: { line: tokenAfterLast.loc.end.line, column: tokenAfterLast.loc.end.column - 1 }, - fix(fixer) { - return fixer.insertTextBefore(tokenAfterLast, "\n"); - }, - message: ALWAYS_MESSAGE - }); - } - } else { - if (blockHasTopPadding) { - - context.report({ - node, - loc: { line: tokenBeforeFirst.loc.start.line, column: tokenBeforeFirst.loc.start.column }, - fix(fixer) { - return fixer.replaceTextRange([tokenBeforeFirst.range[1], firstBlockToken.range[0] - firstBlockToken.loc.start.column], "\n"); - }, - message: NEVER_MESSAGE - }); - } - - if (blockHasBottomPadding) { - - context.report({ - node, - loc: { line: tokenAfterLast.loc.end.line, column: tokenAfterLast.loc.end.column - 1 }, - message: NEVER_MESSAGE, - fix(fixer) { - return fixer.replaceTextRange([lastBlockToken.range[1], tokenAfterLast.range[0] - tokenAfterLast.loc.start.column], "\n"); - } - }); - } - } - } - - const rule = {}; - - if (Object.prototype.hasOwnProperty.call(options, "switches")) { - rule.SwitchStatement = function(node) { - if (node.cases.length === 0) { - return; - } - checkPadding(node); - }; - } - - if (Object.prototype.hasOwnProperty.call(options, "blocks")) { - rule.BlockStatement = function(node) { - if (node.body.length === 0) { - return; - } - checkPadding(node); - }; - } - - if (Object.prototype.hasOwnProperty.call(options, "classes")) { - rule.ClassBody = function(node) { - if (node.body.length === 0) { - return; - } - checkPadding(node); - }; - } - - return rule; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/padding-line-between-statements.js b/tools/node_modules/eslint/lib/rules/padding-line-between-statements.js deleted file mode 100644 index c9995885442f2f..00000000000000 --- a/tools/node_modules/eslint/lib/rules/padding-line-between-statements.js +++ /dev/null @@ -1,642 +0,0 @@ -/** - * @fileoverview Rule to require or disallow newlines between statements - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const LT = `[${Array.from(astUtils.LINEBREAKS).join("")}]`; -const PADDING_LINE_SEQUENCE = new RegExp( - String.raw`^(\s*?${LT})\s*${LT}(\s*;?)$` -); -const CJS_EXPORT = /^(?:module\s*\.\s*)?exports(?:\s*\.|\s*\[|$)/; -const CJS_IMPORT = /^require\(/; - -/** - * Creates tester which check if a node starts with specific keyword. - * - * @param {string} keyword The keyword to test. - * @returns {Object} the created tester. - * @private - */ -function newKeywordTester(keyword) { - return { - test: (node, sourceCode) => - sourceCode.getFirstToken(node).value === keyword - }; -} - -/** - * Creates tester which check if a node starts with specific keyword and spans a single line. - * - * @param {string} keyword The keyword to test. - * @returns {Object} the created tester. - * @private - */ -function newSinglelineKeywordTester(keyword) { - return { - test: (node, sourceCode) => - node.loc.start.line === node.loc.end.line && - sourceCode.getFirstToken(node).value === keyword - }; -} - -/** - * Creates tester which check if a node starts with specific keyword and spans multiple lines. - * - * @param {string} keyword The keyword to test. - * @returns {Object} the created tester. - * @private - */ -function newMultilineKeywordTester(keyword) { - return { - test: (node, sourceCode) => - node.loc.start.line !== node.loc.end.line && - sourceCode.getFirstToken(node).value === keyword - }; -} - -/** - * Creates tester which check if a node is specific type. - * - * @param {string} type The node type to test. - * @returns {Object} the created tester. - * @private - */ -function newNodeTypeTester(type) { - return { - test: node => - node.type === type - }; -} - -/** - * Checks the given node is an expression statement of IIFE. - * - * @param {ASTNode} node The node to check. - * @returns {boolean} `true` if the node is an expression statement of IIFE. - * @private - */ -function isIIFEStatement(node) { - if (node.type === "ExpressionStatement") { - let call = node.expression; - - if (call.type === "UnaryExpression") { - call = call.argument; - } - return call.type === "CallExpression" && astUtils.isFunction(call.callee); - } - return false; -} - -/** - * Checks whether the given node is a block-like statement. - * This checks the last token of the node is the closing brace of a block. - * - * @param {SourceCode} sourceCode The source code to get tokens. - * @param {ASTNode} node The node to check. - * @returns {boolean} `true` if the node is a block-like statement. - * @private - */ -function isBlockLikeStatement(sourceCode, node) { - - // do-while with a block is a block-like statement. - if (node.type === "DoWhileStatement" && node.body.type === "BlockStatement") { - return true; - } - - /* - * IIFE is a block-like statement specially from - * JSCS#disallowPaddingNewLinesAfterBlocks. - */ - if (isIIFEStatement(node)) { - return true; - } - - // Checks the last token is a closing brace of blocks. - const lastToken = sourceCode.getLastToken(node, astUtils.isNotSemicolonToken); - const belongingNode = lastToken && astUtils.isClosingBraceToken(lastToken) - ? sourceCode.getNodeByRangeIndex(lastToken.range[0]) - : null; - - return Boolean(belongingNode) && ( - belongingNode.type === "BlockStatement" || - belongingNode.type === "SwitchStatement" - ); -} - -/** - * Check whether the given node is a directive or not. - * @param {ASTNode} node The node to check. - * @param {SourceCode} sourceCode The source code object to get tokens. - * @returns {boolean} `true` if the node is a directive. - */ -function isDirective(node, sourceCode) { - return ( - node.type === "ExpressionStatement" && - ( - node.parent.type === "Program" || - ( - node.parent.type === "BlockStatement" && - astUtils.isFunction(node.parent.parent) - ) - ) && - node.expression.type === "Literal" && - typeof node.expression.value === "string" && - !astUtils.isParenthesised(sourceCode, node.expression) - ); -} - -/** - * Check whether the given node is a part of directive prologue or not. - * @param {ASTNode} node The node to check. - * @param {SourceCode} sourceCode The source code object to get tokens. - * @returns {boolean} `true` if the node is a part of directive prologue. - */ -function isDirectivePrologue(node, sourceCode) { - if (isDirective(node, sourceCode)) { - for (const sibling of node.parent.body) { - if (sibling === node) { - break; - } - if (!isDirective(sibling, sourceCode)) { - return false; - } - } - return true; - } - return false; -} - -/** - * Gets the actual last token. - * - * If a semicolon is semicolon-less style's semicolon, this ignores it. - * For example: - * - * foo() - * ;[1, 2, 3].forEach(bar) - * - * @param {SourceCode} sourceCode The source code to get tokens. - * @param {ASTNode} node The node to get. - * @returns {Token} The actual last token. - * @private - */ -function getActualLastToken(sourceCode, node) { - const semiToken = sourceCode.getLastToken(node); - const prevToken = sourceCode.getTokenBefore(semiToken); - const nextToken = sourceCode.getTokenAfter(semiToken); - const isSemicolonLessStyle = Boolean( - prevToken && - nextToken && - prevToken.range[0] >= node.range[0] && - astUtils.isSemicolonToken(semiToken) && - semiToken.loc.start.line !== prevToken.loc.end.line && - semiToken.loc.end.line === nextToken.loc.start.line - ); - - return isSemicolonLessStyle ? prevToken : semiToken; -} - -/** - * This returns the concatenation of the first 2 captured strings. - * @param {string} _ Unused. Whole matched string. - * @param {string} trailingSpaces The trailing spaces of the first line. - * @param {string} indentSpaces The indentation spaces of the last line. - * @returns {string} The concatenation of trailingSpaces and indentSpaces. - * @private - */ -function replacerToRemovePaddingLines(_, trailingSpaces, indentSpaces) { - return trailingSpaces + indentSpaces; -} - -/** - * Check and report statements for `any` configuration. - * It does nothing. - * - * @returns {void} - * @private - */ -function verifyForAny() { -} - -/** - * Check and report statements for `never` configuration. - * This autofix removes blank lines between the given 2 statements. - * However, if comments exist between 2 blank lines, it does not remove those - * blank lines automatically. - * - * @param {RuleContext} context The rule context to report. - * @param {ASTNode} _ Unused. The previous node to check. - * @param {ASTNode} nextNode The next node to check. - * @param {Array} paddingLines The array of token pairs that blank - * lines exist between the pair. - * @returns {void} - * @private - */ -function verifyForNever(context, _, nextNode, paddingLines) { - if (paddingLines.length === 0) { - return; - } - - context.report({ - node: nextNode, - message: "Unexpected blank line before this statement.", - fix(fixer) { - if (paddingLines.length >= 2) { - return null; - } - - const prevToken = paddingLines[0][0]; - const nextToken = paddingLines[0][1]; - const start = prevToken.range[1]; - const end = nextToken.range[0]; - const text = context.getSourceCode().text - .slice(start, end) - .replace(PADDING_LINE_SEQUENCE, replacerToRemovePaddingLines); - - return fixer.replaceTextRange([start, end], text); - } - }); -} - -/** - * Check and report statements for `always` configuration. - * This autofix inserts a blank line between the given 2 statements. - * If the `prevNode` has trailing comments, it inserts a blank line after the - * trailing comments. - * - * @param {RuleContext} context The rule context to report. - * @param {ASTNode} prevNode The previous node to check. - * @param {ASTNode} nextNode The next node to check. - * @param {Array} paddingLines The array of token pairs that blank - * lines exist between the pair. - * @returns {void} - * @private - */ -function verifyForAlways(context, prevNode, nextNode, paddingLines) { - if (paddingLines.length > 0) { - return; - } - - context.report({ - node: nextNode, - message: "Expected blank line before this statement.", - fix(fixer) { - const sourceCode = context.getSourceCode(); - let prevToken = getActualLastToken(sourceCode, prevNode); - const nextToken = sourceCode.getFirstTokenBetween( - prevToken, - nextNode, - { - includeComments: true, - - /** - * Skip the trailing comments of the previous node. - * This inserts a blank line after the last trailing comment. - * - * For example: - * - * foo(); // trailing comment. - * // comment. - * bar(); - * - * Get fixed to: - * - * foo(); // trailing comment. - * - * // comment. - * bar(); - * - * @param {Token} token The token to check. - * @returns {boolean} `true` if the token is not a trailing comment. - * @private - */ - filter(token) { - if (astUtils.isTokenOnSameLine(prevToken, token)) { - prevToken = token; - return false; - } - return true; - } - } - ) || nextNode; - const insertText = astUtils.isTokenOnSameLine(prevToken, nextToken) - ? "\n\n" - : "\n"; - - return fixer.insertTextAfter(prevToken, insertText); - } - }); -} - -/** - * Types of blank lines. - * `any`, `never`, and `always` are defined. - * Those have `verify` method to check and report statements. - * @private - */ -const PaddingTypes = { - any: { verify: verifyForAny }, - never: { verify: verifyForNever }, - always: { verify: verifyForAlways } -}; - -/** - * Types of statements. - * Those have `test` method to check it matches to the given statement. - * @private - */ -const StatementTypes = { - "*": { test: () => true }, - "block-like": { - test: (node, sourceCode) => isBlockLikeStatement(sourceCode, node) - }, - "cjs-export": { - test: (node, sourceCode) => - node.type === "ExpressionStatement" && - node.expression.type === "AssignmentExpression" && - CJS_EXPORT.test(sourceCode.getText(node.expression.left)) - }, - "cjs-import": { - test: (node, sourceCode) => - node.type === "VariableDeclaration" && - node.declarations.length > 0 && - Boolean(node.declarations[0].init) && - CJS_IMPORT.test(sourceCode.getText(node.declarations[0].init)) - }, - directive: { - test: isDirectivePrologue - }, - expression: { - test: (node, sourceCode) => - node.type === "ExpressionStatement" && - !isDirectivePrologue(node, sourceCode) - }, - iife: { - test: isIIFEStatement - }, - "multiline-block-like": { - test: (node, sourceCode) => - node.loc.start.line !== node.loc.end.line && - isBlockLikeStatement(sourceCode, node) - }, - "multiline-expression": { - test: (node, sourceCode) => - node.loc.start.line !== node.loc.end.line && - node.type === "ExpressionStatement" && - !isDirectivePrologue(node, sourceCode) - }, - - "multiline-const": newMultilineKeywordTester("const"), - "multiline-let": newMultilineKeywordTester("let"), - "multiline-var": newMultilineKeywordTester("var"), - "singleline-const": newSinglelineKeywordTester("const"), - "singleline-let": newSinglelineKeywordTester("let"), - "singleline-var": newSinglelineKeywordTester("var"), - - block: newNodeTypeTester("BlockStatement"), - empty: newNodeTypeTester("EmptyStatement"), - function: newNodeTypeTester("FunctionDeclaration"), - - break: newKeywordTester("break"), - case: newKeywordTester("case"), - class: newKeywordTester("class"), - const: newKeywordTester("const"), - continue: newKeywordTester("continue"), - debugger: newKeywordTester("debugger"), - default: newKeywordTester("default"), - do: newKeywordTester("do"), - export: newKeywordTester("export"), - for: newKeywordTester("for"), - if: newKeywordTester("if"), - import: newKeywordTester("import"), - let: newKeywordTester("let"), - return: newKeywordTester("return"), - switch: newKeywordTester("switch"), - throw: newKeywordTester("throw"), - try: newKeywordTester("try"), - var: newKeywordTester("var"), - while: newKeywordTester("while"), - with: newKeywordTester("with") -}; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "require or disallow padding lines between statements", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/padding-line-between-statements" - }, - - fixable: "whitespace", - - schema: { - definitions: { - paddingType: { - enum: Object.keys(PaddingTypes) - }, - statementType: { - anyOf: [ - { enum: Object.keys(StatementTypes) }, - { - type: "array", - items: { enum: Object.keys(StatementTypes) }, - minItems: 1, - uniqueItems: true, - additionalItems: false - } - ] - } - }, - type: "array", - items: { - type: "object", - properties: { - blankLine: { $ref: "#/definitions/paddingType" }, - prev: { $ref: "#/definitions/statementType" }, - next: { $ref: "#/definitions/statementType" } - }, - additionalProperties: false, - required: ["blankLine", "prev", "next"] - }, - additionalItems: false - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - const configureList = context.options || []; - let scopeInfo = null; - - /** - * Processes to enter to new scope. - * This manages the current previous statement. - * @returns {void} - * @private - */ - function enterScope() { - scopeInfo = { - upper: scopeInfo, - prevNode: null - }; - } - - /** - * Processes to exit from the current scope. - * @returns {void} - * @private - */ - function exitScope() { - scopeInfo = scopeInfo.upper; - } - - /** - * Checks whether the given node matches the given type. - * - * @param {ASTNode} node The statement node to check. - * @param {string|string[]} type The statement type to check. - * @returns {boolean} `true` if the statement node matched the type. - * @private - */ - function match(node, type) { - let innerStatementNode = node; - - while (innerStatementNode.type === "LabeledStatement") { - innerStatementNode = innerStatementNode.body; - } - if (Array.isArray(type)) { - return type.some(match.bind(null, innerStatementNode)); - } - return StatementTypes[type].test(innerStatementNode, sourceCode); - } - - /** - * Finds the last matched configure from configureList. - * - * @param {ASTNode} prevNode The previous statement to match. - * @param {ASTNode} nextNode The current statement to match. - * @returns {Object} The tester of the last matched configure. - * @private - */ - function getPaddingType(prevNode, nextNode) { - for (let i = configureList.length - 1; i >= 0; --i) { - const configure = configureList[i]; - const matched = - match(prevNode, configure.prev) && - match(nextNode, configure.next); - - if (matched) { - return PaddingTypes[configure.blankLine]; - } - } - return PaddingTypes.any; - } - - /** - * Gets padding line sequences between the given 2 statements. - * Comments are separators of the padding line sequences. - * - * @param {ASTNode} prevNode The previous statement to count. - * @param {ASTNode} nextNode The current statement to count. - * @returns {Array} The array of token pairs. - * @private - */ - function getPaddingLineSequences(prevNode, nextNode) { - const pairs = []; - let prevToken = getActualLastToken(sourceCode, prevNode); - - if (nextNode.loc.start.line - prevToken.loc.end.line >= 2) { - do { - const token = sourceCode.getTokenAfter( - prevToken, - { includeComments: true } - ); - - if (token.loc.start.line - prevToken.loc.end.line >= 2) { - pairs.push([prevToken, token]); - } - prevToken = token; - - } while (prevToken.range[0] < nextNode.range[0]); - } - - return pairs; - } - - /** - * Verify padding lines between the given node and the previous node. - * - * @param {ASTNode} node The node to verify. - * @returns {void} - * @private - */ - function verify(node) { - const parentType = node.parent.type; - const validParent = - astUtils.STATEMENT_LIST_PARENTS.has(parentType) || - parentType === "SwitchStatement"; - - if (!validParent) { - return; - } - - // Save this node as the current previous statement. - const prevNode = scopeInfo.prevNode; - - // Verify. - if (prevNode) { - const type = getPaddingType(prevNode, node); - const paddingLines = getPaddingLineSequences(prevNode, node); - - type.verify(context, prevNode, node, paddingLines); - } - - scopeInfo.prevNode = node; - } - - /** - * Verify padding lines between the given node and the previous node. - * Then process to enter to new scope. - * - * @param {ASTNode} node The node to verify. - * @returns {void} - * @private - */ - function verifyThenEnterScope(node) { - verify(node); - enterScope(); - } - - return { - Program: enterScope, - BlockStatement: enterScope, - SwitchStatement: enterScope, - "Program:exit": exitScope, - "BlockStatement:exit": exitScope, - "SwitchStatement:exit": exitScope, - - ":statement": verify, - - SwitchCase: verifyThenEnterScope, - "SwitchCase:exit": exitScope - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/prefer-arrow-callback.js b/tools/node_modules/eslint/lib/rules/prefer-arrow-callback.js deleted file mode 100644 index a0957399ea5ad1..00000000000000 --- a/tools/node_modules/eslint/lib/rules/prefer-arrow-callback.js +++ /dev/null @@ -1,310 +0,0 @@ -/** - * @fileoverview A rule to suggest using arrow functions as callbacks. - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks whether or not a given variable is a function name. - * @param {eslint-scope.Variable} variable - A variable to check. - * @returns {boolean} `true` if the variable is a function name. - */ -function isFunctionName(variable) { - return variable && variable.defs[0].type === "FunctionName"; -} - -/** - * Checks whether or not a given MetaProperty node equals to a given value. - * @param {ASTNode} node - A MetaProperty node to check. - * @param {string} metaName - The name of `MetaProperty.meta`. - * @param {string} propertyName - The name of `MetaProperty.property`. - * @returns {boolean} `true` if the node is the specific value. - */ -function checkMetaProperty(node, metaName, propertyName) { - return node.meta.name === metaName && node.property.name === propertyName; -} - -/** - * Gets the variable object of `arguments` which is defined implicitly. - * @param {eslint-scope.Scope} scope - A scope to get. - * @returns {eslint-scope.Variable} The found variable object. - */ -function getVariableOfArguments(scope) { - const variables = scope.variables; - - for (let i = 0; i < variables.length; ++i) { - const variable = variables[i]; - - if (variable.name === "arguments") { - - /* - * If there was a parameter which is named "arguments", the - * implicit "arguments" is not defined. - * So does fast return with null. - */ - return (variable.identifiers.length === 0) ? variable : null; - } - } - - /* istanbul ignore next */ - return null; -} - -/** - * Checkes whether or not a given node is a callback. - * @param {ASTNode} node - A node to check. - * @returns {Object} - * {boolean} retv.isCallback - `true` if the node is a callback. - * {boolean} retv.isLexicalThis - `true` if the node is with `.bind(this)`. - */ -function getCallbackInfo(node) { - const retv = { isCallback: false, isLexicalThis: false }; - let currentNode = node; - let parent = node.parent; - - while (currentNode) { - switch (parent.type) { - - // Checks parents recursively. - - case "LogicalExpression": - case "ConditionalExpression": - break; - - // Checks whether the parent node is `.bind(this)` call. - case "MemberExpression": - if (parent.object === currentNode && - !parent.property.computed && - parent.property.type === "Identifier" && - parent.property.name === "bind" && - parent.parent.type === "CallExpression" && - parent.parent.callee === parent - ) { - retv.isLexicalThis = ( - parent.parent.arguments.length === 1 && - parent.parent.arguments[0].type === "ThisExpression" - ); - parent = parent.parent; - } else { - return retv; - } - break; - - // Checks whether the node is a callback. - case "CallExpression": - case "NewExpression": - if (parent.callee !== currentNode) { - retv.isCallback = true; - } - return retv; - - default: - return retv; - } - - currentNode = parent; - parent = parent.parent; - } - - /* istanbul ignore next */ - throw new Error("unreachable"); -} - -/** - * Checks whether a simple list of parameters contains any duplicates. This does not handle complex - * parameter lists (e.g. with destructuring), since complex parameter lists are a SyntaxError with duplicate - * parameter names anyway. Instead, it always returns `false` for complex parameter lists. - * @param {ASTNode[]} paramsList The list of parameters for a function - * @returns {boolean} `true` if the list of parameters contains any duplicates - */ -function hasDuplicateParams(paramsList) { - return paramsList.every(param => param.type === "Identifier") && paramsList.length !== new Set(paramsList.map(param => param.name)).size; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require using arrow functions for callbacks", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/prefer-arrow-callback" - }, - - schema: [ - { - type: "object", - properties: { - allowNamedFunctions: { - type: "boolean", - default: false - }, - allowUnboundThis: { - type: "boolean", - default: true - } - }, - additionalProperties: false - } - ], - - fixable: "code" - }, - - create(context) { - const options = context.options[0] || {}; - - const allowUnboundThis = options.allowUnboundThis !== false; // default to true - const allowNamedFunctions = options.allowNamedFunctions; - const sourceCode = context.getSourceCode(); - - /* - * {Array<{this: boolean, super: boolean, meta: boolean}>} - * - this - A flag which shows there are one or more ThisExpression. - * - super - A flag which shows there are one or more Super. - * - meta - A flag which shows there are one or more MethProperty. - */ - let stack = []; - - /** - * Pushes new function scope with all `false` flags. - * @returns {void} - */ - function enterScope() { - stack.push({ this: false, super: false, meta: false }); - } - - /** - * Pops a function scope from the stack. - * @returns {{this: boolean, super: boolean, meta: boolean}} The information of the last scope. - */ - function exitScope() { - return stack.pop(); - } - - return { - - // Reset internal state. - Program() { - stack = []; - }, - - // If there are below, it cannot replace with arrow functions merely. - ThisExpression() { - const info = stack[stack.length - 1]; - - if (info) { - info.this = true; - } - }, - - Super() { - const info = stack[stack.length - 1]; - - if (info) { - info.super = true; - } - }, - - MetaProperty(node) { - const info = stack[stack.length - 1]; - - if (info && checkMetaProperty(node, "new", "target")) { - info.meta = true; - } - }, - - // To skip nested scopes. - FunctionDeclaration: enterScope, - "FunctionDeclaration:exit": exitScope, - - // Main. - FunctionExpression: enterScope, - "FunctionExpression:exit"(node) { - const scopeInfo = exitScope(); - - // Skip named function expressions - if (allowNamedFunctions && node.id && node.id.name) { - return; - } - - // Skip generators. - if (node.generator) { - return; - } - - // Skip recursive functions. - const nameVar = context.getDeclaredVariables(node)[0]; - - if (isFunctionName(nameVar) && nameVar.references.length > 0) { - return; - } - - // Skip if it's using arguments. - const variable = getVariableOfArguments(context.getScope()); - - if (variable && variable.references.length > 0) { - return; - } - - // Reports if it's a callback which can replace with arrows. - const callbackInfo = getCallbackInfo(node); - - if (callbackInfo.isCallback && - (!allowUnboundThis || !scopeInfo.this || callbackInfo.isLexicalThis) && - !scopeInfo.super && - !scopeInfo.meta - ) { - context.report({ - node, - message: "Unexpected function expression.", - fix(fixer) { - if ((!callbackInfo.isLexicalThis && scopeInfo.this) || hasDuplicateParams(node.params)) { - - /* - * If the callback function does not have .bind(this) and contains a reference to `this`, there - * is no way to determine what `this` should be, so don't perform any fixes. - * If the callback function has duplicates in its list of parameters (possible in sloppy mode), - * don't replace it with an arrow function, because this is a SyntaxError with arrow functions. - */ - return null; - } - - const paramsLeftParen = node.params.length ? sourceCode.getTokenBefore(node.params[0]) : sourceCode.getTokenBefore(node.body, 1); - const paramsRightParen = sourceCode.getTokenBefore(node.body); - const asyncKeyword = node.async ? "async " : ""; - const paramsFullText = sourceCode.text.slice(paramsLeftParen.range[0], paramsRightParen.range[1]); - const arrowFunctionText = `${asyncKeyword}${paramsFullText} => ${sourceCode.getText(node.body)}`; - - /* - * If the callback function has `.bind(this)`, replace it with an arrow function and remove the binding. - * Otherwise, just replace the arrow function itself. - */ - const replacedNode = callbackInfo.isLexicalThis ? node.parent.parent : node; - - /* - * If the replaced node is part of a BinaryExpression, LogicalExpression, or MemberExpression, then - * the arrow function needs to be parenthesized, because `foo || () => {}` is invalid syntax even - * though `foo || function() {}` is valid. - */ - const needsParens = replacedNode.parent.type !== "CallExpression" && replacedNode.parent.type !== "ConditionalExpression"; - const replacementText = needsParens ? `(${arrowFunctionText})` : arrowFunctionText; - - return fixer.replaceText(replacedNode, replacementText); - } - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/prefer-const.js b/tools/node_modules/eslint/lib/rules/prefer-const.js deleted file mode 100644 index 023f69cbd32a30..00000000000000 --- a/tools/node_modules/eslint/lib/rules/prefer-const.js +++ /dev/null @@ -1,471 +0,0 @@ -/** - * @fileoverview A rule to suggest using of const declaration for variables that are never reassigned after declared. - * @author Toru Nagashima - */ - -"use strict"; - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const PATTERN_TYPE = /^(?:.+?Pattern|RestElement|SpreadProperty|ExperimentalRestProperty|Property)$/; -const DECLARATION_HOST_TYPE = /^(?:Program|BlockStatement|SwitchCase)$/; -const DESTRUCTURING_HOST_TYPE = /^(?:VariableDeclarator|AssignmentExpression)$/; - -/** - * Checks whether a given node is located at `ForStatement.init` or not. - * - * @param {ASTNode} node - A node to check. - * @returns {boolean} `true` if the node is located at `ForStatement.init`. - */ -function isInitOfForStatement(node) { - return node.parent.type === "ForStatement" && node.parent.init === node; -} - -/** - * Checks whether a given Identifier node becomes a VariableDeclaration or not. - * - * @param {ASTNode} identifier - An Identifier node to check. - * @returns {boolean} `true` if the node can become a VariableDeclaration. - */ -function canBecomeVariableDeclaration(identifier) { - let node = identifier.parent; - - while (PATTERN_TYPE.test(node.type)) { - node = node.parent; - } - - return ( - node.type === "VariableDeclarator" || - ( - node.type === "AssignmentExpression" && - node.parent.type === "ExpressionStatement" && - DECLARATION_HOST_TYPE.test(node.parent.parent.type) - ) - ); -} - -/** - * Checks if an property or element is from outer scope or function parameters - * in destructing pattern. - * - * @param {string} name - A variable name to be checked. - * @param {eslint-scope.Scope} initScope - A scope to start find. - * @returns {boolean} Indicates if the variable is from outer scope or function parameters. - */ -function isOuterVariableInDestructing(name, initScope) { - - if (initScope.through.find(ref => ref.resolved && ref.resolved.name === name)) { - return true; - } - - const variable = astUtils.getVariableByName(initScope, name); - - if (variable !== null) { - return variable.defs.some(def => def.type === "Parameter"); - } - - return false; -} - -/** - * Gets the VariableDeclarator/AssignmentExpression node that a given reference - * belongs to. - * This is used to detect a mix of reassigned and never reassigned in a - * destructuring. - * - * @param {eslint-scope.Reference} reference - A reference to get. - * @returns {ASTNode|null} A VariableDeclarator/AssignmentExpression node or - * null. - */ -function getDestructuringHost(reference) { - if (!reference.isWrite()) { - return null; - } - let node = reference.identifier.parent; - - while (PATTERN_TYPE.test(node.type)) { - node = node.parent; - } - - if (!DESTRUCTURING_HOST_TYPE.test(node.type)) { - return null; - } - return node; -} - -/** - * Determines if a destructuring assignment node contains - * any MemberExpression nodes. This is used to determine if a - * variable that is only written once using destructuring can be - * safely converted into a const declaration. - * @param {ASTNode} node The ObjectPattern or ArrayPattern node to check. - * @returns {boolean} True if the destructuring pattern contains - * a MemberExpression, false if not. - */ -function hasMemberExpressionAssignment(node) { - switch (node.type) { - case "ObjectPattern": - return node.properties.some(prop => { - if (prop) { - - /* - * Spread elements have an argument property while - * others have a value property. Because different - * parsers use different node types for spread elements, - * we just check if there is an argument property. - */ - return hasMemberExpressionAssignment(prop.argument || prop.value); - } - - return false; - }); - - case "ArrayPattern": - return node.elements.some(element => { - if (element) { - return hasMemberExpressionAssignment(element); - } - - return false; - }); - - case "AssignmentPattern": - return hasMemberExpressionAssignment(node.left); - - case "MemberExpression": - return true; - - // no default - } - - return false; -} - -/** - * Gets an identifier node of a given variable. - * - * If the initialization exists or one or more reading references exist before - * the first assignment, the identifier node is the node of the declaration. - * Otherwise, the identifier node is the node of the first assignment. - * - * If the variable should not change to const, this function returns null. - * - If the variable is reassigned. - * - If the variable is never initialized nor assigned. - * - If the variable is initialized in a different scope from the declaration. - * - If the unique assignment of the variable cannot change to a declaration. - * e.g. `if (a) b = 1` / `return (b = 1)` - * - If the variable is declared in the global scope and `eslintUsed` is `true`. - * `/*exported foo` directive comment makes such variables. This rule does not - * warn such variables because this rule cannot distinguish whether the - * exported variables are reassigned or not. - * - * @param {eslint-scope.Variable} variable - A variable to get. - * @param {boolean} ignoreReadBeforeAssign - - * The value of `ignoreReadBeforeAssign` option. - * @returns {ASTNode|null} - * An Identifier node if the variable should change to const. - * Otherwise, null. - */ -function getIdentifierIfShouldBeConst(variable, ignoreReadBeforeAssign) { - if (variable.eslintUsed && variable.scope.type === "global") { - return null; - } - - // Finds the unique WriteReference. - let writer = null; - let isReadBeforeInit = false; - const references = variable.references; - - for (let i = 0; i < references.length; ++i) { - const reference = references[i]; - - if (reference.isWrite()) { - const isReassigned = ( - writer !== null && - writer.identifier !== reference.identifier - ); - - if (isReassigned) { - return null; - } - - const destructuringHost = getDestructuringHost(reference); - - if (destructuringHost !== null && destructuringHost.left !== void 0) { - const leftNode = destructuringHost.left; - let hasOuterVariables = false, - hasNonIdentifiers = false; - - if (leftNode.type === "ObjectPattern") { - const properties = leftNode.properties; - - hasOuterVariables = properties - .filter(prop => prop.value) - .map(prop => prop.value.name) - .some(name => isOuterVariableInDestructing(name, variable.scope)); - - hasNonIdentifiers = hasMemberExpressionAssignment(leftNode); - - } else if (leftNode.type === "ArrayPattern") { - const elements = leftNode.elements; - - hasOuterVariables = elements - .map(element => element && element.name) - .some(name => isOuterVariableInDestructing(name, variable.scope)); - - hasNonIdentifiers = hasMemberExpressionAssignment(leftNode); - } - - if (hasOuterVariables || hasNonIdentifiers) { - return null; - } - - } - - writer = reference; - - } else if (reference.isRead() && writer === null) { - if (ignoreReadBeforeAssign) { - return null; - } - isReadBeforeInit = true; - } - } - - /* - * If the assignment is from a different scope, ignore it. - * If the assignment cannot change to a declaration, ignore it. - */ - const shouldBeConst = ( - writer !== null && - writer.from === variable.scope && - canBecomeVariableDeclaration(writer.identifier) - ); - - if (!shouldBeConst) { - return null; - } - - if (isReadBeforeInit) { - return variable.defs[0].name; - } - - return writer.identifier; -} - -/** - * Groups by the VariableDeclarator/AssignmentExpression node that each - * reference of given variables belongs to. - * This is used to detect a mix of reassigned and never reassigned in a - * destructuring. - * - * @param {eslint-scope.Variable[]} variables - Variables to group by destructuring. - * @param {boolean} ignoreReadBeforeAssign - - * The value of `ignoreReadBeforeAssign` option. - * @returns {Map} Grouped identifier nodes. - */ -function groupByDestructuring(variables, ignoreReadBeforeAssign) { - const identifierMap = new Map(); - - for (let i = 0; i < variables.length; ++i) { - const variable = variables[i]; - const references = variable.references; - const identifier = getIdentifierIfShouldBeConst(variable, ignoreReadBeforeAssign); - let prevId = null; - - for (let j = 0; j < references.length; ++j) { - const reference = references[j]; - const id = reference.identifier; - - /* - * Avoid counting a reference twice or more for default values of - * destructuring. - */ - if (id === prevId) { - continue; - } - prevId = id; - - // Add the identifier node into the destructuring group. - const group = getDestructuringHost(reference); - - if (group) { - if (identifierMap.has(group)) { - identifierMap.get(group).push(identifier); - } else { - identifierMap.set(group, [identifier]); - } - } - } - } - - return identifierMap; -} - -/** - * Finds the nearest parent of node with a given type. - * - * @param {ASTNode} node – The node to search from. - * @param {string} type – The type field of the parent node. - * @param {Function} shouldStop – a predicate that returns true if the traversal should stop, and false otherwise. - * @returns {ASTNode} The closest ancestor with the specified type; null if no such ancestor exists. - */ -function findUp(node, type, shouldStop) { - if (!node || shouldStop(node)) { - return null; - } - if (node.type === type) { - return node; - } - return findUp(node.parent, type, shouldStop); -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require `const` declarations for variables that are never reassigned after declared", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/prefer-const" - }, - - fixable: "code", - - schema: [ - { - type: "object", - properties: { - destructuring: { enum: ["any", "all"], default: "any" }, - ignoreReadBeforeAssign: { type: "boolean", default: false } - }, - additionalProperties: false - } - ], - messages: { - useConst: "'{{name}}' is never reassigned. Use 'const' instead." - } - }, - - create(context) { - const options = context.options[0] || {}; - const sourceCode = context.getSourceCode(); - const shouldMatchAnyDestructuredVariable = options.destructuring !== "all"; - const ignoreReadBeforeAssign = options.ignoreReadBeforeAssign === true; - const variables = []; - let reportCount = 0; - let name = ""; - - /** - * Reports given identifier nodes if all of the nodes should be declared - * as const. - * - * The argument 'nodes' is an array of Identifier nodes. - * This node is the result of 'getIdentifierIfShouldBeConst()', so it's - * nullable. In simple declaration or assignment cases, the length of - * the array is 1. In destructuring cases, the length of the array can - * be 2 or more. - * - * @param {(eslint-scope.Reference|null)[]} nodes - - * References which are grouped by destructuring to report. - * @returns {void} - */ - function checkGroup(nodes) { - const nodesToReport = nodes.filter(Boolean); - - if (nodes.length && (shouldMatchAnyDestructuredVariable || nodesToReport.length === nodes.length)) { - const varDeclParent = findUp(nodes[0], "VariableDeclaration", parentNode => parentNode.type.endsWith("Statement")); - const isVarDecParentNull = varDeclParent === null; - - if (!isVarDecParentNull && varDeclParent.declarations.length > 0) { - const firstDeclaration = varDeclParent.declarations[0]; - - if (firstDeclaration.init) { - const firstDecParent = firstDeclaration.init.parent; - - /* - * First we check the declaration type and then depending on - * if the type is a "VariableDeclarator" or its an "ObjectPattern" - * we compare the name from the first identifier, if the names are different - * we assign the new name and reset the count of reportCount and nodeCount in - * order to check each block for the number of reported errors and base our fix - * based on comparing nodes.length and nodesToReport.length. - */ - - if (firstDecParent.type === "VariableDeclarator") { - - if (firstDecParent.id.name !== name) { - name = firstDecParent.id.name; - reportCount = 0; - } - - if (firstDecParent.id.type === "ObjectPattern") { - if (firstDecParent.init.name !== name) { - name = firstDecParent.init.name; - reportCount = 0; - } - } - } - } - } - - let shouldFix = varDeclParent && - - // 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.destructuring 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; - - if (!isVarDecParentNull && varDeclParent.declarations && varDeclParent.declarations.length !== 1) { - - if (varDeclParent && varDeclParent.declarations && varDeclParent.declarations.length >= 1) { - - /* - * Add nodesToReport.length to a count, then comparing the count to the length - * of the declarations in the current block. - */ - - reportCount += nodesToReport.length; - - shouldFix = shouldFix && (reportCount === varDeclParent.declarations.length); - } - } - - nodesToReport.forEach(node => { - context.report({ - node, - messageId: "useConst", - data: node, - fix: shouldFix ? fixer => fixer.replaceText(sourceCode.getFirstToken(varDeclParent), "const") : null - }); - }); - } - } - - return { - "Program:exit"() { - groupByDestructuring(variables, ignoreReadBeforeAssign).forEach(checkGroup); - }, - - VariableDeclaration(node) { - if (node.kind === "let" && !isInitOfForStatement(node)) { - variables.push(...context.getDeclaredVariables(node)); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/prefer-destructuring.js b/tools/node_modules/eslint/lib/rules/prefer-destructuring.js deleted file mode 100644 index c30c9170cd9cd2..00000000000000 --- a/tools/node_modules/eslint/lib/rules/prefer-destructuring.js +++ /dev/null @@ -1,281 +0,0 @@ -/** - * @fileoverview Prefer destructuring from arrays and objects - * @author Alex LaFroscia - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require destructuring from arrays and/or objects", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/prefer-destructuring" - }, - - fixable: "code", - - schema: [ - { - - /* - * old support {array: Boolean, object: Boolean} - * new support {VariableDeclarator: {}, AssignmentExpression: {}} - */ - oneOf: [ - { - type: "object", - properties: { - VariableDeclarator: { - type: "object", - properties: { - array: { - type: "boolean", - default: true - }, - object: { - type: "boolean", - default: true - } - }, - additionalProperties: false - }, - AssignmentExpression: { - type: "object", - properties: { - array: { - type: "boolean", - default: true - }, - object: { - type: "boolean", - default: true - } - }, - additionalProperties: false - } - }, - additionalProperties: false - }, - { - type: "object", - properties: { - array: { - type: "boolean", - default: true - }, - object: { - type: "boolean", - default: true - } - }, - additionalProperties: false - } - ] - }, - { - type: "object", - properties: { - enforceForRenamedProperties: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ] - }, - create(context) { - - const enabledTypes = context.options[0]; - const enforceForRenamedProperties = context.options[1] && context.options[1].enforceForRenamedProperties; - let normalizedOptions = { - VariableDeclarator: { array: true, object: true }, - AssignmentExpression: { array: true, object: true } - }; - - if (enabledTypes) { - normalizedOptions = typeof enabledTypes.array !== "undefined" || typeof enabledTypes.object !== "undefined" - ? { VariableDeclarator: enabledTypes, AssignmentExpression: enabledTypes } - : enabledTypes; - } - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * @param {string} nodeType "AssignmentExpression" or "VariableDeclarator" - * @param {string} destructuringType "array" or "object" - * @returns {boolean} `true` if the destructuring type should be checked for the given node - */ - function shouldCheck(nodeType, destructuringType) { - return normalizedOptions && - normalizedOptions[nodeType] && - normalizedOptions[nodeType][destructuringType]; - } - - /** - * Determines if the given 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 - * @param {Function|null} fix the fix function or null to pass to context.report - * @returns {void} - */ - function report(reportNode, type, fix) { - context.report({ - node: reportNode, - message: "Use {{type}} destructuring.", - data: { type }, - fix - }); - } - - /** - * Determines if a node should be fixed into object destructuring - * - * The fixer only fixes the simplest case of object destructuring, - * like: `let x = a.x`; - * - * Assignment expression is not fixed. - * Array destructuring is not fixed. - * Renamed property is not fixed. - * - * @param {ASTNode} node the the node to evaluate - * @returns {boolean} whether or not the node should be fixed - */ - function shouldFix(node) { - return node.type === "VariableDeclarator" && - node.id.type === "Identifier" && - node.init.type === "MemberExpression" && - node.id.name === node.init.property.name; - } - - /** - * Fix a node into object destructuring. - * This function only handles the simplest case of object destructuring, - * see {@link shouldFix}. - * - * @param {SourceCodeFixer} fixer the fixer object - * @param {ASTNode} node the node to be fixed. - * @returns {Object} a fix for the node - */ - function fixIntoObjectDestructuring(fixer, node) { - const rightNode = node.init; - const sourceCode = context.getSourceCode(); - - return fixer.replaceText( - node, - `{${rightNode.property.name}} = ${sourceCode.getText(rightNode.object)}` - ); - } - - /** - * 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" || rightNode.object.type === "Super") { - return; - } - - if (isArrayIndexAccess(rightNode)) { - if (shouldCheck(reportNode.type, "array")) { - report(reportNode, "array", null); - } - return; - } - - const fix = shouldFix(reportNode) - ? fixer => fixIntoObjectDestructuring(fixer, reportNode) - : null; - - if (shouldCheck(reportNode.type, "object") && enforceForRenamedProperties) { - report(reportNode, "object", fix); - return; - } - - if (shouldCheck(reportNode.type, "object")) { - const property = rightNode.property; - - if ( - (property.type === "Literal" && leftNode.name === property.value) || - (property.type === "Identifier" && leftNode.name === property.name && !rightNode.computed) - ) { - report(reportNode, "object", fix); - } - } - } - - /** - * 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) { - if (node.operator === "=") { - performCheck(node.left, node.right, node); - } - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - VariableDeclarator: checkVariableDeclarator, - AssignmentExpression: checkAssigmentExpression - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/prefer-numeric-literals.js b/tools/node_modules/eslint/lib/rules/prefer-numeric-literals.js deleted file mode 100644 index ca7358aa013bda..00000000000000 --- a/tools/node_modules/eslint/lib/rules/prefer-numeric-literals.js +++ /dev/null @@ -1,114 +0,0 @@ -/** - * @fileoverview Rule to disallow `parseInt()` in favor of binary, octal, and hexadecimal literals - * @author Annie Zhang, Henry Zhu - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks to see if a CallExpression's callee node is `parseInt` or - * `Number.parseInt`. - * @param {ASTNode} calleeNode The callee node to evaluate. - * @returns {boolean} True if the callee is `parseInt` or `Number.parseInt`, - * false otherwise. - */ -function isParseInt(calleeNode) { - switch (calleeNode.type) { - case "Identifier": - return calleeNode.name === "parseInt"; - case "MemberExpression": - return calleeNode.object.type === "Identifier" && - calleeNode.object.name === "Number" && - calleeNode.property.type === "Identifier" && - calleeNode.property.name === "parseInt"; - - // no default - } - - return false; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow `parseInt()` and `Number.parseInt()` in favor of binary, octal, and hexadecimal literals", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/prefer-numeric-literals" - }, - - schema: [], - fixable: "code" - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - const radixMap = { - 2: "binary", - 8: "octal", - 16: "hexadecimal" - }; - - const prefixMap = { - 2: "0b", - 8: "0o", - 16: "0x" - }; - - //---------------------------------------------------------------------- - // Public - //---------------------------------------------------------------------- - - return { - - CallExpression(node) { - - // doesn't check parseInt() if it doesn't have a radix argument - if (node.arguments.length !== 2) { - return; - } - - // only error if the radix is 2, 8, or 16 - const radixName = radixMap[node.arguments[1].value]; - - if (isParseInt(node.callee) && - radixName && - node.arguments[0].type === "Literal" - ) { - context.report({ - node, - message: "Use {{radixName}} literals instead of {{functionName}}().", - data: { - radixName, - functionName: sourceCode.getText(node.callee) - }, - fix(fixer) { - const newPrefix = prefixMap[node.arguments[1].value]; - - if (+(newPrefix + node.arguments[0].value) !== parseInt(node.arguments[0].value, node.arguments[1].value)) { - - /* - * If the newly-produced literal would be invalid, (e.g. 0b1234), - * or it would yield an incorrect parseInt result for some other reason, don't make a fix. - */ - return null; - } - return fixer.replaceText(node, prefixMap[node.arguments[1].value] + node.arguments[0].value); - } - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/prefer-object-spread.js b/tools/node_modules/eslint/lib/rules/prefer-object-spread.js deleted file mode 100644 index 4d724339db0573..00000000000000 --- a/tools/node_modules/eslint/lib/rules/prefer-object-spread.js +++ /dev/null @@ -1,265 +0,0 @@ -/** - * @fileoverview Prefers object spread property over Object.assign - * @author Sharmila Jesupaul - * See LICENSE file in root directory for full license. - */ - -"use strict"; - -const { CALL, ReferenceTracker } = require("eslint-utils"); -const { - isCommaToken, - isOpeningParenToken, - isClosingParenToken, - isParenthesised -} = require("../util/ast-utils"); - -const ANY_SPACE = /\s/; - -/** - * Helper that checks if the Object.assign call has array spread - * @param {ASTNode} node - The node that the rule warns on - * @returns {boolean} - Returns true if the Object.assign call has array spread - */ -function hasArraySpread(node) { - return node.arguments.some(arg => arg.type === "SpreadElement"); -} - -/** - * Helper that checks if the node needs parentheses to be valid JS. - * The default is to wrap the node in parentheses to avoid parsing errors. - * @param {ASTNode} node - The node that the rule warns on - * @param {Object} sourceCode - in context sourcecode object - * @returns {boolean} - Returns true if the node needs parentheses - */ -function needsParens(node, sourceCode) { - const parent = node.parent; - - switch (parent.type) { - case "VariableDeclarator": - case "ArrayExpression": - case "ReturnStatement": - case "CallExpression": - case "Property": - return false; - case "AssignmentExpression": - return parent.left === node && !isParenthesised(sourceCode, node); - default: - return !isParenthesised(sourceCode, node); - } -} - -/** - * Determines if an argument needs parentheses. The default is to not add parens. - * @param {ASTNode} node - The node to be checked. - * @param {Object} sourceCode - in context sourcecode object - * @returns {boolean} True if the node needs parentheses - */ -function argNeedsParens(node, sourceCode) { - switch (node.type) { - case "AssignmentExpression": - case "ArrowFunctionExpression": - case "ConditionalExpression": - return !isParenthesised(sourceCode, node); - default: - return false; - } -} - -/** - * Get the parenthesis tokens of a given ObjectExpression node. - * This incldues the braces of the object literal and enclosing parentheses. - * @param {ASTNode} node The node to get. - * @param {Token} leftArgumentListParen The opening paren token of the argument list. - * @param {SourceCode} sourceCode The source code object to get tokens. - * @returns {Token[]} The parenthesis tokens of the node. This is sorted by the location. - */ -function getParenTokens(node, leftArgumentListParen, sourceCode) { - const parens = [sourceCode.getFirstToken(node), sourceCode.getLastToken(node)]; - let leftNext = sourceCode.getTokenBefore(node); - let rightNext = sourceCode.getTokenAfter(node); - - // Note: don't include the parens of the argument list. - while ( - leftNext && - rightNext && - leftNext.range[0] > leftArgumentListParen.range[0] && - isOpeningParenToken(leftNext) && - isClosingParenToken(rightNext) - ) { - parens.push(leftNext, rightNext); - leftNext = sourceCode.getTokenBefore(leftNext); - rightNext = sourceCode.getTokenAfter(rightNext); - } - - return parens.sort((a, b) => a.range[0] - b.range[0]); -} - -/** - * Get the range of a given token and around whitespaces. - * @param {Token} token The token to get range. - * @param {SourceCode} sourceCode The source code object to get tokens. - * @returns {number} The end of the range of the token and around whitespaces. - */ -function getStartWithSpaces(token, sourceCode) { - const text = sourceCode.text; - let start = token.range[0]; - - // If the previous token is a line comment then skip this step to avoid commenting this token out. - { - const prevToken = sourceCode.getTokenBefore(token, { includeComments: true }); - - if (prevToken && prevToken.type === "Line") { - return start; - } - } - - // Detect spaces before the token. - while (ANY_SPACE.test(text[start - 1] || "")) { - start -= 1; - } - - return start; -} - -/** - * Get the range of a given token and around whitespaces. - * @param {Token} token The token to get range. - * @param {SourceCode} sourceCode The source code object to get tokens. - * @returns {number} The start of the range of the token and around whitespaces. - */ -function getEndWithSpaces(token, sourceCode) { - const text = sourceCode.text; - let end = token.range[1]; - - // Detect spaces after the token. - while (ANY_SPACE.test(text[end] || "")) { - end += 1; - } - - return end; -} - -/** - * Autofixes the Object.assign call to use an object spread instead. - * @param {ASTNode|null} node - The node that the rule warns on, i.e. the Object.assign call - * @param {string} sourceCode - sourceCode of the Object.assign call - * @returns {Function} autofixer - replaces the Object.assign with a spread object. - */ -function defineFixer(node, sourceCode) { - return function *(fixer) { - const leftParen = sourceCode.getTokenAfter(node.callee, isOpeningParenToken); - const rightParen = sourceCode.getLastToken(node); - - // Remove the callee `Object.assign` - yield fixer.remove(node.callee); - - // Replace the parens of argument list to braces. - if (needsParens(node, sourceCode)) { - yield fixer.replaceText(leftParen, "({"); - yield fixer.replaceText(rightParen, "})"); - } else { - yield fixer.replaceText(leftParen, "{"); - yield fixer.replaceText(rightParen, "}"); - } - - // Process arguments. - for (const argNode of node.arguments) { - const innerParens = getParenTokens(argNode, leftParen, sourceCode); - const left = innerParens.shift(); - const right = innerParens.pop(); - - if (argNode.type === "ObjectExpression") { - const maybeTrailingComma = sourceCode.getLastToken(argNode, 1); - const maybeArgumentComma = sourceCode.getTokenAfter(right); - - /* - * Make bare this object literal. - * And remove spaces inside of the braces for better formatting. - */ - for (const innerParen of innerParens) { - yield fixer.remove(innerParen); - } - const leftRange = [left.range[0], getEndWithSpaces(left, sourceCode)]; - const rightRange = [ - Math.max(getStartWithSpaces(right, sourceCode), leftRange[1]), // Ensure ranges don't overlap - right.range[1] - ]; - - yield fixer.removeRange(leftRange); - yield fixer.removeRange(rightRange); - - // Remove the comma of this argument if it's duplication. - if ( - (argNode.properties.length === 0 || isCommaToken(maybeTrailingComma)) && - isCommaToken(maybeArgumentComma) - ) { - yield fixer.remove(maybeArgumentComma); - } - } else { - - // Make spread. - if (argNeedsParens(argNode, sourceCode)) { - yield fixer.insertTextBefore(left, "...("); - yield fixer.insertTextAfter(right, ")"); - } else { - yield fixer.insertTextBefore(left, "..."); - } - } - } - }; -} - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: - "disallow using Object.assign with an object literal as the first argument and prefer the use of object spread instead.", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/prefer-object-spread" - }, - - schema: [], - fixable: "code", - - messages: { - useSpreadMessage: "Use an object spread instead of `Object.assign` eg: `{ ...foo }`.", - useLiteralMessage: "Use an object literal instead of `Object.assign`. eg: `{ foo: bar }`." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - return { - Program() { - const scope = context.getScope(); - const tracker = new ReferenceTracker(scope); - const trackMap = { - Object: { - assign: { [CALL]: true } - } - }; - - // Iterate all calls of `Object.assign` (only of the global variable `Object`). - for (const { node } of tracker.iterateGlobalReferences(trackMap)) { - if ( - node.arguments.length >= 1 && - node.arguments[0].type === "ObjectExpression" && - !hasArraySpread(node) - ) { - const messageId = node.arguments.length === 1 - ? "useLiteralMessage" - : "useSpreadMessage"; - const fix = defineFixer(node, sourceCode); - - context.report({ node, messageId, fix }); - } - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/prefer-promise-reject-errors.js b/tools/node_modules/eslint/lib/rules/prefer-promise-reject-errors.js deleted file mode 100644 index 275e705f6d5ca7..00000000000000 --- a/tools/node_modules/eslint/lib/rules/prefer-promise-reject-errors.js +++ /dev/null @@ -1,129 +0,0 @@ -/** - * @fileoverview restrict values that can be used as Promise rejection reasons - * @author Teddy Katz - */ -"use strict"; - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require using Error objects as Promise rejection reasons", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/prefer-promise-reject-errors" - }, - - fixable: null, - - schema: [ - { - type: "object", - properties: { - allowEmptyReject: { type: "boolean", default: false } - }, - additionalProperties: false - } - ] - }, - - create(context) { - - const ALLOW_EMPTY_REJECT = context.options.length && context.options[0].allowEmptyReject; - - //---------------------------------------------------------------------- - // Helpers - //---------------------------------------------------------------------- - - /** - * Checks the argument of a reject() or Promise.reject() CallExpression, and reports it if it can't be an Error - * @param {ASTNode} callExpression A CallExpression node which is used to reject a Promise - * @returns {void} - */ - function checkRejectCall(callExpression) { - if (!callExpression.arguments.length && ALLOW_EMPTY_REJECT) { - return; - } - if ( - !callExpression.arguments.length || - !astUtils.couldBeError(callExpression.arguments[0]) || - callExpression.arguments[0].type === "Identifier" && callExpression.arguments[0].name === "undefined" - ) { - context.report({ - node: callExpression, - message: "Expected the Promise rejection reason to be an Error." - }); - } - } - - /** - * Determines whether a function call is a Promise.reject() call - * @param {ASTNode} node A CallExpression node - * @returns {boolean} `true` if the call is a Promise.reject() call - */ - function isPromiseRejectCall(node) { - return node.callee.type === "MemberExpression" && - node.callee.object.type === "Identifier" && node.callee.object.name === "Promise" && - node.callee.property.type === "Identifier" && node.callee.property.name === "reject"; - } - - //---------------------------------------------------------------------- - // Public - //---------------------------------------------------------------------- - - return { - - // Check `Promise.reject(value)` calls. - CallExpression(node) { - if (isPromiseRejectCall(node)) { - checkRejectCall(node); - } - }, - - /* - * Check for `new Promise((resolve, reject) => {})`, and check for reject() calls. - * This function is run on "NewExpression:exit" instead of "NewExpression" to ensure that - * the nodes in the expression already have the `parent` property. - */ - "NewExpression:exit"(node) { - if ( - node.callee.type === "Identifier" && node.callee.name === "Promise" && - node.arguments.length && astUtils.isFunction(node.arguments[0]) && - node.arguments[0].params.length > 1 && node.arguments[0].params[1].type === "Identifier" - ) { - context.getDeclaredVariables(node.arguments[0]) - - /* - * Find the first variable that matches the second parameter's name. - * If the first parameter has the same name as the second parameter, then the variable will actually - * be "declared" when the first parameter is evaluated, but then it will be immediately overwritten - * by the second parameter. It's not possible for an expression with the variable to be evaluated before - * the variable is overwritten, because functions with duplicate parameters cannot have destructuring or - * default assignments in their parameter lists. Therefore, it's not necessary to explicitly account for - * this case. - */ - .find(variable => variable.name === node.arguments[0].params[1].name) - - // Get the references to that variable. - .references - - // Only check the references that read the parameter's value. - .filter(ref => ref.isRead()) - - // Only check the references that are used as the callee in a function call, e.g. `reject(foo)`. - .filter(ref => ref.identifier.parent.type === "CallExpression" && ref.identifier === ref.identifier.parent.callee) - - // Check the argument of the function call to determine whether it's an Error. - .forEach(ref => checkRejectCall(ref.identifier.parent)); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/prefer-reflect.js b/tools/node_modules/eslint/lib/rules/prefer-reflect.js deleted file mode 100644 index 796bbdf05fd446..00000000000000 --- a/tools/node_modules/eslint/lib/rules/prefer-reflect.js +++ /dev/null @@ -1,123 +0,0 @@ -/** - * @fileoverview Rule to suggest using "Reflect" api over Function/Object methods - * @author Keith Cirkel - * @deprecated in ESLint v3.9.0 - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require `Reflect` methods where applicable", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/prefer-reflect" - }, - - deprecated: true, - - replacedBy: [], - - schema: [ - { - type: "object", - properties: { - exceptions: { - type: "array", - items: { - enum: [ - "apply", - "call", - "delete", - "defineProperty", - "getOwnPropertyDescriptor", - "getPrototypeOf", - "setPrototypeOf", - "isExtensible", - "getOwnPropertyNames", - "preventExtensions" - ] - }, - uniqueItems: true - } - }, - additionalProperties: false - } - ] - }, - - create(context) { - const existingNames = { - apply: "Function.prototype.apply", - call: "Function.prototype.call", - defineProperty: "Object.defineProperty", - getOwnPropertyDescriptor: "Object.getOwnPropertyDescriptor", - getPrototypeOf: "Object.getPrototypeOf", - setPrototypeOf: "Object.setPrototypeOf", - isExtensible: "Object.isExtensible", - getOwnPropertyNames: "Object.getOwnPropertyNames", - preventExtensions: "Object.preventExtensions" - }; - - const reflectSubsitutes = { - apply: "Reflect.apply", - call: "Reflect.apply", - defineProperty: "Reflect.defineProperty", - getOwnPropertyDescriptor: "Reflect.getOwnPropertyDescriptor", - getPrototypeOf: "Reflect.getPrototypeOf", - setPrototypeOf: "Reflect.setPrototypeOf", - isExtensible: "Reflect.isExtensible", - getOwnPropertyNames: "Reflect.getOwnPropertyNames", - preventExtensions: "Reflect.preventExtensions" - }; - - const exceptions = (context.options[0] || {}).exceptions || []; - - /** - * Reports the Reflect violation based on the `existing` and `substitute` - * @param {Object} node The node that violates the rule. - * @param {string} existing The existing method name that has been used. - * @param {string} substitute The Reflect substitute that should be used. - * @returns {void} - */ - function report(node, existing, substitute) { - context.report({ - node, - message: "Avoid using {{existing}}, instead use {{substitute}}.", - data: { - existing, - substitute - } - }); - } - - return { - CallExpression(node) { - const methodName = (node.callee.property || {}).name; - const isReflectCall = (node.callee.object || {}).name === "Reflect"; - const hasReflectSubsitute = Object.prototype.hasOwnProperty.call(reflectSubsitutes, methodName); - const userConfiguredException = exceptions.indexOf(methodName) !== -1; - - if (hasReflectSubsitute && !isReflectCall && !userConfiguredException) { - report(node, existingNames[methodName], reflectSubsitutes[methodName]); - } - }, - UnaryExpression(node) { - const isDeleteOperator = node.operator === "delete"; - const targetsIdentifier = node.argument.type === "Identifier"; - const userConfiguredException = exceptions.indexOf("delete") !== -1; - - if (isDeleteOperator && !targetsIdentifier && !userConfiguredException) { - report(node, "the delete keyword", "Reflect.deleteProperty"); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/prefer-rest-params.js b/tools/node_modules/eslint/lib/rules/prefer-rest-params.js deleted file mode 100644 index 95a562c4a2f4de..00000000000000 --- a/tools/node_modules/eslint/lib/rules/prefer-rest-params.js +++ /dev/null @@ -1,114 +0,0 @@ -/** - * @fileoverview Rule to - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Gets the variable object of `arguments` which is defined implicitly. - * @param {eslint-scope.Scope} scope - A scope to get. - * @returns {eslint-scope.Variable} The found variable object. - */ -function getVariableOfArguments(scope) { - const variables = scope.variables; - - for (let i = 0; i < variables.length; ++i) { - const variable = variables[i]; - - if (variable.name === "arguments") { - - /* - * If there was a parameter which is named "arguments", the implicit "arguments" is not defined. - * So does fast return with null. - */ - return (variable.identifiers.length === 0) ? variable : null; - } - } - - /* istanbul ignore next : unreachable */ - return null; -} - -/** - * Checks if the given reference is not normal member access. - * - * - arguments .... true // not member access - * - arguments[i] .... true // computed member access - * - arguments[0] .... true // computed member access - * - arguments.length .... false // normal member access - * - * @param {eslint-scope.Reference} reference - The reference to check. - * @returns {boolean} `true` if the reference is not normal member access. - */ -function isNotNormalMemberAccess(reference) { - const id = reference.identifier; - const parent = id.parent; - - return !( - parent.type === "MemberExpression" && - parent.object === id && - !parent.computed - ); -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require rest parameters instead of `arguments`", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/prefer-rest-params" - }, - - schema: [] - }, - - create(context) { - - /** - * Reports a given reference. - * - * @param {eslint-scope.Reference} reference - A reference to report. - * @returns {void} - */ - function report(reference) { - context.report({ - node: reference.identifier, - loc: reference.identifier.loc, - message: "Use the rest parameters instead of 'arguments'." - }); - } - - /** - * Reports references of the implicit `arguments` variable if exist. - * - * @returns {void} - */ - function checkForArguments() { - const argumentsVar = getVariableOfArguments(context.getScope()); - - if (argumentsVar) { - argumentsVar - .references - .filter(isNotNormalMemberAccess) - .forEach(report); - } - } - - return { - "FunctionDeclaration:exit": checkForArguments, - "FunctionExpression:exit": checkForArguments - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/prefer-spread.js b/tools/node_modules/eslint/lib/rules/prefer-spread.js deleted file mode 100644 index 5f3a477329b700..00000000000000 --- a/tools/node_modules/eslint/lib/rules/prefer-spread.js +++ /dev/null @@ -1,87 +0,0 @@ -/** - * @fileoverview A rule to suggest using of the spread operator instead of `.apply()`. - * @author Toru Nagashima - */ - -"use strict"; - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks whether or not a node is a `.apply()` for variadic. - * @param {ASTNode} node - A CallExpression node to check. - * @returns {boolean} Whether or not the node is a `.apply()` for variadic. - */ -function isVariadicApplyCalling(node) { - return ( - node.callee.type === "MemberExpression" && - node.callee.property.type === "Identifier" && - node.callee.property.name === "apply" && - node.callee.computed === false && - node.arguments.length === 2 && - node.arguments[1].type !== "ArrayExpression" && - node.arguments[1].type !== "SpreadElement" - ); -} - - -/** - * Checks whether or not `thisArg` is not changed by `.apply()`. - * @param {ASTNode|null} expectedThis - The node that is the owner of the applied function. - * @param {ASTNode} thisArg - The node that is given to the first argument of the `.apply()`. - * @param {RuleContext} context - The ESLint rule context object. - * @returns {boolean} Whether or not `thisArg` is not changed by `.apply()`. - */ -function isValidThisArg(expectedThis, thisArg, context) { - if (!expectedThis) { - return astUtils.isNullOrUndefined(thisArg); - } - return astUtils.equalTokens(expectedThis, thisArg, context); -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require spread operators instead of `.apply()`", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/prefer-spread" - }, - - schema: [], - fixable: null - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - return { - CallExpression(node) { - if (!isVariadicApplyCalling(node)) { - return; - } - - const applied = node.callee.object; - const expectedThis = (applied.type === "MemberExpression") ? applied.object : null; - const thisArg = node.arguments[0]; - - if (isValidThisArg(expectedThis, thisArg, sourceCode)) { - context.report({ - node, - message: "Use the spread operator instead of '.apply()'." - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/prefer-template.js b/tools/node_modules/eslint/lib/rules/prefer-template.js deleted file mode 100644 index 386674a92ef9c3..00000000000000 --- a/tools/node_modules/eslint/lib/rules/prefer-template.js +++ /dev/null @@ -1,289 +0,0 @@ -/** - * @fileoverview A rule to suggest using template literals instead of string concatenation. - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks whether or not a given node is a concatenation. - * @param {ASTNode} node - A node to check. - * @returns {boolean} `true` if the node is a concatenation. - */ -function isConcatenation(node) { - return node.type === "BinaryExpression" && node.operator === "+"; -} - -/** - * Gets the top binary expression node for concatenation in parents of a given node. - * @param {ASTNode} node - A node to get. - * @returns {ASTNode} the top binary expression node in parents of a given node. - */ -function getTopConcatBinaryExpression(node) { - let currentNode = node; - - while (isConcatenation(currentNode.parent)) { - currentNode = currentNode.parent; - } - return currentNode; -} - -/** - * Determines whether a given node is a octal escape sequence - * @param {ASTNode} node A node to check - * @returns {boolean} `true` if the node is an octal escape sequence - */ -function isOctalEscapeSequence(node) { - - // No need to check TemplateLiterals – would throw error with octal escape - const isStringLiteral = node.type === "Literal" && typeof node.value === "string"; - - if (!isStringLiteral) { - return false; - } - - const match = node.raw.match(/^([^\\]|\\[^0-7])*\\([0-7]{1,3})/); - - if (match) { - - // \0 is actually not considered an octal - if (match[2] !== "0" || typeof match[3] !== "undefined") { - return true; - } - } - return false; -} - -/** - * Checks whether or not a node contains a octal escape sequence - * @param {ASTNode} node A node to check - * @returns {boolean} `true` if the node contains an octal escape sequence - */ -function hasOctalEscapeSequence(node) { - if (isConcatenation(node)) { - return hasOctalEscapeSequence(node.left) || hasOctalEscapeSequence(node.right); - } - - return isOctalEscapeSequence(node); -} - -/** - * Checks whether or not a given binary expression has string literals. - * @param {ASTNode} node - A node to check. - * @returns {boolean} `true` if the node has string literals. - */ -function hasStringLiteral(node) { - if (isConcatenation(node)) { - - // `left` is deeper than `right` normally. - return hasStringLiteral(node.right) || hasStringLiteral(node.left); - } - return astUtils.isStringLiteral(node); -} - -/** - * Checks whether or not a given binary expression has non string literals. - * @param {ASTNode} node - A node to check. - * @returns {boolean} `true` if the node has non string literals. - */ -function hasNonStringLiteral(node) { - if (isConcatenation(node)) { - - // `left` is deeper than `right` normally. - return hasNonStringLiteral(node.right) || hasNonStringLiteral(node.left); - } - return !astUtils.isStringLiteral(node); -} - -/** - * Determines whether a given node will start with a template curly expression (`${}`) when being converted to a template literal. - * @param {ASTNode} node The node that will be fixed to a template literal - * @returns {boolean} `true` if the node will start with a template curly. - */ -function startsWithTemplateCurly(node) { - if (node.type === "BinaryExpression") { - return startsWithTemplateCurly(node.left); - } - if (node.type === "TemplateLiteral") { - return node.expressions.length && node.quasis.length && node.quasis[0].range[0] === node.quasis[0].range[1]; - } - return node.type !== "Literal" || typeof node.value !== "string"; -} - -/** - * Determines whether a given node end with a template curly expression (`${}`) when being converted to a template literal. - * @param {ASTNode} node The node that will be fixed to a template literal - * @returns {boolean} `true` if the node will end with a template curly. - */ -function endsWithTemplateCurly(node) { - if (node.type === "BinaryExpression") { - return startsWithTemplateCurly(node.right); - } - if (node.type === "TemplateLiteral") { - return node.expressions.length && node.quasis.length && node.quasis[node.quasis.length - 1].range[0] === node.quasis[node.quasis.length - 1].range[1]; - } - return node.type !== "Literal" || typeof node.value !== "string"; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require template literals instead of string concatenation", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/prefer-template" - }, - - schema: [], - fixable: "code" - }, - - create(context) { - const sourceCode = context.getSourceCode(); - let done = Object.create(null); - - /** - * Gets the non-token text between two nodes, ignoring any other tokens that appear between the two tokens. - * @param {ASTNode} node1 The first node - * @param {ASTNode} node2 The second node - * @returns {string} The text between the nodes, excluding other tokens - */ - function getTextBetween(node1, node2) { - const allTokens = [node1].concat(sourceCode.getTokensBetween(node1, node2)).concat(node2); - const sourceText = sourceCode.getText(); - - return allTokens.slice(0, -1).reduce((accumulator, token, index) => accumulator + sourceText.slice(token.range[1], allTokens[index + 1].range[0]), ""); - } - - /** - * Returns a template literal form of the given node. - * @param {ASTNode} currentNode A node that should be converted to a template literal - * @param {string} textBeforeNode Text that should appear before the node - * @param {string} textAfterNode Text that should appear after the node - * @returns {string} A string form of this node, represented as a template literal - */ - function getTemplateLiteral(currentNode, textBeforeNode, textAfterNode) { - if (currentNode.type === "Literal" && typeof currentNode.value === "string") { - - /* - * If the current node is a string literal, escape any instances of ${ or ` to prevent them from being interpreted - * as a template placeholder. However, if the code already contains a backslash before the ${ or ` - * for some reason, don't add another backslash, because that would change the meaning of the code (it would cause - * an actual backslash character to appear before the dollar sign). - */ - return `\`${currentNode.raw.slice(1, -1).replace(/\\*(\${|`)/g, matched => { - if (matched.lastIndexOf("\\") % 2) { - return `\\${matched}`; - } - return matched; - - // Unescape any quotes that appear in the original Literal that no longer need to be escaped. - }).replace(new RegExp(`\\\\${currentNode.raw[0]}`, "g"), currentNode.raw[0])}\``; - } - - if (currentNode.type === "TemplateLiteral") { - return sourceCode.getText(currentNode); - } - - if (isConcatenation(currentNode) && hasStringLiteral(currentNode) && hasNonStringLiteral(currentNode)) { - const plusSign = sourceCode.getFirstTokenBetween(currentNode.left, currentNode.right, token => token.value === "+"); - const textBeforePlus = getTextBetween(currentNode.left, plusSign); - const textAfterPlus = getTextBetween(plusSign, currentNode.right); - const leftEndsWithCurly = endsWithTemplateCurly(currentNode.left); - const rightStartsWithCurly = startsWithTemplateCurly(currentNode.right); - - if (leftEndsWithCurly) { - - // If the left side of the expression ends with a template curly, add the extra text to the end of the curly bracket. - // `foo${bar}` /* comment */ + 'baz' --> `foo${bar /* comment */ }${baz}` - return getTemplateLiteral(currentNode.left, textBeforeNode, textBeforePlus + textAfterPlus).slice(0, -1) + - getTemplateLiteral(currentNode.right, null, textAfterNode).slice(1); - } - if (rightStartsWithCurly) { - - // Otherwise, if the right side of the expression starts with a template curly, add the text there. - // 'foo' /* comment */ + `${bar}baz` --> `foo${ /* comment */ bar}baz` - return getTemplateLiteral(currentNode.left, textBeforeNode, null).slice(0, -1) + - getTemplateLiteral(currentNode.right, textBeforePlus + textAfterPlus, textAfterNode).slice(1); - } - - /* - * Otherwise, these nodes should not be combined into a template curly, since there is nowhere to put - * the text between them. - */ - return `${getTemplateLiteral(currentNode.left, textBeforeNode, null)}${textBeforePlus}+${textAfterPlus}${getTemplateLiteral(currentNode.right, textAfterNode, null)}`; - } - - return `\`\${${textBeforeNode || ""}${sourceCode.getText(currentNode)}${textAfterNode || ""}}\``; - } - - /** - * Returns a fixer object that converts a non-string binary expression to a template literal - * @param {SourceCodeFixer} fixer The fixer object - * @param {ASTNode} node A node that should be converted to a template literal - * @returns {Object} A fix for this binary expression - */ - function fixNonStringBinaryExpression(fixer, node) { - const topBinaryExpr = getTopConcatBinaryExpression(node.parent); - - if (hasOctalEscapeSequence(topBinaryExpr)) { - return null; - } - - return fixer.replaceText(topBinaryExpr, getTemplateLiteral(topBinaryExpr, null, null)); - } - - /** - * Reports if a given node is string concatenation with non string literals. - * - * @param {ASTNode} node - A node to check. - * @returns {void} - */ - function checkForStringConcat(node) { - if (!astUtils.isStringLiteral(node) || !isConcatenation(node.parent)) { - return; - } - - const topBinaryExpr = getTopConcatBinaryExpression(node.parent); - - // Checks whether or not this node had been checked already. - if (done[topBinaryExpr.range[0]]) { - return; - } - done[topBinaryExpr.range[0]] = true; - - if (hasNonStringLiteral(topBinaryExpr)) { - context.report({ - node: topBinaryExpr, - message: "Unexpected string concatenation.", - fix: fixer => fixNonStringBinaryExpression(fixer, node) - }); - } - } - - return { - Program() { - done = Object.create(null); - }, - - Literal: checkForStringConcat, - TemplateLiteral: checkForStringConcat - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/quote-props.js b/tools/node_modules/eslint/lib/rules/quote-props.js deleted file mode 100644 index f4582dd1f4a87c..00000000000000 --- a/tools/node_modules/eslint/lib/rules/quote-props.js +++ /dev/null @@ -1,306 +0,0 @@ -/** - * @fileoverview Rule to flag non-quoted property names in object literals. - * @author Mathias Bynens - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const espree = require("espree"), - keywords = require("../util/keywords"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require quotes around object literal property names", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/quote-props" - }, - - schema: { - anyOf: [ - { - type: "array", - items: [ - { - enum: ["always", "as-needed", "consistent", "consistent-as-needed"], - default: "always" - } - ], - minItems: 0, - maxItems: 1 - }, - { - type: "array", - items: [ - { - enum: ["always", "as-needed", "consistent", "consistent-as-needed"], - default: "always" - }, - { - type: "object", - properties: { - keywords: { - type: "boolean", - default: false - }, - unnecessary: { - type: "boolean", - default: true - }, - numbers: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - minItems: 0, - maxItems: 2 - } - ] - }, - - fixable: "code" - }, - - create(context) { - - const MODE = context.options[0], - KEYWORDS = context.options[1] && context.options[1].keywords, - CHECK_UNNECESSARY = !context.options[1] || context.options[1].unnecessary !== false, - NUMBERS = context.options[1] && context.options[1].numbers, - - MESSAGE_UNNECESSARY = "Unnecessarily quoted property '{{property}}' found.", - MESSAGE_UNQUOTED = "Unquoted property '{{property}}' found.", - MESSAGE_NUMERIC = "Unquoted number literal '{{property}}' used as key.", - MESSAGE_RESERVED = "Unquoted reserved word '{{property}}' used as key.", - sourceCode = context.getSourceCode(); - - - /** - * Checks whether a certain string constitutes an ES3 token - * @param {string} tokenStr - The string to be checked. - * @returns {boolean} `true` if it is an ES3 token. - */ - function isKeyword(tokenStr) { - return keywords.indexOf(tokenStr) >= 0; - } - - /** - * Checks if an espree-tokenized key has redundant quotes (i.e. whether quotes are unnecessary) - * @param {string} rawKey The raw key value from the source - * @param {espreeTokens} tokens The espree-tokenized node key - * @param {boolean} [skipNumberLiterals=false] Indicates whether number literals should be checked - * @returns {boolean} Whether or not a key has redundant quotes. - * @private - */ - function areQuotesRedundant(rawKey, tokens, skipNumberLiterals) { - return tokens.length === 1 && tokens[0].start === 0 && tokens[0].end === rawKey.length && - (["Identifier", "Keyword", "Null", "Boolean"].indexOf(tokens[0].type) >= 0 || - (tokens[0].type === "Numeric" && !skipNumberLiterals && String(+tokens[0].value) === tokens[0].value)); - } - - /** - * Returns a string representation of a property node with quotes removed - * @param {ASTNode} key Key AST Node, which may or may not be quoted - * @returns {string} A replacement string for this property - */ - function getUnquotedKey(key) { - return key.type === "Identifier" ? key.name : key.value; - } - - /** - * Returns a string representation of a property node with quotes added - * @param {ASTNode} key Key AST Node, which may or may not be quoted - * @returns {string} A replacement string for this property - */ - function getQuotedKey(key) { - if (key.type === "Literal" && typeof key.value === "string") { - - // If the key is already a string literal, don't replace the quotes with double quotes. - return sourceCode.getText(key); - } - - // Otherwise, the key is either an identifier or a number literal. - return `"${key.type === "Identifier" ? key.name : key.value}"`; - } - - /** - * Ensures that a property's key is quoted only when necessary - * @param {ASTNode} node Property AST node - * @returns {void} - */ - function checkUnnecessaryQuotes(node) { - const key = node.key; - - if (node.method || node.computed || node.shorthand) { - return; - } - - if (key.type === "Literal" && typeof key.value === "string") { - let tokens; - - try { - tokens = espree.tokenize(key.value); - } catch (e) { - return; - } - - if (tokens.length !== 1) { - return; - } - - const isKeywordToken = isKeyword(tokens[0].value); - - if (isKeywordToken && KEYWORDS) { - return; - } - - if (CHECK_UNNECESSARY && areQuotesRedundant(key.value, tokens, NUMBERS)) { - context.report({ - node, - message: MESSAGE_UNNECESSARY, - data: { property: key.value }, - fix: fixer => fixer.replaceText(key, getUnquotedKey(key)) - }); - } - } else if (KEYWORDS && key.type === "Identifier" && isKeyword(key.name)) { - context.report({ - node, - message: MESSAGE_RESERVED, - 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 }, - fix: fixer => fixer.replaceText(key, getQuotedKey(key)) - }); - } - } - - /** - * Ensures that a property's key is quoted - * @param {ASTNode} node Property AST node - * @returns {void} - */ - function checkOmittedQuotes(node) { - const key = node.key; - - if (!node.method && !node.computed && !node.shorthand && !(key.type === "Literal" && typeof key.value === "string")) { - context.report({ - node, - message: MESSAGE_UNQUOTED, - data: { property: key.name || key.value }, - fix: fixer => fixer.replaceText(key, getQuotedKey(key)) - }); - } - } - - /** - * Ensures that an object's keys are consistently quoted, optionally checks for redundancy of quotes - * @param {ASTNode} node Property AST node - * @param {boolean} checkQuotesRedundancy Whether to check quotes' redundancy - * @returns {void} - */ - function checkConsistency(node, checkQuotesRedundancy) { - const quotedProps = [], - unquotedProps = []; - let keywordKeyName = null, - necessaryQuotes = false; - - node.properties.forEach(property => { - const key = property.key; - - if (!key || property.method || property.computed || property.shorthand) { - return; - } - - if (key.type === "Literal" && typeof key.value === "string") { - - quotedProps.push(property); - - if (checkQuotesRedundancy) { - let tokens; - - try { - tokens = espree.tokenize(key.value); - } catch (e) { - necessaryQuotes = true; - return; - } - - necessaryQuotes = necessaryQuotes || !areQuotesRedundant(key.value, tokens) || KEYWORDS && isKeyword(tokens[0].value); - } - } else if (KEYWORDS && checkQuotesRedundancy && key.type === "Identifier" && isKeyword(key.name)) { - unquotedProps.push(property); - necessaryQuotes = true; - keywordKeyName = key.name; - } else { - unquotedProps.push(property); - } - }); - - if (checkQuotesRedundancy && quotedProps.length && !necessaryQuotes) { - quotedProps.forEach(property => { - context.report({ - node: property, - message: "Properties shouldn't be quoted as all quotes are redundant.", - fix: fixer => fixer.replaceText(property.key, getUnquotedKey(property.key)) - }); - }); - } else if (unquotedProps.length && keywordKeyName) { - unquotedProps.forEach(property => { - context.report({ - node: property, - message: "Properties should be quoted as '{{property}}' is a reserved word.", - data: { property: keywordKeyName }, - fix: fixer => fixer.replaceText(property.key, getQuotedKey(property.key)) - }); - }); - } else if (quotedProps.length && unquotedProps.length) { - unquotedProps.forEach(property => { - context.report({ - node: property, - message: "Inconsistently quoted property '{{key}}' found.", - data: { key: property.key.name || property.key.value }, - fix: fixer => fixer.replaceText(property.key, getQuotedKey(property.key)) - }); - }); - } - } - - return { - Property(node) { - if (MODE === "always" || !MODE) { - checkOmittedQuotes(node); - } - if (MODE === "as-needed") { - checkUnnecessaryQuotes(node); - } - }, - ObjectExpression(node) { - if (MODE === "consistent") { - checkConsistency(node, false); - } - if (MODE === "consistent-as-needed") { - checkConsistency(node, true); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/quotes.js b/tools/node_modules/eslint/lib/rules/quotes.js deleted file mode 100644 index e0797f9e8be3bb..00000000000000 --- a/tools/node_modules/eslint/lib/rules/quotes.js +++ /dev/null @@ -1,325 +0,0 @@ -/** - * @fileoverview A rule to choose between single and double quote marks - * @author Matt DuVall , Brandon Payton - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Constants -//------------------------------------------------------------------------------ - -const QUOTE_SETTINGS = { - double: { - quote: "\"", - alternateQuote: "'", - description: "doublequote" - }, - single: { - quote: "'", - alternateQuote: "\"", - description: "singlequote" - }, - backtick: { - quote: "`", - alternateQuote: "\"", - description: "backtick" - } -}; - -// An unescaped newline is a newline preceded by an even number of backslashes. -const UNESCAPED_LINEBREAK_PATTERN = new RegExp(String.raw`(^|[^\\])(\\\\)*[${Array.from(astUtils.LINEBREAKS).join("")}]`); - -/** - * Switches quoting of javascript string between ' " and ` - * escaping and unescaping as necessary. - * Only escaping of the minimal set of characters is changed. - * Note: escaping of newlines when switching from backtick to other quotes is not handled. - * @param {string} str - A string to convert. - * @returns {string} The string with changed quotes. - * @private - */ -QUOTE_SETTINGS.double.convert = -QUOTE_SETTINGS.single.convert = -QUOTE_SETTINGS.backtick.convert = function(str) { - const newQuote = this.quote; - const oldQuote = str[0]; - - if (newQuote === oldQuote) { - return str; - } - 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 - } - if (match === newQuote || newQuote === "`" && match === "${") { - return `\\${match}`; // escape - } - if (newline && oldQuote === "`") { - return "\\n"; // escape newlines - } - return match; - }) + newQuote; -}; - -const AVOID_ESCAPE = "avoid-escape"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce the consistent use of either backticks, double, or single quotes", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/quotes" - }, - - fixable: "code", - - schema: [ - { - enum: ["single", "double", "backtick"] - }, - { - anyOf: [ - { - enum: ["avoid-escape"] - }, - { - type: "object", - properties: { - avoidEscape: { - type: "boolean", - default: false - }, - allowTemplateLiterals: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ] - } - ] - }, - - create(context) { - - const quoteOption = context.options[0], - settings = QUOTE_SETTINGS[quoteOption || "double"], - options = context.options[1], - allowTemplateLiterals = options && options.allowTemplateLiterals === true, - sourceCode = context.getSourceCode(); - let avoidEscape = options && options.avoidEscape === true; - - // deprecated - if (options === AVOID_ESCAPE) { - avoidEscape = true; - } - - /** - * Determines if a given node is part of JSX syntax. - * - * This function returns `true` in the following cases: - * - * - `
` ... If the literal is an attribute value, the parent of the literal is `JSXAttribute`. - * - `
foo
` ... If the literal is a text content, the parent of the literal is `JSXElement`. - * - `<>foo` ... If the literal is a text content, the parent of the literal is `JSXFragment`. - * - * In particular, this function returns `false` in the following cases: - * - * - `
` - * - `
{"foo"}
` - * - * In both cases, inside of the braces is handled as normal JavaScript. - * The braces are `JSXExpressionContainer` nodes. - * - * @param {ASTNode} node The Literal node to check. - * @returns {boolean} True if the node is a part of JSX, false if not. - * @private - */ - function isJSXLiteral(node) { - return node.parent.type === "JSXAttribute" || node.parent.type === "JSXElement" || node.parent.type === "JSXFragment"; - } - - /** - * Checks whether or not a given node is a directive. - * The directive is a `ExpressionStatement` which has only a string literal. - * @param {ASTNode} node - A node to check. - * @returns {boolean} Whether or not the node is a directive. - * @private - */ - function isDirective(node) { - return ( - node.type === "ExpressionStatement" && - node.expression.type === "Literal" && - typeof node.expression.value === "string" - ); - } - - /** - * Checks whether or not a given node is a part of directive prologues. - * See also: http://www.ecma-international.org/ecma-262/6.0/#sec-directive-prologues-and-the-use-strict-directive - * @param {ASTNode} node - A node to check. - * @returns {boolean} Whether or not the node is a part of directive prologues. - * @private - */ - function isPartOfDirectivePrologue(node) { - const block = node.parent.parent; - - if (block.type !== "Program" && (block.type !== "BlockStatement" || !astUtils.isFunction(block.parent))) { - return false; - } - - // Check the node is at a prologue. - for (let i = 0; i < block.body.length; ++i) { - const statement = block.body[i]; - - if (statement === node.parent) { - return true; - } - if (!isDirective(statement)) { - break; - } - } - - return false; - } - - /** - * Checks whether or not a given node is allowed as non backtick. - * @param {ASTNode} node - A node to check. - * @returns {boolean} Whether or not the node is allowed as non backtick. - * @private - */ - function isAllowedAsNonBacktick(node) { - const parent = node.parent; - - switch (parent.type) { - - // Directive Prologues. - case "ExpressionStatement": - return isPartOfDirectivePrologue(node); - - // LiteralPropertyName. - case "Property": - case "MethodDefinition": - return parent.key === node && !parent.computed; - - // ModuleSpecifier. - case "ImportDeclaration": - case "ExportNamedDeclaration": - case "ExportAllDeclaration": - return parent.source === node; - - // Others don't allow. - default: - return false; - } - } - - /** - * Checks whether or not a given TemplateLiteral node is actually using any of the special features provided by template literal strings. - * @param {ASTNode} node - A TemplateLiteral node to check. - * @returns {boolean} Whether or not the TemplateLiteral node is using any of the special features provided by template literal strings. - * @private - */ - function isUsingFeatureOfTemplateLiteral(node) { - const hasTag = node.parent.type === "TaggedTemplateExpression" && node === node.parent.quasi; - - if (hasTag) { - return true; - } - - const hasStringInterpolation = node.expressions.length > 0; - - if (hasStringInterpolation) { - return true; - } - - const isMultilineString = node.quasis.length >= 1 && UNESCAPED_LINEBREAK_PATTERN.test(node.quasis[0].value.raw); - - if (isMultilineString) { - return true; - } - - return false; - } - - return { - - Literal(node) { - const val = node.value, - rawVal = node.raw; - - if (settings && typeof val === "string") { - let isValid = (quoteOption === "backtick" && isAllowedAsNonBacktick(node)) || - isJSXLiteral(node) || - astUtils.isSurroundedBy(rawVal, settings.quote); - - if (!isValid && avoidEscape) { - isValid = astUtils.isSurroundedBy(rawVal, settings.alternateQuote) && rawVal.indexOf(settings.quote) >= 0; - } - - if (!isValid) { - context.report({ - node, - message: "Strings must use {{description}}.", - data: { - description: settings.description - }, - fix(fixer) { - return fixer.replaceText(node, settings.convert(node.raw)); - } - }); - } - } - }, - - TemplateLiteral(node) { - - // Don't throw an error if backticks are expected or a template literal feature is in use. - if ( - allowTemplateLiterals || - quoteOption === "backtick" || - isUsingFeatureOfTemplateLiteral(node) - ) { - return; - } - - context.report({ - node, - message: "Strings must use {{description}}.", - data: { - 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/node_modules/eslint/lib/rules/radix.js b/tools/node_modules/eslint/lib/rules/radix.js deleted file mode 100644 index 5d3805d0a70679..00000000000000 --- a/tools/node_modules/eslint/lib/rules/radix.js +++ /dev/null @@ -1,174 +0,0 @@ -/** - * @fileoverview Rule to flag use of parseInt without a radix argument - * @author James Allardice - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const MODE_ALWAYS = "always", - MODE_AS_NEEDED = "as-needed"; - -/** - * Checks whether a given variable is shadowed or not. - * - * @param {eslint-scope.Variable} variable - A variable to check. - * @returns {boolean} `true` if the variable is shadowed. - */ -function isShadowed(variable) { - return variable.defs.length >= 1; -} - -/** - * Checks whether a given node is a MemberExpression of `parseInt` method or not. - * - * @param {ASTNode} node - A node to check. - * @returns {boolean} `true` if the node is a MemberExpression of `parseInt` - * method. - */ -function isParseIntMethod(node) { - return ( - node.type === "MemberExpression" && - !node.computed && - node.property.type === "Identifier" && - node.property.name === "parseInt" - ); -} - -/** - * Checks whether a given node is a valid value of radix or not. - * - * The following values are invalid. - * - * - A literal except numbers. - * - undefined. - * - * @param {ASTNode} radix - A node of radix to check. - * @returns {boolean} `true` if the node is valid. - */ -function isValidRadix(radix) { - return !( - (radix.type === "Literal" && typeof radix.value !== "number") || - (radix.type === "Identifier" && radix.name === "undefined") - ); -} - -/** - * Checks whether a given node is a default value of radix or not. - * - * @param {ASTNode} radix - A node of radix to check. - * @returns {boolean} `true` if the node is the literal node of `10`. - */ -function isDefaultRadix(radix) { - return radix.type === "Literal" && radix.value === 10; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce the consistent use of the radix argument when using `parseInt()`", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/radix" - }, - - schema: [ - { - enum: ["always", "as-needed"] - } - ] - }, - - create(context) { - const mode = context.options[0] || MODE_ALWAYS; - - /** - * Checks the arguments of a given CallExpression node and reports it if it - * offends this rule. - * - * @param {ASTNode} node - A CallExpression node to check. - * @returns {void} - */ - function checkArguments(node) { - const args = node.arguments; - - switch (args.length) { - case 0: - context.report({ - node, - message: "Missing parameters." - }); - break; - - case 1: - if (mode === MODE_ALWAYS) { - context.report({ - node, - message: "Missing radix parameter." - }); - } - break; - - default: - if (mode === MODE_AS_NEEDED && isDefaultRadix(args[1])) { - context.report({ - node, - message: "Redundant radix parameter." - }); - } else if (!isValidRadix(args[1])) { - context.report({ - node, - message: "Invalid radix parameter." - }); - } - break; - } - } - - return { - "Program:exit"() { - const scope = context.getScope(); - let variable; - - // Check `parseInt()` - variable = astUtils.getVariableByName(scope, "parseInt"); - if (!isShadowed(variable)) { - variable.references.forEach(reference => { - const node = reference.identifier; - - if (astUtils.isCallee(node)) { - checkArguments(node.parent); - } - }); - } - - // Check `Number.parseInt()` - variable = astUtils.getVariableByName(scope, "Number"); - if (!isShadowed(variable)) { - variable.references.forEach(reference => { - const node = reference.identifier.parent; - - if (isParseIntMethod(node) && astUtils.isCallee(node)) { - checkArguments(node.parent); - } - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/require-atomic-updates.js b/tools/node_modules/eslint/lib/rules/require-atomic-updates.js deleted file mode 100644 index e8dbe17b88dcd8..00000000000000 --- a/tools/node_modules/eslint/lib/rules/require-atomic-updates.js +++ /dev/null @@ -1,300 +0,0 @@ -/** - * @fileoverview disallow assignments that can lead to race conditions due to usage of `await` or `yield` - * @author Teddy Katz - */ -"use strict"; - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow assignments that can lead to race conditions due to usage of `await` or `yield`", - category: "Possible Errors", - recommended: false, - url: "https://eslint.org/docs/rules/require-atomic-updates" - }, - - fixable: null, - schema: [], - - messages: { - nonAtomicUpdate: "Possible race condition: `{{value}}` might be reassigned based on an outdated value of `{{value}}`." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - const identifierToSurroundingFunctionMap = new WeakMap(); - const expressionsByCodePathSegment = new Map(); - - //---------------------------------------------------------------------- - // Helpers - //---------------------------------------------------------------------- - - const resolvedVariableCache = new WeakMap(); - - /** - * Gets the variable scope around this variable reference - * @param {ASTNode} identifier An `Identifier` AST node - * @returns {Scope|null} An escope Scope - */ - function getScope(identifier) { - for (let currentNode = identifier; currentNode; currentNode = currentNode.parent) { - const scope = sourceCode.scopeManager.acquire(currentNode, true); - - if (scope) { - return scope; - } - } - return null; - } - - /** - * Resolves a given identifier to a given scope - * @param {ASTNode} identifier An `Identifier` AST node - * @param {Scope} scope An escope Scope - * @returns {Variable|null} An escope Variable corresponding to the given identifier - */ - function resolveVariableInScope(identifier, scope) { - return scope.variables.find(variable => variable.name === identifier.name) || - (scope.upper ? resolveVariableInScope(identifier, scope.upper) : null); - } - - /** - * Resolves an identifier to a variable - * @param {ASTNode} identifier An identifier node - * @returns {Variable|null} The escope Variable that uses this identifier - */ - function resolveVariable(identifier) { - if (!resolvedVariableCache.has(identifier)) { - const surroundingScope = getScope(identifier); - - if (surroundingScope) { - resolvedVariableCache.set(identifier, resolveVariableInScope(identifier, surroundingScope)); - } else { - resolvedVariableCache.set(identifier, null); - } - } - - return resolvedVariableCache.get(identifier); - } - - /** - * Checks if an expression is a variable that can only be observed within the given function. - * @param {ASTNode} expression The expression to check - * @param {ASTNode} surroundingFunction The function node - * @returns {boolean} `true` if the expression is a variable which is local to the given function, and is never - * referenced in a closure. - */ - function isLocalVariableWithoutEscape(expression, surroundingFunction) { - if (expression.type !== "Identifier") { - return false; - } - - const variable = resolveVariable(expression); - - if (!variable) { - return false; - } - - return variable.references.every(reference => identifierToSurroundingFunctionMap.get(reference.identifier) === surroundingFunction) && - variable.defs.every(def => identifierToSurroundingFunctionMap.get(def.name) === surroundingFunction); - } - - /** - * Reports an AssignmentExpression node that has a non-atomic update - * @param {ASTNode} assignmentExpression The assignment that is potentially unsafe - * @returns {void} - */ - function reportAssignment(assignmentExpression) { - context.report({ - node: assignmentExpression, - messageId: "nonAtomicUpdate", - data: { - value: sourceCode.getText(assignmentExpression.left) - } - }); - } - - const alreadyReportedAssignments = new WeakSet(); - - class AssignmentTrackerState { - constructor({ openAssignmentsWithoutReads = new Set(), openAssignmentsWithReads = new Set() } = {}) { - this.openAssignmentsWithoutReads = openAssignmentsWithoutReads; - this.openAssignmentsWithReads = openAssignmentsWithReads; - } - - copy() { - return new AssignmentTrackerState({ - openAssignmentsWithoutReads: new Set(this.openAssignmentsWithoutReads), - openAssignmentsWithReads: new Set(this.openAssignmentsWithReads) - }); - } - - merge(other) { - const initialAssignmentsWithoutReadsCount = this.openAssignmentsWithoutReads.size; - const initialAssignmentsWithReadsCount = this.openAssignmentsWithReads.size; - - other.openAssignmentsWithoutReads.forEach(assignment => this.openAssignmentsWithoutReads.add(assignment)); - other.openAssignmentsWithReads.forEach(assignment => this.openAssignmentsWithReads.add(assignment)); - - return this.openAssignmentsWithoutReads.size > initialAssignmentsWithoutReadsCount || - this.openAssignmentsWithReads.size > initialAssignmentsWithReadsCount; - } - - enterAssignment(assignmentExpression) { - (assignmentExpression.operator === "=" ? this.openAssignmentsWithoutReads : this.openAssignmentsWithReads).add(assignmentExpression); - } - - exitAssignment(assignmentExpression) { - this.openAssignmentsWithoutReads.delete(assignmentExpression); - this.openAssignmentsWithReads.delete(assignmentExpression); - } - - exitAwaitOrYield(node, surroundingFunction) { - return [...this.openAssignmentsWithReads] - .filter(assignment => !isLocalVariableWithoutEscape(assignment.left, surroundingFunction)) - .forEach(assignment => { - if (!alreadyReportedAssignments.has(assignment)) { - reportAssignment(assignment); - alreadyReportedAssignments.add(assignment); - } - }); - } - - exitIdentifierOrMemberExpression(node) { - [...this.openAssignmentsWithoutReads] - .filter(assignment => ( - assignment.left !== node && - assignment.left.type === node.type && - astUtils.equalTokens(assignment.left, node, sourceCode) - )) - .forEach(assignment => { - this.openAssignmentsWithoutReads.delete(assignment); - this.openAssignmentsWithReads.add(assignment); - }); - } - } - - /** - * If the control flow graph of a function enters an assignment expression, then does the - * both of the following steps in order (possibly with other steps in between) before exiting the - * assignment expression, then the assignment might be using an outdated value. - * 1. Enters a read of the variable or property assigned in the expression (not necessary if operator assignment is used) - * 2. Exits an `await` or `yield` expression - * - * This function checks for the outdated values and reports them. - * @param {CodePathSegment} codePathSegment The current code path segment to traverse - * @param {ASTNode} surroundingFunction The function node containing the code path segment - * @returns {void} - */ - function findOutdatedReads( - codePathSegment, - surroundingFunction, - { - stateBySegmentStart = new WeakMap(), - stateBySegmentEnd = new WeakMap() - } = {} - ) { - if (!stateBySegmentStart.has(codePathSegment)) { - stateBySegmentStart.set(codePathSegment, new AssignmentTrackerState()); - } - - const currentState = stateBySegmentStart.get(codePathSegment).copy(); - - expressionsByCodePathSegment.get(codePathSegment).forEach(({ entering, node }) => { - if (node.type === "AssignmentExpression") { - if (entering) { - currentState.enterAssignment(node); - } else { - currentState.exitAssignment(node); - } - } else if (!entering && (node.type === "AwaitExpression" || node.type === "YieldExpression")) { - currentState.exitAwaitOrYield(node, surroundingFunction); - } else if (!entering && (node.type === "Identifier" || node.type === "MemberExpression")) { - currentState.exitIdentifierOrMemberExpression(node); - } - }); - - stateBySegmentEnd.set(codePathSegment, currentState); - - codePathSegment.nextSegments.forEach(nextSegment => { - if (stateBySegmentStart.has(nextSegment)) { - if (!stateBySegmentStart.get(nextSegment).merge(currentState)) { - - /* - * This segment has already been processed with the given set of inputs; - * no need to do it again. After no new state is available to process - * for any control flow segment in the graph, the analysis reaches a fixpoint and - * traversal stops. - */ - return; - } - } else { - stateBySegmentStart.set(nextSegment, currentState.copy()); - } - findOutdatedReads( - nextSegment, - surroundingFunction, - { stateBySegmentStart, stateBySegmentEnd } - ); - }); - } - - //---------------------------------------------------------------------- - // Public - //---------------------------------------------------------------------- - - const currentCodePathSegmentStack = []; - let currentCodePathSegment = null; - const functionStack = []; - - return { - onCodePathStart() { - currentCodePathSegmentStack.push(currentCodePathSegment); - }, - - onCodePathEnd(codePath, node) { - currentCodePathSegment = currentCodePathSegmentStack.pop(); - - if (astUtils.isFunction(node) && (node.async || node.generator)) { - findOutdatedReads(codePath.initialSegment, node); - } - }, - - onCodePathSegmentStart(segment) { - currentCodePathSegment = segment; - expressionsByCodePathSegment.set(segment, []); - }, - - "AssignmentExpression, Identifier, MemberExpression, AwaitExpression, YieldExpression"(node) { - expressionsByCodePathSegment.get(currentCodePathSegment).push({ entering: true, node }); - }, - - "AssignmentExpression, Identifier, MemberExpression, AwaitExpression, YieldExpression:exit"(node) { - expressionsByCodePathSegment.get(currentCodePathSegment).push({ entering: false, node }); - }, - - ":function"(node) { - functionStack.push(node); - }, - - ":function:exit"() { - functionStack.pop(); - }, - - Identifier(node) { - if (functionStack.length) { - identifierToSurroundingFunctionMap.set(node, functionStack[functionStack.length - 1]); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/require-await.js b/tools/node_modules/eslint/lib/rules/require-await.js deleted file mode 100644 index 5e614c50251fed..00000000000000 --- a/tools/node_modules/eslint/lib/rules/require-await.js +++ /dev/null @@ -1,104 +0,0 @@ -/** - * @fileoverview Rule to disallow async functions which have no `await` expression. - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/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: { - type: "suggestion", - - docs: { - description: "disallow async functions which have no `await` expression", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/require-await" - }, - - 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; - }, - ForOfStatement(node) { - if (node.await) { - scopeInfo.hasAwait = true; - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/require-jsdoc.js b/tools/node_modules/eslint/lib/rules/require-jsdoc.js deleted file mode 100644 index 416a22ce6c4375..00000000000000 --- a/tools/node_modules/eslint/lib/rules/require-jsdoc.js +++ /dev/null @@ -1,117 +0,0 @@ -/** - * @fileoverview Rule to check for jsdoc presence. - * @author Gyandeep Singh - */ -"use strict"; - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require JSDoc comments", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/require-jsdoc" - }, - - schema: [ - { - type: "object", - properties: { - require: { - type: "object", - properties: { - ClassDeclaration: { - type: "boolean", - default: false - }, - MethodDefinition: { - type: "boolean", - default: false - }, - FunctionDeclaration: { - type: "boolean", - default: true - }, - ArrowFunctionExpression: { - type: "boolean", - default: false - }, - FunctionExpression: { - type: "boolean", - default: false - } - }, - additionalProperties: false, - default: {} - } - }, - additionalProperties: false - } - ], - - deprecated: true, - replacedBy: [] - }, - - create(context) { - const source = context.getSourceCode(); - const DEFAULT_OPTIONS = { - FunctionDeclaration: true, - MethodDefinition: false, - ClassDeclaration: false, - ArrowFunctionExpression: false, - FunctionExpression: false - }; - const options = Object.assign(DEFAULT_OPTIONS, context.options[0] && context.options[0].require); - - /** - * Report the error message - * @param {ASTNode} node node to report - * @returns {void} - */ - function report(node) { - context.report({ node, message: "Missing JSDoc comment." }); - } - - /** - * Check if the jsdoc comment is present or not. - * @param {ASTNode} node node to examine - * @returns {void} - */ - function checkJsDoc(node) { - const jsdocComment = source.getJSDocComment(node); - - if (!jsdocComment) { - report(node); - } - } - - return { - FunctionDeclaration(node) { - if (options.FunctionDeclaration) { - checkJsDoc(node); - } - }, - FunctionExpression(node) { - if ( - (options.MethodDefinition && node.parent.type === "MethodDefinition") || - (options.FunctionExpression && (node.parent.type === "VariableDeclarator" || (node.parent.type === "Property" && node === node.parent.value))) - ) { - checkJsDoc(node); - } - }, - ClassDeclaration(node) { - if (options.ClassDeclaration) { - checkJsDoc(node); - } - }, - ArrowFunctionExpression(node) { - if (options.ArrowFunctionExpression && node.parent.type === "VariableDeclarator") { - checkJsDoc(node); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/require-unicode-regexp.js b/tools/node_modules/eslint/lib/rules/require-unicode-regexp.js deleted file mode 100644 index 880405e9a25dbf..00000000000000 --- a/tools/node_modules/eslint/lib/rules/require-unicode-regexp.js +++ /dev/null @@ -1,69 +0,0 @@ -/** - * @fileoverview Rule to enforce the use of `u` flag on RegExp. - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const { - CALL, - CONSTRUCT, - ReferenceTracker, - getStringIfConstant -} = require("eslint-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce the use of `u` flag on RegExp", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/require-unicode-regexp" - }, - - messages: { - requireUFlag: "Use the 'u' flag." - }, - - schema: [] - }, - - create(context) { - return { - "Literal[regex]"(node) { - const flags = node.regex.flags || ""; - - if (!flags.includes("u")) { - context.report({ node, messageId: "requireUFlag" }); - } - }, - - Program() { - const scope = context.getScope(); - const tracker = new ReferenceTracker(scope); - const trackMap = { - RegExp: { [CALL]: true, [CONSTRUCT]: true } - }; - - for (const { node } of tracker.iterateGlobalReferences(trackMap)) { - const flagsNode = node.arguments[1]; - const flags = getStringIfConstant(flagsNode, scope); - - if (!flagsNode || (typeof flags === "string" && !flags.includes("u"))) { - context.report({ node, messageId: "requireUFlag" }); - } - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/require-yield.js b/tools/node_modules/eslint/lib/rules/require-yield.js deleted file mode 100644 index 7bb7cf9a872bd8..00000000000000 --- a/tools/node_modules/eslint/lib/rules/require-yield.js +++ /dev/null @@ -1,74 +0,0 @@ -/** - * @fileoverview Rule to flag the generator functions that does not have yield. - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require generator functions to contain `yield`", - category: "ECMAScript 6", - recommended: true, - url: "https://eslint.org/docs/rules/require-yield" - }, - - schema: [] - }, - - create(context) { - const stack = []; - - /** - * If the node is a generator function, start counting `yield` keywords. - * @param {Node} node - A function node to check. - * @returns {void} - */ - function beginChecking(node) { - if (node.generator) { - stack.push(0); - } - } - - /** - * If the node is a generator function, end counting `yield` keywords, then - * reports result. - * @param {Node} node - A function node to check. - * @returns {void} - */ - function endChecking(node) { - if (!node.generator) { - return; - } - - const countYield = stack.pop(); - - if (countYield === 0 && node.body.body.length > 0) { - context.report({ node, message: "This generator function does not have 'yield'." }); - } - } - - return { - FunctionDeclaration: beginChecking, - "FunctionDeclaration:exit": endChecking, - FunctionExpression: beginChecking, - "FunctionExpression:exit": endChecking, - - // Increases the count of `yield` keyword. - YieldExpression() { - - /* istanbul ignore else */ - if (stack.length > 0) { - stack[stack.length - 1] += 1; - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/rest-spread-spacing.js b/tools/node_modules/eslint/lib/rules/rest-spread-spacing.js deleted file mode 100644 index 04539395ef4ec1..00000000000000 --- a/tools/node_modules/eslint/lib/rules/rest-spread-spacing.js +++ /dev/null @@ -1,118 +0,0 @@ -/** - * @fileoverview Enforce spacing between rest and spread operators and their expressions. - * @author Kai Cataldo - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce spacing between rest and spread operators and their expressions", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/rest-spread-spacing" - }, - - fixable: "whitespace", - - schema: [ - { - enum: ["always", "never"] - } - ] - }, - - create(context) { - const sourceCode = context.getSourceCode(), - alwaysSpace = context.options[0] === "always"; - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Checks whitespace between rest/spread operators and their expressions - * @param {ASTNode} node - The node to check - * @returns {void} - */ - function checkWhiteSpace(node) { - const operator = sourceCode.getFirstToken(node), - nextToken = sourceCode.getTokenAfter(operator), - hasWhitespace = sourceCode.isSpaceBetweenTokens(operator, nextToken); - let type; - - switch (node.type) { - case "SpreadElement": - type = "spread"; - if (node.parent.type === "ObjectExpression") { - type += " property"; - } - break; - case "RestElement": - type = "rest"; - if (node.parent.type === "ObjectPattern") { - type += " property"; - } - break; - case "ExperimentalSpreadProperty": - type = "spread property"; - break; - case "ExperimentalRestProperty": - type = "rest property"; - break; - default: - return; - } - - if (alwaysSpace && !hasWhitespace) { - context.report({ - node, - loc: { - line: operator.loc.end.line, - column: operator.loc.end.column - }, - message: "Expected whitespace after {{type}} operator.", - data: { - type - }, - fix(fixer) { - return fixer.replaceTextRange([operator.range[1], nextToken.range[0]], " "); - } - }); - } else if (!alwaysSpace && hasWhitespace) { - context.report({ - node, - loc: { - line: operator.loc.end.line, - column: operator.loc.end.column - }, - message: "Unexpected whitespace after {{type}} operator.", - data: { - type - }, - fix(fixer) { - return fixer.removeRange([operator.range[1], nextToken.range[0]]); - } - }); - } - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - SpreadElement: checkWhiteSpace, - RestElement: checkWhiteSpace, - ExperimentalSpreadProperty: checkWhiteSpace, - ExperimentalRestProperty: checkWhiteSpace - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/semi-spacing.js b/tools/node_modules/eslint/lib/rules/semi-spacing.js deleted file mode 100644 index 3a6d8a052a343b..00000000000000 --- a/tools/node_modules/eslint/lib/rules/semi-spacing.js +++ /dev/null @@ -1,212 +0,0 @@ -/** - * @fileoverview Validates spacing before and after semicolon - * @author Mathias Schreck - */ - -"use strict"; - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce consistent spacing before and after semicolons", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/semi-spacing" - }, - - fixable: "whitespace", - - schema: [ - { - type: "object", - properties: { - before: { - type: "boolean", - default: false - }, - after: { - type: "boolean", - default: true - } - }, - additionalProperties: false - } - ] - }, - - create(context) { - - const config = context.options[0], - sourceCode = context.getSourceCode(); - let requireSpaceBefore = false, - requireSpaceAfter = true; - - if (typeof config === "object") { - requireSpaceBefore = config.before; - requireSpaceAfter = config.after; - } - - /** - * Checks if a given token has leading whitespace. - * @param {Object} token The token to check. - * @returns {boolean} True if the given token has leading space, false if not. - */ - function hasLeadingSpace(token) { - const tokenBefore = sourceCode.getTokenBefore(token); - - return tokenBefore && astUtils.isTokenOnSameLine(tokenBefore, token) && sourceCode.isSpaceBetweenTokens(tokenBefore, token); - } - - /** - * Checks if a given token has trailing whitespace. - * @param {Object} token The token to check. - * @returns {boolean} True if the given token has trailing space, false if not. - */ - function hasTrailingSpace(token) { - const tokenAfter = sourceCode.getTokenAfter(token); - - return tokenAfter && astUtils.isTokenOnSameLine(token, tokenAfter) && sourceCode.isSpaceBetweenTokens(token, tokenAfter); - } - - /** - * Checks if the given token is the last token in its line. - * @param {Token} token The token to check. - * @returns {boolean} Whether or not the token is the last in its line. - */ - function isLastTokenInCurrentLine(token) { - const tokenAfter = sourceCode.getTokenAfter(token); - - return !(tokenAfter && astUtils.isTokenOnSameLine(token, tokenAfter)); - } - - /** - * Checks if the given token is the first token in its line - * @param {Token} token The token to check. - * @returns {boolean} Whether or not the token is the first in its line. - */ - function isFirstTokenInCurrentLine(token) { - const tokenBefore = sourceCode.getTokenBefore(token); - - return !(tokenBefore && astUtils.isTokenOnSameLine(token, tokenBefore)); - } - - /** - * Checks if the next token of a given token is a closing parenthesis. - * @param {Token} token The token to check. - * @returns {boolean} Whether or not the next token of a given token is a closing parenthesis. - */ - function isBeforeClosingParen(token) { - const nextToken = sourceCode.getTokenAfter(token); - - return (nextToken && astUtils.isClosingBraceToken(nextToken) || astUtils.isClosingParenToken(nextToken)); - } - - /** - * Reports if the given token has invalid spacing. - * @param {Token} token The semicolon token to check. - * @param {ASTNode} node The corresponding node of the token. - * @returns {void} - */ - function checkSemicolonSpacing(token, node) { - if (astUtils.isSemicolonToken(token)) { - const location = token.loc.start; - - if (hasLeadingSpace(token)) { - if (!requireSpaceBefore) { - context.report({ - node, - loc: location, - message: "Unexpected whitespace before semicolon.", - fix(fixer) { - const tokenBefore = sourceCode.getTokenBefore(token); - - return fixer.removeRange([tokenBefore.range[1], token.range[0]]); - } - }); - } - } else { - if (requireSpaceBefore) { - context.report({ - node, - loc: location, - message: "Missing whitespace before semicolon.", - fix(fixer) { - return fixer.insertTextBefore(token, " "); - } - }); - } - } - - if (!isFirstTokenInCurrentLine(token) && !isLastTokenInCurrentLine(token) && !isBeforeClosingParen(token)) { - if (hasTrailingSpace(token)) { - if (!requireSpaceAfter) { - context.report({ - node, - loc: location, - message: "Unexpected whitespace after semicolon.", - fix(fixer) { - const tokenAfter = sourceCode.getTokenAfter(token); - - return fixer.removeRange([token.range[1], tokenAfter.range[0]]); - } - }); - } - } else { - if (requireSpaceAfter) { - context.report({ - node, - loc: location, - message: "Missing whitespace after semicolon.", - fix(fixer) { - return fixer.insertTextAfter(token, " "); - } - }); - } - } - } - } - } - - /** - * Checks the spacing of the semicolon with the assumption that the last token is the semicolon. - * @param {ASTNode} node The node to check. - * @returns {void} - */ - function checkNode(node) { - const token = sourceCode.getLastToken(node); - - checkSemicolonSpacing(token, node); - } - - return { - VariableDeclaration: checkNode, - ExpressionStatement: checkNode, - BreakStatement: checkNode, - ContinueStatement: checkNode, - DebuggerStatement: checkNode, - ReturnStatement: checkNode, - ThrowStatement: checkNode, - ImportDeclaration: checkNode, - ExportNamedDeclaration: checkNode, - ExportAllDeclaration: checkNode, - ExportDefaultDeclaration: checkNode, - ForStatement(node) { - if (node.init) { - checkSemicolonSpacing(sourceCode.getTokenAfter(node.init), node); - } - - if (node.test) { - checkSemicolonSpacing(sourceCode.getTokenAfter(node.test), node); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/semi-style.js b/tools/node_modules/eslint/lib/rules/semi-style.js deleted file mode 100644 index dd76b68f82beac..00000000000000 --- a/tools/node_modules/eslint/lib/rules/semi-style.js +++ /dev/null @@ -1,147 +0,0 @@ -/** - * @fileoverview Rule to enforce location of semicolons. - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -const SELECTOR = `:matches(${ - [ - "BreakStatement", "ContinueStatement", "DebuggerStatement", - "DoWhileStatement", "ExportAllDeclaration", - "ExportDefaultDeclaration", "ExportNamedDeclaration", - "ExpressionStatement", "ImportDeclaration", "ReturnStatement", - "ThrowStatement", "VariableDeclaration" - ].join(",") -})`; - -/** - * Get the child node list of a given node. - * This returns `Program#body`, `BlockStatement#body`, or `SwitchCase#consequent`. - * This is used to check whether a node is the first/last child. - * @param {Node} node A node to get child node list. - * @returns {Node[]|null} The child node list. - */ -function getChildren(node) { - const t = node.type; - - if (t === "BlockStatement" || t === "Program") { - return node.body; - } - if (t === "SwitchCase") { - return node.consequent; - } - return null; -} - -/** - * Check whether a given node is the last statement in the parent block. - * @param {Node} node A node to check. - * @returns {boolean} `true` if the node is the last statement in the parent block. - */ -function isLastChild(node) { - const t = node.parent.type; - - if (t === "IfStatement" && node.parent.consequent === node && node.parent.alternate) { // before `else` keyword. - return true; - } - if (t === "DoWhileStatement") { // before `while` keyword. - return true; - } - const nodeList = getChildren(node.parent); - - return nodeList !== null && nodeList[nodeList.length - 1] === node; // before `}` or etc. -} - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce location of semicolons", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/semi-style" - }, - - schema: [{ enum: ["last", "first"] }], - fixable: "whitespace" - }, - - create(context) { - const sourceCode = context.getSourceCode(); - const option = context.options[0] || "last"; - - /** - * Check the given semicolon token. - * @param {Token} semiToken The semicolon token to check. - * @param {"first"|"last"} expected The expected location to check. - * @returns {void} - */ - function check(semiToken, expected) { - const prevToken = sourceCode.getTokenBefore(semiToken); - const nextToken = sourceCode.getTokenAfter(semiToken); - const prevIsSameLine = !prevToken || astUtils.isTokenOnSameLine(prevToken, semiToken); - const nextIsSameLine = !nextToken || astUtils.isTokenOnSameLine(semiToken, nextToken); - - if ((expected === "last" && !prevIsSameLine) || (expected === "first" && !nextIsSameLine)) { - context.report({ - loc: semiToken.loc, - message: "Expected this semicolon to be at {{pos}}.", - data: { - pos: (expected === "last") - ? "the end of the previous line" - : "the beginning of the next line" - }, - fix(fixer) { - if (prevToken && nextToken && sourceCode.commentsExistBetween(prevToken, nextToken)) { - return null; - } - - const start = prevToken ? prevToken.range[1] : semiToken.range[0]; - const end = nextToken ? nextToken.range[0] : semiToken.range[1]; - const text = (expected === "last") ? ";\n" : "\n;"; - - return fixer.replaceTextRange([start, end], text); - } - }); - } - } - - return { - [SELECTOR](node) { - if (option === "first" && isLastChild(node)) { - return; - } - - const lastToken = sourceCode.getLastToken(node); - - if (astUtils.isSemicolonToken(lastToken)) { - check(lastToken, option); - } - }, - - ForStatement(node) { - const firstSemi = node.init && sourceCode.getTokenAfter(node.init, astUtils.isSemicolonToken); - const secondSemi = node.test && sourceCode.getTokenAfter(node.test, astUtils.isSemicolonToken); - - if (firstSemi) { - check(firstSemi, "last"); - } - if (secondSemi) { - check(secondSemi, "last"); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/semi.js b/tools/node_modules/eslint/lib/rules/semi.js deleted file mode 100644 index f7bc0f5fd66198..00000000000000 --- a/tools/node_modules/eslint/lib/rules/semi.js +++ /dev/null @@ -1,329 +0,0 @@ -/** - * @fileoverview Rule to flag missing semicolons. - * @author Nicholas C. Zakas - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const FixTracker = require("../util/fix-tracker"); -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "require or disallow semicolons instead of ASI", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/semi" - }, - - fixable: "code", - - schema: { - anyOf: [ - { - type: "array", - items: [ - { - enum: ["never"] - }, - { - type: "object", - properties: { - beforeStatementContinuationChars: { - enum: ["always", "any", "never"], - default: "any" - } - }, - additionalProperties: false - } - ], - minItems: 0, - maxItems: 2 - }, - { - type: "array", - items: [ - { - enum: ["always"] - }, - { - type: "object", - properties: { - omitLastInOneLineBlock: { type: "boolean", default: false } - }, - additionalProperties: false - } - ], - minItems: 0, - maxItems: 2 - } - ] - } - }, - - create(context) { - - const OPT_OUT_PATTERN = /^[-[(/+`]/; // One of [(/+-` - const options = context.options[1]; - const never = context.options[0] === "never"; - const exceptOneLine = options && options.omitLastInOneLineBlock; - const beforeStatementContinuationChars = options && options.beforeStatementContinuationChars; - const sourceCode = context.getSourceCode(); - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Reports a semicolon error with appropriate location and message. - * @param {ASTNode} node The node with an extra or missing semicolon. - * @param {boolean} missing True if the semicolon is missing. - * @returns {void} - */ - function report(node, missing) { - const lastToken = sourceCode.getLastToken(node); - let message, - fix, - loc = lastToken.loc; - - if (!missing) { - message = "Missing semicolon."; - loc = loc.end; - fix = function(fixer) { - return fixer.insertTextAfter(lastToken, ";"); - }; - } else { - message = "Extra semicolon."; - loc = loc.start; - fix = function(fixer) { - - /* - * Expand the replacement range to include the surrounding - * tokens to avoid conflicting with no-extra-semi. - * https://github.com/eslint/eslint/issues/7928 - */ - return new FixTracker(fixer, sourceCode) - .retainSurroundingTokens(lastToken) - .remove(lastToken); - }; - } - - context.report({ - node, - loc, - message, - fix - }); - - } - - /** - * Check whether a given semicolon token is redandant. - * @param {Token} semiToken A semicolon token to check. - * @returns {boolean} `true` if the next token is `;` or `}`. - */ - function isRedundantSemi(semiToken) { - const nextToken = sourceCode.getTokenAfter(semiToken); - - return ( - !nextToken || - astUtils.isClosingBraceToken(nextToken) || - astUtils.isSemicolonToken(nextToken) - ); - } - - /** - * Check whether a given token is the closing brace of an arrow function. - * @param {Token} lastToken A token to check. - * @returns {boolean} `true` if the token is the closing brace of an arrow function. - */ - function isEndOfArrowBlock(lastToken) { - if (!astUtils.isClosingBraceToken(lastToken)) { - return false; - } - const node = sourceCode.getNodeByRangeIndex(lastToken.range[0]); - - return ( - node.type === "BlockStatement" && - node.parent.type === "ArrowFunctionExpression" - ); - } - - /** - * Check whether a given node is on the same line with the next token. - * @param {Node} node A statement node to check. - * @returns {boolean} `true` if the node is on the same line with the next token. - */ - function isOnSameLineWithNextToken(node) { - const prevToken = sourceCode.getLastToken(node, 1); - const nextToken = sourceCode.getTokenAfter(node); - - return !!nextToken && astUtils.isTokenOnSameLine(prevToken, nextToken); - } - - /** - * Check whether a given node can connect the next line if the next line is unreliable. - * @param {Node} node A statement node to check. - * @returns {boolean} `true` if the node can connect the next line. - */ - function maybeAsiHazardAfter(node) { - const t = node.type; - - if (t === "DoWhileStatement" || - t === "BreakStatement" || - t === "ContinueStatement" || - t === "DebuggerStatement" || - t === "ImportDeclaration" || - t === "ExportAllDeclaration" - ) { - return false; - } - if (t === "ReturnStatement") { - return Boolean(node.argument); - } - if (t === "ExportNamedDeclaration") { - return Boolean(node.declaration); - } - if (isEndOfArrowBlock(sourceCode.getLastToken(node, 1))) { - return false; - } - - return true; - } - - /** - * Check whether a given token can connect the previous statement. - * @param {Token} token A token to check. - * @returns {boolean} `true` if the token is one of `[`, `(`, `/`, `+`, `-`, ```, `++`, and `--`. - */ - function maybeAsiHazardBefore(token) { - return ( - Boolean(token) && - OPT_OUT_PATTERN.test(token.value) && - token.value !== "++" && - token.value !== "--" - ); - } - - /** - * Check if the semicolon of a given node is unnecessary, only true if: - * - next token is a valid statement divider (`;` or `}`). - * - next token is on a new line and the node is not connectable to the new line. - * @param {Node} node A statement node to check. - * @returns {boolean} whether the semicolon is unnecessary. - */ - function canRemoveSemicolon(node) { - if (isRedundantSemi(sourceCode.getLastToken(node))) { - return true; // `;;` or `;}` - } - if (isOnSameLineWithNextToken(node)) { - return false; // One liner. - } - if (beforeStatementContinuationChars === "never" && !maybeAsiHazardAfter(node)) { - return true; // ASI works. This statement doesn't connect to the next. - } - if (!maybeAsiHazardBefore(sourceCode.getTokenAfter(node))) { - return true; // ASI works. The next token doesn't connect to this statement. - } - - return false; - } - - /** - * Checks a node to see if it's in a one-liner block statement. - * @param {ASTNode} node The node to check. - * @returns {boolean} whether the node is in a one-liner block statement. - */ - function isOneLinerBlock(node) { - const parent = node.parent; - const nextToken = sourceCode.getTokenAfter(node); - - if (!nextToken || nextToken.value !== "}") { - return false; - } - return ( - !!parent && - parent.type === "BlockStatement" && - parent.loc.start.line === parent.loc.end.line - ); - } - - /** - * Checks a node to see if it's followed by a semicolon. - * @param {ASTNode} node The node to check. - * @returns {void} - */ - function checkForSemicolon(node) { - const isSemi = astUtils.isSemicolonToken(sourceCode.getLastToken(node)); - - if (never) { - if (isSemi && canRemoveSemicolon(node)) { - report(node, true); - } else if (!isSemi && beforeStatementContinuationChars === "always" && maybeAsiHazardBefore(sourceCode.getTokenAfter(node))) { - report(node); - } - } else { - const oneLinerBlock = (exceptOneLine && isOneLinerBlock(node)); - - if (isSemi && oneLinerBlock) { - report(node, true); - } else if (!isSemi && !oneLinerBlock) { - report(node); - } - } - } - - /** - * Checks to see if there's a semicolon after a variable declaration. - * @param {ASTNode} node The node to check. - * @returns {void} - */ - function checkForSemicolonForVariableDeclaration(node) { - const parent = node.parent; - - if ((parent.type !== "ForStatement" || parent.init !== node) && - (!/^For(?:In|Of)Statement/.test(parent.type) || parent.left !== node) - ) { - checkForSemicolon(node); - } - } - - //-------------------------------------------------------------------------- - // Public API - //-------------------------------------------------------------------------- - - return { - VariableDeclaration: checkForSemicolonForVariableDeclaration, - ExpressionStatement: checkForSemicolon, - ReturnStatement: checkForSemicolon, - ThrowStatement: checkForSemicolon, - DoWhileStatement: checkForSemicolon, - DebuggerStatement: checkForSemicolon, - BreakStatement: checkForSemicolon, - ContinueStatement: checkForSemicolon, - ImportDeclaration: checkForSemicolon, - ExportAllDeclaration: checkForSemicolon, - ExportNamedDeclaration(node) { - if (!node.declaration) { - checkForSemicolon(node); - } - }, - ExportDefaultDeclaration(node) { - if (!/(?:Class|Function)Declaration/.test(node.declaration.type)) { - checkForSemicolon(node); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/sort-imports.js b/tools/node_modules/eslint/lib/rules/sort-imports.js deleted file mode 100644 index 05e643ca0611d5..00000000000000 --- a/tools/node_modules/eslint/lib/rules/sort-imports.js +++ /dev/null @@ -1,208 +0,0 @@ -/** - * @fileoverview Rule to require sorting of import declarations - * @author Christian Schuller - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce sorted import declarations within modules", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/sort-imports" - }, - - schema: [ - { - type: "object", - properties: { - ignoreCase: { - type: "boolean", - default: false - }, - memberSyntaxSortOrder: { - type: "array", - items: { - enum: ["none", "all", "multiple", "single"] - }, - uniqueItems: true, - minItems: 4, - maxItems: 4 - }, - ignoreDeclarationSort: { - type: "boolean", - default: false - }, - ignoreMemberSort: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - - fixable: "code" - }, - - create(context) { - - const configuration = context.options[0] || {}, - ignoreCase = configuration.ignoreCase || false, - ignoreDeclarationSort = configuration.ignoreDeclarationSort || false, - ignoreMemberSort = configuration.ignoreMemberSort || false, - memberSyntaxSortOrder = configuration.memberSyntaxSortOrder || ["none", "all", "multiple", "single"], - sourceCode = context.getSourceCode(); - let previousDeclaration = null; - - /** - * Gets the used member syntax style. - * - * import "my-module.js" --> none - * import * as myModule from "my-module.js" --> all - * import {myMember} from "my-module.js" --> single - * import {foo, bar} from "my-module.js" --> multiple - * - * @param {ASTNode} node - the ImportDeclaration node. - * @returns {string} used member parameter style, ["all", "multiple", "single"] - */ - function usedMemberSyntax(node) { - if (node.specifiers.length === 0) { - return "none"; - } - if (node.specifiers[0].type === "ImportNamespaceSpecifier") { - return "all"; - } - if (node.specifiers.length === 1) { - return "single"; - } - return "multiple"; - - } - - /** - * Gets the group by member parameter index for given declaration. - * @param {ASTNode} node - the ImportDeclaration node. - * @returns {number} the declaration group by member index. - */ - function getMemberParameterGroupIndex(node) { - return memberSyntaxSortOrder.indexOf(usedMemberSyntax(node)); - } - - /** - * Gets the local name of the first imported module. - * @param {ASTNode} node - the ImportDeclaration node. - * @returns {?string} the local name of the first imported module. - */ - function getFirstLocalMemberName(node) { - if (node.specifiers[0]) { - return node.specifiers[0].local.name; - } - return null; - - } - - return { - ImportDeclaration(node) { - if (!ignoreDeclarationSort) { - if (previousDeclaration) { - const currentMemberSyntaxGroupIndex = getMemberParameterGroupIndex(node), - previousMemberSyntaxGroupIndex = getMemberParameterGroupIndex(previousDeclaration); - let currentLocalMemberName = getFirstLocalMemberName(node), - previousLocalMemberName = getFirstLocalMemberName(previousDeclaration); - - if (ignoreCase) { - previousLocalMemberName = previousLocalMemberName && previousLocalMemberName.toLowerCase(); - currentLocalMemberName = currentLocalMemberName && currentLocalMemberName.toLowerCase(); - } - - /* - * When the current declaration uses a different member syntax, - * then check if the ordering is correct. - * Otherwise, make a default string compare (like rule sort-vars to be consistent) of the first used local member name. - */ - if (currentMemberSyntaxGroupIndex !== previousMemberSyntaxGroupIndex) { - if (currentMemberSyntaxGroupIndex < previousMemberSyntaxGroupIndex) { - context.report({ - node, - message: "Expected '{{syntaxA}}' syntax before '{{syntaxB}}' syntax.", - data: { - syntaxA: memberSyntaxSortOrder[currentMemberSyntaxGroupIndex], - syntaxB: memberSyntaxSortOrder[previousMemberSyntaxGroupIndex] - } - }); - } - } else { - if (previousLocalMemberName && - currentLocalMemberName && - currentLocalMemberName < previousLocalMemberName - ) { - context.report({ - node, - message: "Imports should be sorted alphabetically." - }); - } - } - } - - previousDeclaration = node; - } - - 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.getCommentsBefore(specifier).length || sourceCode.getCommentsAfter(specifier).length)) { - - // If there are comments in the ImportSpecifier list, don't rearrange the specifiers. - return null; - } - - return fixer.replaceTextRange( - [importSpecifiers[0].range[0], importSpecifiers[importSpecifiers.length - 1].range[1]], - importSpecifiers - - // Clone the importSpecifiers array to avoid mutating it - .slice() - - // Sort the array into the desired order - .sort((specifierA, specifierB) => { - const aName = getSortableName(specifierA); - const bName = getSortableName(specifierB); - - return aName > bName ? 1 : -1; - }) - - // 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]); - - return sourceText + sourceCode.getText(specifier) + textAfterSpecifier; - }, "") - ); - } - }); - } - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/sort-keys.js b/tools/node_modules/eslint/lib/rules/sort-keys.js deleted file mode 100644 index 08bfcdf3d8335b..00000000000000 --- a/tools/node_modules/eslint/lib/rules/sort-keys.js +++ /dev/null @@ -1,167 +0,0 @@ -/** - * @fileoverview Rule to require object keys to be sorted - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"), - naturalCompare = require("natural-compare"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Gets the property name of the given `Property` node. - * - * - If the property's key is an `Identifier` node, this returns the key's name - * whether it's a computed property or not. - * - If the property has a static name, this returns the static name. - * - Otherwise, this returns null. - * - * @param {ASTNode} node - The `Property` node to get. - * @returns {string|null} The property name or null. - * @private - */ -function getPropertyName(node) { - return astUtils.getStaticPropertyName(node) || node.key.name || null; -} - -/** - * Functions which check that the given 2 names are in specific order. - * - * Postfix `I` is meant insensitive. - * Postfix `N` is meant natual. - * - * @private - */ -const isValidOrders = { - asc(a, b) { - return a <= b; - }, - ascI(a, b) { - return a.toLowerCase() <= b.toLowerCase(); - }, - ascN(a, b) { - return naturalCompare(a, b) <= 0; - }, - ascIN(a, b) { - return naturalCompare(a.toLowerCase(), b.toLowerCase()) <= 0; - }, - desc(a, b) { - return isValidOrders.asc(b, a); - }, - descI(a, b) { - return isValidOrders.ascI(b, a); - }, - descN(a, b) { - return isValidOrders.ascN(b, a); - }, - descIN(a, b) { - return isValidOrders.ascIN(b, a); - } -}; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require object keys to be sorted", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/sort-keys" - }, - - schema: [ - { - enum: ["asc", "desc"] - }, - { - type: "object", - properties: { - caseSensitive: { - type: "boolean", - default: true - }, - natural: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ] - }, - - create(context) { - - // Parse options. - const order = context.options[0] || "asc"; - const options = context.options[1]; - const insensitive = options && options.caseSensitive === false; - const natual = options && options.natural; - const isValidOrder = isValidOrders[ - order + (insensitive ? "I" : "") + (natual ? "N" : "") - ]; - - // The stack to save the previous property's name for each object literals. - let stack = null; - - return { - ObjectExpression() { - stack = { - upper: stack, - prevName: null - }; - }, - - "ObjectExpression:exit"() { - stack = stack.upper; - }, - - SpreadElement() { - stack.prevName = null; - }, - - Property(node) { - if (node.parent.type === "ObjectPattern") { - return; - } - - const prevName = stack.prevName; - const thisName = getPropertyName(node); - - stack.prevName = thisName || prevName; - - if (!prevName || !thisName) { - return; - } - - if (!isValidOrder(prevName, thisName)) { - context.report({ - node, - loc: node.key.loc, - message: "Expected object keys to be in {{natual}}{{insensitive}}{{order}}ending order. '{{thisName}}' should be before '{{prevName}}'.", - data: { - thisName, - prevName, - order, - insensitive: insensitive ? "insensitive " : "", - natual: natual ? "natural " : "" - } - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/sort-vars.js b/tools/node_modules/eslint/lib/rules/sort-vars.js deleted file mode 100644 index e85c6534e3a189..00000000000000 --- a/tools/node_modules/eslint/lib/rules/sort-vars.js +++ /dev/null @@ -1,100 +0,0 @@ -/** - * @fileoverview Rule to require sorting of variables within a single Variable Declaration block - * @author Ilya Volodin - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require variables within the same declaration block to be sorted", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/sort-vars" - }, - - schema: [ - { - type: "object", - properties: { - ignoreCase: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - - fixable: "code" - }, - - create(context) { - - const configuration = context.options[0] || {}, - ignoreCase = configuration.ignoreCase || false, - sourceCode = context.getSourceCode(); - - return { - VariableDeclaration(node) { - const idDeclarations = node.declarations.filter(decl => decl.id.type === "Identifier"); - const getSortableName = ignoreCase ? decl => decl.id.name.toLowerCase() : decl => decl.id.name; - const unfixable = idDeclarations.some(decl => decl.init !== null && decl.init.type !== "Literal"); - let fixed = false; - - idDeclarations.slice(1).reduce((memo, decl) => { - const lastVariableName = getSortableName(memo), - currentVariableName = getSortableName(decl); - - if (currentVariableName < lastVariableName) { - context.report({ - node: decl, - message: "Variables within the same declaration block should be sorted alphabetically.", - fix(fixer) { - if (unfixable || fixed) { - return null; - } - return fixer.replaceTextRange( - [idDeclarations[0].range[0], idDeclarations[idDeclarations.length - 1].range[1]], - idDeclarations - - // Clone the idDeclarations array to avoid mutating it - .slice() - - // Sort the array into the desired order - .sort((declA, declB) => { - const aName = getSortableName(declA); - const bName = getSortableName(declB); - - return aName > bName ? 1 : -1; - }) - - // Build a string out of the sorted list of identifier declarations and the text between the originals - .reduce((sourceText, identifier, index) => { - const textAfterIdentifier = index === idDeclarations.length - 1 - ? "" - : sourceCode.getText().slice(idDeclarations[index].range[1], idDeclarations[index + 1].range[0]); - - return sourceText + sourceCode.getText(identifier) + textAfterIdentifier; - }, "") - - ); - } - }); - fixed = true; - return memo; - } - return decl; - - }, idDeclarations[0]); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/space-before-blocks.js b/tools/node_modules/eslint/lib/rules/space-before-blocks.js deleted file mode 100644 index 872338effc29b3..00000000000000 --- a/tools/node_modules/eslint/lib/rules/space-before-blocks.js +++ /dev/null @@ -1,160 +0,0 @@ -/** - * @fileoverview A rule to ensure whitespace before blocks. - * @author Mathias Schreck - */ - -"use strict"; - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce consistent spacing before blocks", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/space-before-blocks" - }, - - fixable: "whitespace", - - schema: [ - { - oneOf: [ - { - enum: ["always", "never"] - }, - { - type: "object", - properties: { - keywords: { - enum: ["always", "never", "off"] - }, - functions: { - enum: ["always", "never", "off"] - }, - classes: { - enum: ["always", "never", "off"] - } - }, - additionalProperties: false - } - ] - } - ] - }, - - create(context) { - const config = context.options[0], - sourceCode = context.getSourceCode(); - let alwaysFunctions = true, - alwaysKeywords = true, - alwaysClasses = true, - neverFunctions = false, - neverKeywords = false, - neverClasses = false; - - if (typeof config === "object") { - alwaysFunctions = config.functions === "always"; - alwaysKeywords = config.keywords === "always"; - alwaysClasses = config.classes === "always"; - neverFunctions = config.functions === "never"; - neverKeywords = config.keywords === "never"; - neverClasses = config.classes === "never"; - } else if (config === "never") { - alwaysFunctions = false; - alwaysKeywords = false; - alwaysClasses = false; - neverFunctions = true; - neverKeywords = true; - neverClasses = true; - } - - /** - * Checks whether or not a given token is an arrow operator (=>) or a keyword - * in order to avoid to conflict with `arrow-spacing` and `keyword-spacing`. - * - * @param {Token} token - A token to check. - * @returns {boolean} `true` if the token is an arrow operator. - */ - function isConflicted(token) { - return (token.type === "Punctuator" && token.value === "=>") || token.type === "Keyword"; - } - - /** - * Checks the given BlockStatement node has a preceding space if it doesn’t start on a new line. - * @param {ASTNode|Token} node The AST node of a BlockStatement. - * @returns {void} undefined. - */ - function checkPrecedingSpace(node) { - const precedingToken = sourceCode.getTokenBefore(node); - - if (precedingToken && !isConflicted(precedingToken) && astUtils.isTokenOnSameLine(precedingToken, node)) { - const hasSpace = sourceCode.isSpaceBetweenTokens(precedingToken, node); - const parent = context.getAncestors().pop(); - let requireSpace; - let requireNoSpace; - - if (parent.type === "FunctionExpression" || parent.type === "FunctionDeclaration") { - requireSpace = alwaysFunctions; - requireNoSpace = neverFunctions; - } else if (node.type === "ClassBody") { - requireSpace = alwaysClasses; - requireNoSpace = neverClasses; - } else { - requireSpace = alwaysKeywords; - requireNoSpace = neverKeywords; - } - - if (requireSpace && !hasSpace) { - context.report({ - node, - message: "Missing space before opening brace.", - fix(fixer) { - return fixer.insertTextBefore(node, " "); - } - }); - } else if (requireNoSpace && hasSpace) { - context.report({ - node, - message: "Unexpected space before opening brace.", - fix(fixer) { - return fixer.removeRange([precedingToken.range[1], node.range[0]]); - } - }); - } - } - } - - /** - * Checks if the CaseBlock of an given SwitchStatement node has a preceding space. - * @param {ASTNode} node The node of a SwitchStatement. - * @returns {void} undefined. - */ - function checkSpaceBeforeCaseBlock(node) { - const cases = node.cases; - let openingBrace; - - if (cases.length > 0) { - openingBrace = sourceCode.getTokenBefore(cases[0]); - } else { - openingBrace = sourceCode.getLastToken(node, 1); - } - - checkPrecedingSpace(openingBrace); - } - - return { - BlockStatement: checkPrecedingSpace, - ClassBody: checkPrecedingSpace, - SwitchStatement: checkSpaceBeforeCaseBlock - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/space-before-function-paren.js b/tools/node_modules/eslint/lib/rules/space-before-function-paren.js deleted file mode 100644 index c0d8e509fddd63..00000000000000 --- a/tools/node_modules/eslint/lib/rules/space-before-function-paren.js +++ /dev/null @@ -1,148 +0,0 @@ -/** - * @fileoverview Rule to validate spacing before function paren. - * @author Mathias Schreck - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce consistent spacing before `function` definition opening parenthesis", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/space-before-function-paren" - }, - - fixable: "whitespace", - - schema: [ - { - oneOf: [ - { - enum: ["always", "never"] - }, - { - type: "object", - properties: { - anonymous: { - enum: ["always", "never", "ignore"], - default: "always" - }, - named: { - enum: ["always", "never", "ignore"], - default: "always" - }, - asyncArrow: { - enum: ["always", "never", "ignore"], - default: "always" - } - }, - additionalProperties: false - } - ] - } - ] - }, - - create(context) { - const sourceCode = context.getSourceCode(); - const baseConfig = typeof context.options[0] === "string" ? context.options[0] : "always"; - const overrideConfig = typeof context.options[0] === "object" ? context.options[0] : {}; - - /** - * Determines whether a function has a name. - * @param {ASTNode} node The function node. - * @returns {boolean} Whether the function has a name. - */ - function isNamedFunction(node) { - if (node.id) { - return true; - } - - const parent = node.parent; - - return parent.type === "MethodDefinition" || - (parent.type === "Property" && - ( - parent.kind === "get" || - parent.kind === "set" || - parent.method - ) - ); - } - - /** - * Gets the config for a given function - * @param {ASTNode} node The function node - * @returns {string} "always", "never", or "ignore" - */ - function getConfigForFunction(node) { - if (node.type === "ArrowFunctionExpression") { - - // Always ignore non-async functions and arrow functions without parens, e.g. async foo => bar - if (node.async && astUtils.isOpeningParenToken(sourceCode.getFirstToken(node, { skip: 1 }))) { - return overrideConfig.asyncArrow || baseConfig; - } - } else if (isNamedFunction(node)) { - return overrideConfig.named || baseConfig; - - // `generator-star-spacing` should warn anonymous generators. E.g. `function* () {}` - } else if (!node.generator) { - return overrideConfig.anonymous || baseConfig; - } - - return "ignore"; - } - - /** - * Checks the parens of a function node - * @param {ASTNode} node A function node - * @returns {void} - */ - function checkFunction(node) { - const functionConfig = getConfigForFunction(node); - - if (functionConfig === "ignore") { - return; - } - - const rightToken = sourceCode.getFirstToken(node, astUtils.isOpeningParenToken); - const leftToken = sourceCode.getTokenBefore(rightToken); - const hasSpacing = sourceCode.isSpaceBetweenTokens(leftToken, rightToken); - - if (hasSpacing && functionConfig === "never") { - context.report({ - node, - loc: leftToken.loc.end, - message: "Unexpected space before function parentheses.", - fix: fixer => fixer.removeRange([leftToken.range[1], rightToken.range[0]]) - }); - } else if (!hasSpacing && functionConfig === "always") { - context.report({ - node, - loc: leftToken.loc.end, - message: "Missing space before function parentheses.", - fix: fixer => fixer.insertTextAfter(leftToken, " ") - }); - } - } - - return { - ArrowFunctionExpression: checkFunction, - FunctionDeclaration: checkFunction, - FunctionExpression: checkFunction - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/space-in-parens.js b/tools/node_modules/eslint/lib/rules/space-in-parens.js deleted file mode 100644 index 3068662632172e..00000000000000 --- a/tools/node_modules/eslint/lib/rules/space-in-parens.js +++ /dev/null @@ -1,276 +0,0 @@ -/** - * @fileoverview Disallows or enforces spaces inside of parentheses. - * @author Jonathan Rajavuori - */ -"use strict"; - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce consistent spacing inside parentheses", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/space-in-parens" - }, - - fixable: "whitespace", - - schema: [ - { - enum: ["always", "never"] - }, - { - type: "object", - properties: { - exceptions: { - type: "array", - items: { - enum: ["{}", "[]", "()", "empty"] - }, - uniqueItems: true - } - }, - additionalProperties: false - } - ] - }, - - create(context) { - - const MISSING_SPACE_MESSAGE = "There must be a space inside this paren.", - REJECTED_SPACE_MESSAGE = "There should be no spaces inside this paren.", - ALWAYS = context.options[0] === "always", - exceptionsArrayOptions = (context.options[1] && context.options[1].exceptions) || [], - options = {}; - let exceptions; - - if (exceptionsArrayOptions.length) { - options.braceException = exceptionsArrayOptions.indexOf("{}") !== -1; - options.bracketException = exceptionsArrayOptions.indexOf("[]") !== -1; - options.parenException = exceptionsArrayOptions.indexOf("()") !== -1; - options.empty = exceptionsArrayOptions.indexOf("empty") !== -1; - } - - /** - * Produces an object with the opener and closer exception values - * @returns {Object} `openers` and `closers` exception values - * @private - */ - function getExceptions() { - const openers = [], - closers = []; - - if (options.braceException) { - openers.push("{"); - closers.push("}"); - } - - if (options.bracketException) { - openers.push("["); - closers.push("]"); - } - - if (options.parenException) { - openers.push("("); - closers.push(")"); - } - - if (options.empty) { - openers.push(")"); - closers.push("("); - } - - return { - openers, - closers - }; - } - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - const sourceCode = context.getSourceCode(); - - /** - * Determines if a token is one of the exceptions for the opener paren - * @param {Object} token The token to check - * @returns {boolean} True if the token is one of the exceptions for the opener paren - */ - function isOpenerException(token) { - return token.type === "Punctuator" && exceptions.openers.indexOf(token.value) >= 0; - } - - /** - * Determines if a token is one of the exceptions for the closer paren - * @param {Object} token The token to check - * @returns {boolean} True if the token is one of the exceptions for the closer paren - */ - function isCloserException(token) { - return token.type === "Punctuator" && exceptions.closers.indexOf(token.value) >= 0; - } - - /** - * Determines if an opener paren should have a missing space after it - * @param {Object} left The paren token - * @param {Object} right The token after it - * @returns {boolean} True if the paren should have a space - */ - function shouldOpenerHaveSpace(left, right) { - if (sourceCode.isSpaceBetweenTokens(left, right)) { - return false; - } - - if (ALWAYS) { - if (astUtils.isClosingParenToken(right)) { - return false; - } - return !isOpenerException(right); - } - return isOpenerException(right); - - } - - /** - * Determines if an closer paren should have a missing space after it - * @param {Object} left The token before the paren - * @param {Object} right The paren token - * @returns {boolean} True if the paren should have a space - */ - function shouldCloserHaveSpace(left, right) { - if (astUtils.isOpeningParenToken(left)) { - return false; - } - - if (sourceCode.isSpaceBetweenTokens(left, right)) { - return false; - } - - if (ALWAYS) { - return !isCloserException(left); - } - return isCloserException(left); - - } - - /** - * Determines if an opener paren should not have an existing space after it - * @param {Object} left The paren token - * @param {Object} right The token after it - * @returns {boolean} True if the paren should reject the space - */ - function shouldOpenerRejectSpace(left, right) { - if (right.type === "Line") { - return false; - } - - if (!astUtils.isTokenOnSameLine(left, right)) { - return false; - } - - if (!sourceCode.isSpaceBetweenTokens(left, right)) { - return false; - } - - if (ALWAYS) { - return isOpenerException(right); - } - return !isOpenerException(right); - - } - - /** - * Determines if an closer paren should not have an existing space after it - * @param {Object} left The token before the paren - * @param {Object} right The paren token - * @returns {boolean} True if the paren should reject the space - */ - function shouldCloserRejectSpace(left, right) { - if (astUtils.isOpeningParenToken(left)) { - return false; - } - - if (!astUtils.isTokenOnSameLine(left, right)) { - return false; - } - - if (!sourceCode.isSpaceBetweenTokens(left, right)) { - return false; - } - - if (ALWAYS) { - return isCloserException(left); - } - return !isCloserException(left); - - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - Program: function checkParenSpaces(node) { - exceptions = getExceptions(); - const tokens = sourceCode.tokensAndComments; - - tokens.forEach((token, i) => { - const prevToken = tokens[i - 1]; - const nextToken = tokens[i + 1]; - - if (!astUtils.isOpeningParenToken(token) && !astUtils.isClosingParenToken(token)) { - return; - } - - if (token.value === "(" && shouldOpenerHaveSpace(token, nextToken)) { - context.report({ - node, - loc: token.loc.start, - message: MISSING_SPACE_MESSAGE, - fix(fixer) { - return fixer.insertTextAfter(token, " "); - } - }); - } else if (token.value === "(" && shouldOpenerRejectSpace(token, nextToken)) { - context.report({ - node, - loc: token.loc.start, - message: REJECTED_SPACE_MESSAGE, - fix(fixer) { - return fixer.removeRange([token.range[1], nextToken.range[0]]); - } - }); - } else if (token.value === ")" && shouldCloserHaveSpace(prevToken, token)) { - - // context.report(node, token.loc.start, MISSING_SPACE_MESSAGE); - context.report({ - node, - loc: token.loc.start, - message: MISSING_SPACE_MESSAGE, - fix(fixer) { - return fixer.insertTextBefore(token, " "); - } - }); - } else if (token.value === ")" && shouldCloserRejectSpace(prevToken, token)) { - context.report({ - node, - loc: token.loc.start, - message: REJECTED_SPACE_MESSAGE, - fix(fixer) { - return fixer.removeRange([prevToken.range[1], token.range[0]]); - } - }); - } - }); - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/space-infix-ops.js b/tools/node_modules/eslint/lib/rules/space-infix-ops.js deleted file mode 100644 index 8d1d172c6697b6..00000000000000 --- a/tools/node_modules/eslint/lib/rules/space-infix-ops.js +++ /dev/null @@ -1,165 +0,0 @@ -/** - * @fileoverview Require spaces around infix operators - * @author Michael Ficarra - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "require spacing around infix operators", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/space-infix-ops" - }, - - fixable: "whitespace", - - schema: [ - { - type: "object", - properties: { - int32Hint: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ] - }, - - create(context) { - const int32Hint = context.options[0] ? context.options[0].int32Hint === true : false; - const sourceCode = context.getSourceCode(); - - /** - * Returns the first token which violates the rule - * @param {ASTNode} left - The left node of the main node - * @param {ASTNode} right - The right node of the main node - * @param {string} op - The operator of the main node - * @returns {Object} The violator token or null - * @private - */ - function getFirstNonSpacedToken(left, right, op) { - const operator = sourceCode.getFirstTokenBetween(left, right, token => token.value === op); - const prev = sourceCode.getTokenBefore(operator); - const next = sourceCode.getTokenAfter(operator); - - if (!sourceCode.isSpaceBetweenTokens(prev, operator) || !sourceCode.isSpaceBetweenTokens(operator, next)) { - return operator; - } - - return null; - } - - /** - * Reports an AST node as a rule violation - * @param {ASTNode} mainNode - The node to report - * @param {Object} culpritToken - The token which has a problem - * @returns {void} - * @private - */ - function report(mainNode, culpritToken) { - context.report({ - node: mainNode, - loc: culpritToken.loc.start, - message: "Operator '{{operator}}' must be spaced.", - data: { - operator: culpritToken.value - }, - fix(fixer) { - const previousToken = sourceCode.getTokenBefore(culpritToken); - const afterToken = sourceCode.getTokenAfter(culpritToken); - let fixString = ""; - - if (culpritToken.range[0] - previousToken.range[1] === 0) { - fixString = " "; - } - - fixString += culpritToken.value; - - if (afterToken.range[0] - culpritToken.range[1] === 0) { - fixString += " "; - } - - return fixer.replaceText(culpritToken, fixString); - } - }); - } - - /** - * Check if the node is binary then report - * @param {ASTNode} node node to evaluate - * @returns {void} - * @private - */ - function checkBinary(node) { - const leftNode = (node.left.typeAnnotation) ? node.left.typeAnnotation : node.left; - const rightNode = node.right; - - // search for = in AssignmentPattern nodes - const operator = node.operator || "="; - - const nonSpacedNode = getFirstNonSpacedToken(leftNode, rightNode, operator); - - if (nonSpacedNode) { - if (!(int32Hint && sourceCode.getText(node).endsWith("|0"))) { - report(node, nonSpacedNode); - } - } - } - - /** - * Check if the node is conditional - * @param {ASTNode} node node to evaluate - * @returns {void} - * @private - */ - function checkConditional(node) { - const nonSpacedConsequesntNode = getFirstNonSpacedToken(node.test, node.consequent, "?"); - const nonSpacedAlternateNode = getFirstNonSpacedToken(node.consequent, node.alternate, ":"); - - if (nonSpacedConsequesntNode) { - report(node, nonSpacedConsequesntNode); - } else if (nonSpacedAlternateNode) { - report(node, nonSpacedAlternateNode); - } - } - - /** - * Check if the node is a variable - * @param {ASTNode} node node to evaluate - * @returns {void} - * @private - */ - function checkVar(node) { - const leftNode = (node.id.typeAnnotation) ? node.id.typeAnnotation : node.id; - const rightNode = node.init; - - if (rightNode) { - const nonSpacedNode = getFirstNonSpacedToken(leftNode, rightNode, "="); - - if (nonSpacedNode) { - report(node, nonSpacedNode); - } - } - } - - return { - AssignmentExpression: checkBinary, - AssignmentPattern: checkBinary, - BinaryExpression: checkBinary, - LogicalExpression: checkBinary, - ConditionalExpression: checkConditional, - VariableDeclarator: checkVar - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/space-unary-ops.js b/tools/node_modules/eslint/lib/rules/space-unary-ops.js deleted file mode 100644 index 779697b5b39b08..00000000000000 --- a/tools/node_modules/eslint/lib/rules/space-unary-ops.js +++ /dev/null @@ -1,321 +0,0 @@ -/** - * @fileoverview This rule shoud require or disallow spaces before or after unary operations. - * @author Marcin Kumorek - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce consistent spacing before or after unary operators", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/space-unary-ops" - }, - - fixable: "whitespace", - - schema: [ - { - type: "object", - properties: { - words: { - type: "boolean", - default: true - }, - nonwords: { - type: "boolean", - default: false - }, - overrides: { - type: "object", - additionalProperties: { - type: "boolean" - } - } - }, - additionalProperties: false - } - ], - messages: { - unexpectedBefore: "Unexpected space before unary operator '{{operator}}'.", - unexpectedAfter: "Unexpected space after unary operator '{{operator}}'.", - unexpectedAfterWord: "Unexpected space after unary word operator '{{word}}'.", - wordOperator: "Unary word operator '{{word}}' must be followed by whitespace.", - operator: "Unary operator '{{operator}}' must be followed by whitespace.", - beforeUnaryExpressions: "Space is required before unary expressions '{{token}}'." - } - }, - - create(context) { - const options = context.options[0] || { words: true, nonwords: false }; - - const sourceCode = context.getSourceCode(); - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Check if the node is the first "!" in a "!!" convert to Boolean expression - * @param {ASTnode} node AST node - * @returns {boolean} Whether or not the node is first "!" in "!!" - */ - function isFirstBangInBangBangExpression(node) { - return node && node.type === "UnaryExpression" && node.argument.operator === "!" && - node.argument && node.argument.type === "UnaryExpression" && node.argument.operator === "!"; - } - - /** - * Checks if an override exists for a given operator. - * @param {string} operator Operator - * @returns {boolean} Whether or not an override has been provided for the operator - */ - function overrideExistsForOperator(operator) { - return options.overrides && Object.prototype.hasOwnProperty.call(options.overrides, operator); - } - - /** - * Gets the value that the override was set to for this operator - * @param {string} operator Operator - * @returns {boolean} Whether or not an override enforces a space with this operator - */ - function overrideEnforcesSpaces(operator) { - return options.overrides[operator]; - } - - /** - * Verify Unary Word Operator has spaces after the word operator - * @param {ASTnode} node AST node - * @param {Object} firstToken first token from the AST node - * @param {Object} secondToken second token from the AST node - * @param {string} word The word to be used for reporting - * @returns {void} - */ - function verifyWordHasSpaces(node, firstToken, secondToken, word) { - if (secondToken.range[0] === firstToken.range[1]) { - context.report({ - node, - messageId: "wordOperator", - data: { - word - }, - fix(fixer) { - return fixer.insertTextAfter(firstToken, " "); - } - }); - } - } - - /** - * Verify Unary Word Operator doesn't have spaces after the word operator - * @param {ASTnode} node AST node - * @param {Object} firstToken first token from the AST node - * @param {Object} secondToken second token from the AST node - * @param {string} word The word to be used for reporting - * @returns {void} - */ - function verifyWordDoesntHaveSpaces(node, firstToken, secondToken, word) { - if (astUtils.canTokensBeAdjacent(firstToken, secondToken)) { - if (secondToken.range[0] > firstToken.range[1]) { - context.report({ - node, - messageId: "unexpectedAfterWord", - data: { - word - }, - fix(fixer) { - return fixer.removeRange([firstToken.range[1], secondToken.range[0]]); - } - }); - } - } - } - - /** - * Check Unary Word Operators for spaces after the word operator - * @param {ASTnode} node AST node - * @param {Object} firstToken first token from the AST node - * @param {Object} secondToken second token from the AST node - * @param {string} word The word to be used for reporting - * @returns {void} - */ - function checkUnaryWordOperatorForSpaces(node, firstToken, secondToken, word) { - if (overrideExistsForOperator(word)) { - if (overrideEnforcesSpaces(word)) { - verifyWordHasSpaces(node, firstToken, secondToken, word); - } else { - verifyWordDoesntHaveSpaces(node, firstToken, secondToken, word); - } - } else if (options.words) { - verifyWordHasSpaces(node, firstToken, secondToken, word); - } else { - verifyWordDoesntHaveSpaces(node, firstToken, secondToken, word); - } - } - - /** - * Verifies YieldExpressions satisfy spacing requirements - * @param {ASTnode} node AST node - * @returns {void} - */ - function checkForSpacesAfterYield(node) { - const tokens = sourceCode.getFirstTokens(node, 3), - word = "yield"; - - if (!node.argument || node.delegate) { - return; - } - - checkUnaryWordOperatorForSpaces(node, tokens[0], tokens[1], word); - } - - /** - * Verifies AwaitExpressions satisfy spacing requirements - * @param {ASTNode} node AwaitExpression AST node - * @returns {void} - */ - function checkForSpacesAfterAwait(node) { - const tokens = sourceCode.getFirstTokens(node, 3); - - checkUnaryWordOperatorForSpaces(node, tokens[0], tokens[1], "await"); - } - - /** - * Verifies UnaryExpression, UpdateExpression and NewExpression have spaces before or after the operator - * @param {ASTnode} node AST node - * @param {Object} firstToken First token in the expression - * @param {Object} secondToken Second token in the expression - * @returns {void} - */ - function verifyNonWordsHaveSpaces(node, firstToken, secondToken) { - if (node.prefix) { - if (isFirstBangInBangBangExpression(node)) { - return; - } - if (firstToken.range[1] === secondToken.range[0]) { - context.report({ - node, - messageId: "operator", - data: { - operator: firstToken.value - }, - fix(fixer) { - return fixer.insertTextAfter(firstToken, " "); - } - }); - } - } else { - if (firstToken.range[1] === secondToken.range[0]) { - context.report({ - node, - messageId: "beforeUnaryExpressions", - data: { - token: secondToken.value - }, - fix(fixer) { - return fixer.insertTextBefore(secondToken, " "); - } - }); - } - } - } - - /** - * Verifies UnaryExpression, UpdateExpression and NewExpression don't have spaces before or after the operator - * @param {ASTnode} node AST node - * @param {Object} firstToken First token in the expression - * @param {Object} secondToken Second token in the expression - * @returns {void} - */ - function verifyNonWordsDontHaveSpaces(node, firstToken, secondToken) { - if (node.prefix) { - if (secondToken.range[0] > firstToken.range[1]) { - context.report({ - node, - messageId: "unexpectedAfter", - data: { - operator: firstToken.value - }, - fix(fixer) { - if (astUtils.canTokensBeAdjacent(firstToken, secondToken)) { - return fixer.removeRange([firstToken.range[1], secondToken.range[0]]); - } - return null; - } - }); - } - } else { - if (secondToken.range[0] > firstToken.range[1]) { - context.report({ - node, - messageId: "unexpectedBefore", - data: { - operator: secondToken.value - }, - fix(fixer) { - return fixer.removeRange([firstToken.range[1], secondToken.range[0]]); - } - }); - } - } - } - - /** - * Verifies UnaryExpression, UpdateExpression and NewExpression satisfy spacing requirements - * @param {ASTnode} node AST node - * @returns {void} - */ - function checkForSpaces(node) { - const tokens = node.type === "UpdateExpression" && !node.prefix - ? sourceCode.getLastTokens(node, 2) - : sourceCode.getFirstTokens(node, 2); - const firstToken = tokens[0]; - const secondToken = tokens[1]; - - if ((node.type === "NewExpression" || node.prefix) && firstToken.type === "Keyword") { - checkUnaryWordOperatorForSpaces(node, firstToken, secondToken, firstToken.value); - return; - } - - const operator = node.prefix ? tokens[0].value : tokens[1].value; - - if (overrideExistsForOperator(operator)) { - if (overrideEnforcesSpaces(operator)) { - verifyNonWordsHaveSpaces(node, firstToken, secondToken); - } else { - verifyNonWordsDontHaveSpaces(node, firstToken, secondToken); - } - } else if (options.nonwords) { - verifyNonWordsHaveSpaces(node, firstToken, secondToken); - } else { - verifyNonWordsDontHaveSpaces(node, firstToken, secondToken); - } - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - UnaryExpression: checkForSpaces, - UpdateExpression: checkForSpaces, - NewExpression: checkForSpaces, - YieldExpression: checkForSpacesAfterYield, - AwaitExpression: checkForSpacesAfterAwait - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/spaced-comment.js b/tools/node_modules/eslint/lib/rules/spaced-comment.js deleted file mode 100644 index 63177eb1c7f4f4..00000000000000 --- a/tools/node_modules/eslint/lib/rules/spaced-comment.js +++ /dev/null @@ -1,375 +0,0 @@ -/** - * @fileoverview Source code for spaced-comments rule - * @author Gyandeep Singh - */ -"use strict"; - -const lodash = require("lodash"); -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Escapes the control characters of a given string. - * @param {string} s - A string to escape. - * @returns {string} An escaped string. - */ -function escape(s) { - return `(?:${lodash.escapeRegExp(s)})`; -} - -/** - * Escapes the control characters of a given string. - * And adds a repeat flag. - * @param {string} s - A string to escape. - * @returns {string} An escaped string. - */ -function escapeAndRepeat(s) { - return `${escape(s)}+`; -} - -/** - * Parses `markers` option. - * If markers don't include `"*"`, this adds `"*"` to allow JSDoc comments. - * @param {string[]} [markers] - A marker list. - * @returns {string[]} A marker list. - */ -function parseMarkersOption(markers) { - - // `*` is a marker for JSDoc comments. - if (markers.indexOf("*") === -1) { - return markers.concat("*"); - } - - return markers; -} - -/** - * Creates string pattern for exceptions. - * Generated pattern: - * - * 1. A space or an exception pattern sequence. - * - * @param {string[]} exceptions - An exception pattern list. - * @returns {string} A regular expression string for exceptions. - */ -function createExceptionsPattern(exceptions) { - let pattern = ""; - - /* - * A space or an exception pattern sequence. - * [] ==> "\s" - * ["-"] ==> "(?:\s|\-+$)" - * ["-", "="] ==> "(?:\s|(?:\-+|=+)$)" - * ["-", "=", "--=="] ==> "(?:\s|(?:\-+|=+|(?:\-\-==)+)$)" ==> https://jex.im/regulex/#!embed=false&flags=&re=(%3F%3A%5Cs%7C(%3F%3A%5C-%2B%7C%3D%2B%7C(%3F%3A%5C-%5C-%3D%3D)%2B)%24) - */ - if (exceptions.length === 0) { - - // a space. - pattern += "\\s"; - } else { - - // a space or... - pattern += "(?:\\s|"; - - if (exceptions.length === 1) { - - // a sequence of the exception pattern. - pattern += escapeAndRepeat(exceptions[0]); - } else { - - // a sequence of one of the exception patterns. - pattern += "(?:"; - pattern += exceptions.map(escapeAndRepeat).join("|"); - pattern += ")"; - } - pattern += `(?:$|[${Array.from(astUtils.LINEBREAKS).join("")}]))`; - } - - return pattern; -} - -/** - * Creates RegExp object for `always` mode. - * Generated pattern for beginning of comment: - * - * 1. First, a marker or nothing. - * 2. Next, a space or an exception pattern sequence. - * - * @param {string[]} markers - A marker list. - * @param {string[]} exceptions - An exception pattern list. - * @returns {RegExp} A RegExp object for the beginning of a comment in `always` mode. - */ -function createAlwaysStylePattern(markers, exceptions) { - let pattern = "^"; - - /* - * A marker or nothing. - * ["*"] ==> "\*?" - * ["*", "!"] ==> "(?:\*|!)?" - * ["*", "/", "!<"] ==> "(?:\*|\/|(?:!<))?" ==> https://jex.im/regulex/#!embed=false&flags=&re=(%3F%3A%5C*%7C%5C%2F%7C(%3F%3A!%3C))%3F - */ - if (markers.length === 1) { - - // the marker. - pattern += escape(markers[0]); - } else { - - // one of markers. - pattern += "(?:"; - pattern += markers.map(escape).join("|"); - pattern += ")"; - } - - pattern += "?"; // or nothing. - pattern += createExceptionsPattern(exceptions); - - return new RegExp(pattern); -} - -/** - * Creates RegExp object for `never` mode. - * Generated pattern for beginning of comment: - * - * 1. First, a marker or nothing (captured). - * 2. Next, a space or a tab. - * - * @param {string[]} markers - A marker list. - * @returns {RegExp} A RegExp object for `never` mode. - */ -function createNeverStylePattern(markers) { - const pattern = `^(${markers.map(escape).join("|")})?[ \t]+`; - - return new RegExp(pattern); -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce consistent spacing after the `//` or `/*` in a comment", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/spaced-comment" - }, - - fixable: "whitespace", - - schema: [ - { - enum: ["always", "never"] - }, - { - type: "object", - properties: { - exceptions: { - type: "array", - items: { - type: "string" - } - }, - markers: { - type: "array", - items: { - type: "string" - } - }, - line: { - type: "object", - properties: { - exceptions: { - type: "array", - items: { - type: "string" - } - }, - markers: { - type: "array", - items: { - type: "string" - } - } - }, - additionalProperties: false - }, - block: { - type: "object", - properties: { - exceptions: { - type: "array", - items: { - type: "string" - } - }, - markers: { - type: "array", - items: { - type: "string" - } - }, - balanced: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - }, - additionalProperties: false - } - ] - }, - - create(context) { - - const sourceCode = context.getSourceCode(); - - // Unless the first option is never, require a space - const requireSpace = context.options[0] !== "never"; - - /* - * Parse the second options. - * If markers don't include `"*"`, it's added automatically for JSDoc - * comments. - */ - const config = context.options[1] || {}; - const balanced = config.block && config.block.balanced; - - 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]+$"; - - // Create RegExp object for valid patterns. - rule[type] = { - beginRegex: requireSpace ? createAlwaysStylePattern(markers, exceptions) : createNeverStylePattern(markers), - endRegex: balanced && requireSpace ? new RegExp(`${createExceptionsPattern(exceptions)}$`) : new RegExp(endNeverPattern), - hasExceptions: exceptions.length > 0, - markers: new RegExp(`^(${markers.map(escape).join("|")})`) - }; - - return rule; - }, {}); - - /** - * Reports a beginning spacing error with an appropriate message. - * @param {ASTNode} node - A comment node to check. - * @param {string} message - An error message to report. - * @param {Array} match - An array of match results for markers. - * @param {string} refChar - Character used for reference in the error message. - * @returns {void} - */ - function reportBegin(node, message, match, refChar) { - const type = node.type.toLowerCase(), - commentIdentifier = type === "block" ? "/*" : "//"; - - context.report({ - node, - fix(fixer) { - const start = node.range[0]; - let end = start + 2; - - if (requireSpace) { - if (match) { - end += match[0].length; - } - return fixer.insertTextAfterRange([start, end], " "); - } - end += match[0].length; - return fixer.replaceTextRange([start, end], commentIdentifier + (match[1] ? match[1] : "")); - - }, - message, - data: { refChar } - }); - } - - /** - * Reports an ending spacing error with an appropriate message. - * @param {ASTNode} node - A comment node to check. - * @param {string} message - An error message to report. - * @param {string} match - An array of the matched whitespace characters. - * @returns {void} - */ - function reportEnd(node, message, match) { - context.report({ - node, - fix(fixer) { - if (requireSpace) { - return fixer.insertTextAfterRange([node.range[0], node.range[1] - 2], " "); - } - const end = node.range[1] - 2, - start = end - match[0].length; - - return fixer.replaceTextRange([start, end], ""); - - }, - message - }); - } - - /** - * Reports a given comment if it's invalid. - * @param {ASTNode} node - a comment node to check. - * @returns {void} - */ - function checkCommentForSpace(node) { - const type = node.type.toLowerCase(), - rule = styleRules[type], - commentIdentifier = type === "block" ? "/*" : "//"; - - // Ignores empty comments. - if (node.value.length === 0) { - return; - } - - const beginMatch = rule.beginRegex.exec(node.value); - const endMatch = rule.endRegex.exec(node.value); - - // Checks. - if (requireSpace) { - if (!beginMatch) { - const hasMarker = rule.markers.exec(node.value); - const marker = hasMarker ? commentIdentifier + hasMarker[0] : commentIdentifier; - - if (rule.hasExceptions) { - reportBegin(node, "Expected exception block, space or tab after '{{refChar}}' in comment.", hasMarker, marker); - } else { - reportBegin(node, "Expected space or tab after '{{refChar}}' in comment.", hasMarker, marker); - } - } - - if (balanced && type === "block" && !endMatch) { - reportEnd(node, "Expected space or tab before '*/' in comment."); - } - } else { - if (beginMatch) { - if (!beginMatch[1]) { - reportBegin(node, "Unexpected space or tab after '{{refChar}}' in comment.", beginMatch, commentIdentifier); - } else { - reportBegin(node, "Unexpected space or tab after marker ({{refChar}}) in comment.", beginMatch, beginMatch[1]); - } - } - - if (balanced && type === "block" && endMatch) { - reportEnd(node, "Unexpected space or tab before '*/' in comment.", endMatch); - } - } - } - - return { - Program() { - const comments = sourceCode.getAllComments(); - - comments.filter(token => token.type !== "Shebang").forEach(checkCommentForSpace); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/strict.js b/tools/node_modules/eslint/lib/rules/strict.js deleted file mode 100644 index a826731260b376..00000000000000 --- a/tools/node_modules/eslint/lib/rules/strict.js +++ /dev/null @@ -1,279 +0,0 @@ -/** - * @fileoverview Rule to control usage of strict mode directives. - * @author Brandon Mills - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Gets all of the Use Strict Directives in the Directive Prologue of a group of - * statements. - * @param {ASTNode[]} statements Statements in the program or function body. - * @returns {ASTNode[]} All of the Use Strict Directives. - */ -function getUseStrictDirectives(statements) { - const directives = []; - - for (let i = 0; i < statements.length; i++) { - const statement = statements[i]; - - if ( - statement.type === "ExpressionStatement" && - statement.expression.type === "Literal" && - statement.expression.value === "use strict" - ) { - directives[i] = statement; - } else { - break; - } - } - - return directives; -} - -/** - * Checks whether a given parameter is a simple parameter. - * - * @param {ASTNode} node - A pattern node to check. - * @returns {boolean} `true` if the node is an Identifier node. - */ -function isSimpleParameter(node) { - return node.type === "Identifier"; -} - -/** - * Checks whether a given parameter list is a simple parameter list. - * - * @param {ASTNode[]} params - A parameter list to check. - * @returns {boolean} `true` if the every parameter is an Identifier node. - */ -function isSimpleParameterList(params) { - return params.every(isSimpleParameter); -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require or disallow strict mode directives", - category: "Strict Mode", - recommended: false, - url: "https://eslint.org/docs/rules/strict" - }, - - schema: [ - { - enum: ["never", "global", "function", "safe"] - } - ], - - fixable: "code", - messages: { - function: "Use the function form of 'use strict'.", - global: "Use the global form of 'use strict'.", - multiple: "Multiple 'use strict' directives.", - never: "Strict mode is not permitted.", - unnecessary: "Unnecessary 'use strict' directive.", - module: "'use strict' is unnecessary inside of modules.", - implied: "'use strict' is unnecessary when implied strict mode is enabled.", - unnecessaryInClasses: "'use strict' is unnecessary inside of classes.", - nonSimpleParameterList: "'use strict' directive inside a function with non-simple parameter list throws a syntax error since ES2016.", - wrap: "Wrap {{name}} in a function with 'use strict' directive." - } - }, - - create(context) { - - const ecmaFeatures = context.parserOptions.ecmaFeatures || {}, - scopes = [], - classScopes = []; - let mode = context.options[0] || "safe"; - - if (ecmaFeatures.impliedStrict) { - mode = "implied"; - } else if (mode === "safe") { - mode = ecmaFeatures.globalReturn ? "global" : "function"; - } - - /** - * Determines whether a reported error should be fixed, depending on the error type. - * @param {string} errorType The type of error - * @returns {boolean} `true` if the reported error should be fixed - */ - function shouldFix(errorType) { - return errorType === "multiple" || errorType === "unnecessary" || errorType === "module" || errorType === "implied" || errorType === "unnecessaryInClasses"; - } - - /** - * Gets a fixer function to remove a given 'use strict' directive. - * @param {ASTNode} node The directive that should be removed - * @returns {Function} A fixer function - */ - function getFixFunction(node) { - return fixer => fixer.remove(node); - } - - /** - * Report a slice of an array of nodes with a given message. - * @param {ASTNode[]} nodes Nodes. - * @param {string} start Index to start from. - * @param {string} end Index to end before. - * @param {string} messageId Message to display. - * @param {boolean} fix `true` if the directive should be fixed (i.e. removed) - * @returns {void} - */ - function reportSlice(nodes, start, end, messageId, fix) { - nodes.slice(start, end).forEach(node => { - context.report({ node, messageId, fix: fix ? getFixFunction(node) : null }); - }); - } - - /** - * Report all nodes in an array with a given message. - * @param {ASTNode[]} nodes Nodes. - * @param {string} messageId Message id to display. - * @param {boolean} fix `true` if the directive should be fixed (i.e. removed) - * @returns {void} - */ - function reportAll(nodes, messageId, fix) { - reportSlice(nodes, 0, nodes.length, messageId, fix); - } - - /** - * Report all nodes in an array, except the first, with a given message. - * @param {ASTNode[]} nodes Nodes. - * @param {string} messageId Message id to display. - * @param {boolean} fix `true` if the directive should be fixed (i.e. removed) - * @returns {void} - */ - function reportAllExceptFirst(nodes, messageId, fix) { - reportSlice(nodes, 1, nodes.length, messageId, fix); - } - - /** - * Entering a function in 'function' mode pushes a new nested scope onto the - * stack. The new scope is true if the nested function is strict mode code. - * @param {ASTNode} node The function declaration or expression. - * @param {ASTNode[]} useStrictDirectives The Use Strict Directives of the node. - * @returns {void} - */ - function enterFunctionInFunctionMode(node, useStrictDirectives) { - const isInClass = classScopes.length > 0, - isParentGlobal = scopes.length === 0 && classScopes.length === 0, - isParentStrict = scopes.length > 0 && scopes[scopes.length - 1], - isStrict = useStrictDirectives.length > 0; - - if (isStrict) { - if (!isSimpleParameterList(node.params)) { - context.report({ node: useStrictDirectives[0], messageId: "nonSimpleParameterList" }); - } else if (isParentStrict) { - context.report({ node: useStrictDirectives[0], messageId: "unnecessary", fix: getFixFunction(useStrictDirectives[0]) }); - } else if (isInClass) { - context.report({ node: useStrictDirectives[0], messageId: "unnecessaryInClasses", fix: getFixFunction(useStrictDirectives[0]) }); - } - - reportAllExceptFirst(useStrictDirectives, "multiple", true); - } else if (isParentGlobal) { - if (isSimpleParameterList(node.params)) { - context.report({ node, messageId: "function" }); - } else { - context.report({ - node, - messageId: "wrap", - data: { name: astUtils.getFunctionNameWithKind(node) } - }); - } - } - - scopes.push(isParentStrict || isStrict); - } - - /** - * Exiting a function in 'function' mode pops its scope off the stack. - * @returns {void} - */ - function exitFunctionInFunctionMode() { - scopes.pop(); - } - - /** - * Enter a function and either: - * - Push a new nested scope onto the stack (in 'function' mode). - * - Report all the Use Strict Directives (in the other modes). - * @param {ASTNode} node The function declaration or expression. - * @returns {void} - */ - function enterFunction(node) { - const isBlock = node.body.type === "BlockStatement", - useStrictDirectives = isBlock - ? getUseStrictDirectives(node.body.body) : []; - - if (mode === "function") { - enterFunctionInFunctionMode(node, useStrictDirectives); - } else if (useStrictDirectives.length > 0) { - if (isSimpleParameterList(node.params)) { - reportAll(useStrictDirectives, mode, shouldFix(mode)); - } else { - context.report({ node: useStrictDirectives[0], messageId: "nonSimpleParameterList" }); - reportAllExceptFirst(useStrictDirectives, "multiple", true); - } - } - } - - const rule = { - Program(node) { - const useStrictDirectives = getUseStrictDirectives(node.body); - - if (node.sourceType === "module") { - mode = "module"; - } - - if (mode === "global") { - if (node.body.length > 0 && useStrictDirectives.length === 0) { - context.report({ node, messageId: "global" }); - } - reportAllExceptFirst(useStrictDirectives, "multiple", true); - } else { - reportAll(useStrictDirectives, mode, shouldFix(mode)); - } - }, - FunctionDeclaration: enterFunction, - FunctionExpression: enterFunction, - ArrowFunctionExpression: enterFunction - }; - - if (mode === "function") { - Object.assign(rule, { - - // Inside of class bodies are always strict mode. - ClassBody() { - classScopes.push(true); - }, - "ClassBody:exit"() { - classScopes.pop(); - }, - - "FunctionDeclaration:exit": exitFunctionInFunctionMode, - "FunctionExpression:exit": exitFunctionInFunctionMode, - "ArrowFunctionExpression:exit": exitFunctionInFunctionMode - }); - } - - return rule; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/switch-colon-spacing.js b/tools/node_modules/eslint/lib/rules/switch-colon-spacing.js deleted file mode 100644 index 40154862d19215..00000000000000 --- a/tools/node_modules/eslint/lib/rules/switch-colon-spacing.js +++ /dev/null @@ -1,141 +0,0 @@ -/** - * @fileoverview Rule to enforce spacing around colons of switch statements. - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce spacing around colons of switch statements", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/switch-colon-spacing" - }, - - schema: [ - { - type: "object", - properties: { - before: { type: "boolean", default: false }, - after: { type: "boolean", default: true } - }, - additionalProperties: false - } - ], - fixable: "whitespace", - messages: { - expectedBefore: "Expected space(s) before this colon.", - expectedAfter: "Expected space(s) after this colon.", - unexpectedBefore: "Unexpected space(s) before this colon.", - unexpectedAfter: "Unexpected space(s) after this colon." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - const options = context.options[0] || {}; - const beforeSpacing = options.before === true; // false by default - const afterSpacing = options.after !== false; // true by default - - /** - * Get the colon token of the given SwitchCase node. - * @param {ASTNode} node The SwitchCase node to get. - * @returns {Token} The colon token of the node. - */ - function getColonToken(node) { - if (node.test) { - return sourceCode.getTokenAfter(node.test, astUtils.isColonToken); - } - return sourceCode.getFirstToken(node, 1); - } - - /** - * Check whether the spacing between the given 2 tokens is valid or not. - * @param {Token} left The left token to check. - * @param {Token} right The right token to check. - * @param {boolean} expected The expected spacing to check. `true` if there should be a space. - * @returns {boolean} `true` if the spacing between the tokens is valid. - */ - function isValidSpacing(left, right, expected) { - return ( - astUtils.isClosingBraceToken(right) || - !astUtils.isTokenOnSameLine(left, right) || - sourceCode.isSpaceBetweenTokens(left, right) === expected - ); - } - - /** - * Check whether comments exist between the given 2 tokens. - * @param {Token} left The left token to check. - * @param {Token} right The right token to check. - * @returns {boolean} `true` if comments exist between the given 2 tokens. - */ - function commentsExistBetween(left, right) { - return sourceCode.getFirstTokenBetween( - left, - right, - { - includeComments: true, - filter: astUtils.isCommentToken - } - ) !== null; - } - - /** - * Fix the spacing between the given 2 tokens. - * @param {RuleFixer} fixer The fixer to fix. - * @param {Token} left The left token of fix range. - * @param {Token} right The right token of fix range. - * @param {boolean} spacing The spacing style. `true` if there should be a space. - * @returns {Fix|null} The fix object. - */ - function fix(fixer, left, right, spacing) { - if (commentsExistBetween(left, right)) { - return null; - } - if (spacing) { - return fixer.insertTextAfter(left, " "); - } - return fixer.removeRange([left.range[1], right.range[0]]); - } - - return { - SwitchCase(node) { - const colonToken = getColonToken(node); - const beforeToken = sourceCode.getTokenBefore(colonToken); - const afterToken = sourceCode.getTokenAfter(colonToken); - - if (!isValidSpacing(beforeToken, colonToken, beforeSpacing)) { - context.report({ - node, - loc: colonToken.loc, - messageId: beforeSpacing ? "expectedBefore" : "unexpectedBefore", - fix: fixer => fix(fixer, beforeToken, colonToken, beforeSpacing) - }); - } - if (!isValidSpacing(colonToken, afterToken, afterSpacing)) { - context.report({ - node, - loc: colonToken.loc, - messageId: afterSpacing ? "expectedAfter" : "unexpectedAfter", - fix: fixer => fix(fixer, colonToken, afterToken, afterSpacing) - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/symbol-description.js b/tools/node_modules/eslint/lib/rules/symbol-description.js deleted file mode 100644 index f2e7e16b7a5874..00000000000000 --- a/tools/node_modules/eslint/lib/rules/symbol-description.js +++ /dev/null @@ -1,72 +0,0 @@ -/** - * @fileoverview Rule to enforce description with the `Symbol` object - * @author Jarek Rencz - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require symbol descriptions", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/symbol-description" - }, - fixable: null, - schema: [], - messages: { - expected: "Expected Symbol to have a description." - } - }, - - create(context) { - - /** - * Reports if node does not conform the rule in case rule is set to - * report missing description - * - * @param {ASTNode} node - A CallExpression node to check. - * @returns {void} - */ - function checkArgument(node) { - if (node.arguments.length === 0) { - context.report({ - node, - messageId: "expected" - }); - } - } - - return { - "Program:exit"() { - const scope = context.getScope(); - const variable = astUtils.getVariableByName(scope, "Symbol"); - - if (variable && variable.defs.length === 0) { - variable.references.forEach(reference => { - const node = reference.identifier; - - if (astUtils.isCallee(node)) { - checkArgument(node.parent); - } - }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/template-curly-spacing.js b/tools/node_modules/eslint/lib/rules/template-curly-spacing.js deleted file mode 100644 index 84957d475941bf..00000000000000 --- a/tools/node_modules/eslint/lib/rules/template-curly-spacing.js +++ /dev/null @@ -1,124 +0,0 @@ -/** - * @fileoverview Rule to enforce spacing around embedded expressions of template strings - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const OPEN_PAREN = /\$\{$/; -const CLOSE_PAREN = /^\}/; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "require or disallow spacing around embedded expressions of template strings", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/template-curly-spacing" - }, - - fixable: "whitespace", - - schema: [ - { enum: ["always", "never"] } - ], - messages: { - expectedBefore: "Expected space(s) before '}'.", - expectedAfter: "Expected space(s) after '${'.", - unexpectedBefore: "Unexpected space(s) before '}'.", - unexpectedAfter: "Unexpected space(s) after '${'." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - const always = context.options[0] === "always"; - const prefix = always ? "expected" : "unexpected"; - - /** - * Checks spacing before `}` of a given token. - * @param {Token} token - A token to check. This is a Template token. - * @returns {void} - */ - function checkSpacingBefore(token) { - const prevToken = sourceCode.getTokenBefore(token); - - if (prevToken && - CLOSE_PAREN.test(token.value) && - astUtils.isTokenOnSameLine(prevToken, token) && - sourceCode.isSpaceBetweenTokens(prevToken, token) !== always - ) { - context.report({ - loc: token.loc.start, - messageId: `${prefix}Before`, - fix(fixer) { - if (always) { - return fixer.insertTextBefore(token, " "); - } - return fixer.removeRange([ - prevToken.range[1], - token.range[0] - ]); - } - }); - } - } - - /** - * Checks spacing after `${` of a given token. - * @param {Token} token - A token to check. This is a Template token. - * @returns {void} - */ - function checkSpacingAfter(token) { - const nextToken = sourceCode.getTokenAfter(token); - - if (nextToken && - OPEN_PAREN.test(token.value) && - astUtils.isTokenOnSameLine(token, nextToken) && - sourceCode.isSpaceBetweenTokens(token, nextToken) !== always - ) { - context.report({ - loc: { - line: token.loc.end.line, - column: token.loc.end.column - 2 - }, - messageId: `${prefix}After`, - fix(fixer) { - if (always) { - return fixer.insertTextAfter(token, " "); - } - return fixer.removeRange([ - token.range[1], - nextToken.range[0] - ]); - } - }); - } - } - - return { - TemplateElement(node) { - const token = sourceCode.getFirstToken(node); - - checkSpacingBefore(token); - checkSpacingAfter(token); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/template-tag-spacing.js b/tools/node_modules/eslint/lib/rules/template-tag-spacing.js deleted file mode 100644 index 9eb6d86077da36..00000000000000 --- a/tools/node_modules/eslint/lib/rules/template-tag-spacing.js +++ /dev/null @@ -1,84 +0,0 @@ -/** - * @fileoverview Rule to check spacing between template tags and their literals - * @author Jonathan Wilsson - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "require or disallow spacing between template tags and their literals", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/template-tag-spacing" - }, - - fixable: "whitespace", - - schema: [ - { enum: ["always", "never"] } - ], - messages: { - unexpected: "Unexpected space between template tag and template literal.", - missing: "Missing space between template tag and template literal." - } - }, - - create(context) { - const never = context.options[0] !== "always"; - const sourceCode = context.getSourceCode(); - - /** - * Check if a space is present between a template tag and its literal - * @param {ASTNode} node node to evaluate - * @returns {void} - * @private - */ - function checkSpacing(node) { - const tagToken = sourceCode.getTokenBefore(node.quasi); - const literalToken = sourceCode.getFirstToken(node.quasi); - const hasWhitespace = sourceCode.isSpaceBetweenTokens(tagToken, literalToken); - - if (never && hasWhitespace) { - context.report({ - node, - loc: tagToken.loc.start, - messageId: "unexpected", - fix(fixer) { - const comments = sourceCode.getCommentsBefore(node.quasi); - - // Don't fix anything if there's a single line comment after the template tag - if (comments.some(comment => comment.type === "Line")) { - return null; - } - - return fixer.replaceTextRange( - [tagToken.range[1], literalToken.range[0]], - comments.reduce((text, comment) => text + sourceCode.getText(comment), "") - ); - } - }); - } else if (!never && !hasWhitespace) { - context.report({ - node, - loc: tagToken.loc.start, - messageId: "missing", - fix(fixer) { - return fixer.insertTextAfter(tagToken, " "); - } - }); - } - } - - return { - TaggedTemplateExpression: checkSpacing - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/unicode-bom.js b/tools/node_modules/eslint/lib/rules/unicode-bom.js deleted file mode 100644 index 39642f85193e90..00000000000000 --- a/tools/node_modules/eslint/lib/rules/unicode-bom.js +++ /dev/null @@ -1,73 +0,0 @@ -/** - * @fileoverview Require or disallow Unicode BOM - * @author Andrew Johnston - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "require or disallow Unicode byte order mark (BOM)", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/unicode-bom" - }, - - fixable: "whitespace", - - schema: [ - { - enum: ["always", "never"] - } - ], - messages: { - expected: "Expected Unicode BOM (Byte Order Mark).", - unexpected: "Unexpected Unicode BOM (Byte Order Mark)." - } - }, - - create(context) { - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - - Program: function checkUnicodeBOM(node) { - - const sourceCode = context.getSourceCode(), - location = { column: 0, line: 1 }, - requireBOM = context.options[0] || "never"; - - if (!sourceCode.hasBOM && (requireBOM === "always")) { - context.report({ - node, - loc: location, - messageId: "expected", - fix(fixer) { - return fixer.insertTextBeforeRange([0, 1], "\uFEFF"); - } - }); - } else if (sourceCode.hasBOM && (requireBOM === "never")) { - context.report({ - node, - loc: location, - messageId: "unexpected", - fix(fixer) { - return fixer.removeRange([-1, 0]); - } - }); - } - } - - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/use-isnan.js b/tools/node_modules/eslint/lib/rules/use-isnan.js deleted file mode 100644 index c8adefd608a751..00000000000000 --- a/tools/node_modules/eslint/lib/rules/use-isnan.js +++ /dev/null @@ -1,40 +0,0 @@ -/** - * @fileoverview Rule to flag comparisons to the value NaN - * @author James Allardice - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "require calls to `isNaN()` when checking for `NaN`", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/use-isnan" - }, - - schema: [], - messages: { - useIsNaN: "Use the isNaN function to compare with NaN." - } - }, - - create(context) { - - return { - BinaryExpression(node) { - if (/^(?:[<>]|[!=]=)=?$/.test(node.operator) && (node.left.name === "NaN" || node.right.name === "NaN")) { - context.report({ node, messageId: "useIsNaN" }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/valid-jsdoc.js b/tools/node_modules/eslint/lib/rules/valid-jsdoc.js deleted file mode 100644 index 46eb02211a4872..00000000000000 --- a/tools/node_modules/eslint/lib/rules/valid-jsdoc.js +++ /dev/null @@ -1,515 +0,0 @@ -/** - * @fileoverview Validates JSDoc comments are syntactically correct - * @author Nicholas C. Zakas - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const doctrine = require("doctrine"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce valid JSDoc comments", - category: "Possible Errors", - recommended: false, - url: "https://eslint.org/docs/rules/valid-jsdoc" - }, - - schema: [ - { - type: "object", - properties: { - prefer: { - type: "object", - additionalProperties: { - type: "string" - } - }, - preferType: { - type: "object", - additionalProperties: { - type: "string" - } - }, - requireReturn: { - type: "boolean", - default: true - }, - requireParamDescription: { - type: "boolean", - default: true - }, - requireReturnDescription: { - type: "boolean", - default: true - }, - matchDescription: { - type: "string" - }, - requireReturnType: { - type: "boolean", - default: true - }, - requireParamType: { - type: "boolean", - default: true - } - }, - additionalProperties: false - } - ], - - fixable: "code", - messages: { - unexpectedTag: "Unexpected @{{title}} tag; function has no return statement.", - expected: "Expected JSDoc for '{{name}}' but found '{{jsdocName}}'.", - use: "Use @{{name}} instead.", - useType: "Use '{{expectedTypeName}}' instead of '{{currentTypeName}}'.", - syntaxError: "JSDoc syntax error.", - missingBrace: "JSDoc type missing brace.", - missingParamDesc: "Missing JSDoc parameter description for '{{name}}'.", - missingParamType: "Missing JSDoc parameter type for '{{name}}'.", - missingReturnType: "Missing JSDoc return type.", - missingReturnDesc: "Missing JSDoc return description.", - missingReturn: "Missing JSDoc @{{returns}} for function.", - missingParam: "Missing JSDoc for parameter '{{name}}'.", - duplicateParam: "Duplicate JSDoc parameter '{{name}}'.", - unsatisfiedDesc: "JSDoc description does not satisfy the regex pattern." - }, - - deprecated: true, - replacedBy: [] - }, - - create(context) { - - const options = context.options[0] || {}, - prefer = options.prefer || {}, - sourceCode = context.getSourceCode(), - - // these both default to true, so you have to explicitly make them false - requireReturn = options.requireReturn !== false, - requireParamDescription = options.requireParamDescription !== false, - requireReturnDescription = options.requireReturnDescription !== false, - requireReturnType = options.requireReturnType !== false, - requireParamType = options.requireParamType !== false, - preferType = options.preferType || {}, - checkPreferType = Object.keys(preferType).length !== 0; - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - // Using a stack to store if a function returns or not (handling nested functions) - const fns = []; - - /** - * Check if node type is a Class - * @param {ASTNode} node node to check. - * @returns {boolean} True is its a class - * @private - */ - function isTypeClass(node) { - return node.type === "ClassExpression" || node.type === "ClassDeclaration"; - } - - /** - * When parsing a new function, store it in our function stack. - * @param {ASTNode} node A function node to check. - * @returns {void} - * @private - */ - function startFunction(node) { - fns.push({ - returnPresent: (node.type === "ArrowFunctionExpression" && node.body.type !== "BlockStatement") || - isTypeClass(node) || node.async - }); - } - - /** - * Indicate that return has been found in the current function. - * @param {ASTNode} node The return node. - * @returns {void} - * @private - */ - function addReturn(node) { - const functionState = fns[fns.length - 1]; - - if (functionState && node.argument !== null) { - functionState.returnPresent = true; - } - } - - /** - * Check if return tag type is void or undefined - * @param {Object} tag JSDoc tag - * @returns {boolean} True if its of type void or undefined - * @private - */ - function isValidReturnType(tag) { - return tag.type === null || tag.type.name === "void" || tag.type.type === "UndefinedLiteral"; - } - - /** - * Check if type should be validated based on some exceptions - * @param {Object} type JSDoc tag - * @returns {boolean} True if it can be validated - * @private - */ - function canTypeBeValidated(type) { - return type !== "UndefinedLiteral" && // {undefined} as there is no name property available. - type !== "NullLiteral" && // {null} - type !== "NullableLiteral" && // {?} - type !== "FunctionType" && // {function(a)} - type !== "AllLiteral"; // {*} - } - - /** - * Extract the current and expected type based on the input type object - * @param {Object} type JSDoc tag - * @returns {{currentType: Doctrine.Type, expectedTypeName: string}} The current type annotation and - * the expected name of the annotation - * @private - */ - function getCurrentExpectedTypes(type) { - let currentType; - - if (type.name) { - currentType = type; - } else if (type.expression) { - currentType = type.expression; - } - - return { - currentType, - expectedTypeName: currentType && preferType[currentType.name] - }; - } - - /** - * Gets the location of a JSDoc node in a file - * @param {Token} jsdocComment The comment that this node is parsed from - * @param {{range: number[]}} parsedJsdocNode A tag or other node which was parsed from this comment - * @returns {{start: SourceLocation, end: SourceLocation}} The 0-based source location for the tag - */ - function getAbsoluteRange(jsdocComment, parsedJsdocNode) { - return { - start: sourceCode.getLocFromIndex(jsdocComment.range[0] + 2 + parsedJsdocNode.range[0]), - end: sourceCode.getLocFromIndex(jsdocComment.range[0] + 2 + parsedJsdocNode.range[1]) - }; - } - - /** - * Validate type for a given JSDoc node - * @param {Object} jsdocNode JSDoc node - * @param {Object} type JSDoc tag - * @returns {void} - * @private - */ - function validateType(jsdocNode, type) { - if (!type || !canTypeBeValidated(type.type)) { - return; - } - - const typesToCheck = []; - let elements = []; - - switch (type.type) { - case "TypeApplication": // {Array.} - elements = type.applications[0].type === "UnionType" ? type.applications[0].elements : type.applications; - typesToCheck.push(getCurrentExpectedTypes(type)); - break; - case "RecordType": // {{20:String}} - elements = type.fields; - break; - case "UnionType": // {String|number|Test} - case "ArrayType": // {[String, number, Test]} - elements = type.elements; - break; - case "FieldType": // Array.<{count: number, votes: number}> - if (type.value) { - typesToCheck.push(getCurrentExpectedTypes(type.value)); - } - break; - default: - typesToCheck.push(getCurrentExpectedTypes(type)); - } - - elements.forEach(validateType.bind(null, jsdocNode)); - - typesToCheck.forEach(typeToCheck => { - if (typeToCheck.expectedTypeName && - typeToCheck.expectedTypeName !== typeToCheck.currentType.name) { - context.report({ - node: jsdocNode, - messageId: "useType", - loc: getAbsoluteRange(jsdocNode, typeToCheck.currentType), - data: { - currentTypeName: typeToCheck.currentType.name, - expectedTypeName: typeToCheck.expectedTypeName - }, - fix(fixer) { - return fixer.replaceTextRange( - typeToCheck.currentType.range.map(indexInComment => jsdocNode.range[0] + 2 + indexInComment), - typeToCheck.expectedTypeName - ); - } - }); - } - }); - } - - /** - * Validate the JSDoc node and output warnings if anything is wrong. - * @param {ASTNode} node The AST node to check. - * @returns {void} - * @private - */ - function checkJSDoc(node) { - const jsdocNode = sourceCode.getJSDocComment(node), - functionData = fns.pop(), - paramTagsByName = Object.create(null), - paramTags = []; - let hasReturns = false, - returnsTag, - hasConstructor = false, - isInterface = false, - isOverride = false, - isAbstract = false; - - // make sure only to validate JSDoc comments - if (jsdocNode) { - let jsdoc; - - try { - jsdoc = doctrine.parse(jsdocNode.value, { - strict: true, - unwrap: true, - sloppy: true, - range: true - }); - } catch (ex) { - - if (/braces/i.test(ex.message)) { - context.report({ node: jsdocNode, messageId: "missingBrace" }); - } else { - context.report({ node: jsdocNode, messageId: "syntaxError" }); - } - - return; - } - - jsdoc.tags.forEach(tag => { - - switch (tag.title.toLowerCase()) { - - case "param": - case "arg": - case "argument": - paramTags.push(tag); - break; - - case "return": - case "returns": - hasReturns = true; - returnsTag = tag; - break; - - case "constructor": - case "class": - hasConstructor = true; - break; - - case "override": - case "inheritdoc": - isOverride = true; - break; - - case "abstract": - case "virtual": - isAbstract = true; - break; - - case "interface": - isInterface = true; - break; - - // no default - } - - // check tag preferences - if (Object.prototype.hasOwnProperty.call(prefer, tag.title) && tag.title !== prefer[tag.title]) { - const entireTagRange = getAbsoluteRange(jsdocNode, tag); - - context.report({ - node: jsdocNode, - messageId: "use", - loc: { - start: entireTagRange.start, - end: { - line: entireTagRange.start.line, - column: entireTagRange.start.column + `@${tag.title}`.length - } - }, - data: { name: prefer[tag.title] }, - fix(fixer) { - return fixer.replaceTextRange( - [ - jsdocNode.range[0] + tag.range[0] + 3, - jsdocNode.range[0] + tag.range[0] + tag.title.length + 3 - ], - prefer[tag.title] - ); - } - }); - } - - // validate the types - if (checkPreferType && tag.type) { - validateType(jsdocNode, tag.type); - } - }); - - paramTags.forEach(param => { - if (requireParamType && !param.type) { - context.report({ - node: jsdocNode, - messageId: "missingParamType", - loc: getAbsoluteRange(jsdocNode, param), - data: { name: param.name } - }); - } - if (!param.description && requireParamDescription) { - context.report({ - node: jsdocNode, - messageId: "missingParamDesc", - loc: getAbsoluteRange(jsdocNode, param), - data: { name: param.name } - }); - } - if (paramTagsByName[param.name]) { - context.report({ - node: jsdocNode, - messageId: "duplicateParam", - loc: getAbsoluteRange(jsdocNode, param), - data: { name: param.name } - }); - } else if (param.name.indexOf(".") === -1) { - paramTagsByName[param.name] = param; - } - }); - - if (hasReturns) { - if (!requireReturn && !functionData.returnPresent && (returnsTag.type === null || !isValidReturnType(returnsTag)) && !isAbstract) { - context.report({ - node: jsdocNode, - messageId: "unexpectedTag", - loc: getAbsoluteRange(jsdocNode, returnsTag), - data: { - title: returnsTag.title - } - }); - } else { - if (requireReturnType && !returnsTag.type) { - context.report({ node: jsdocNode, messageId: "missingReturnType" }); - } - - if (!isValidReturnType(returnsTag) && !returnsTag.description && requireReturnDescription) { - context.report({ node: jsdocNode, messageId: "missingReturnDesc" }); - } - } - } - - // check for functions missing @returns - if (!isOverride && !hasReturns && !hasConstructor && !isInterface && - node.parent.kind !== "get" && node.parent.kind !== "constructor" && - node.parent.kind !== "set" && !isTypeClass(node)) { - if (requireReturn || (functionData.returnPresent && !node.async)) { - context.report({ - node: jsdocNode, - messageId: "missingReturn", - data: { - returns: prefer.returns || "returns" - } - }); - } - } - - // check the parameters - const jsdocParamNames = Object.keys(paramTagsByName); - - if (node.params) { - node.params.forEach((param, paramsIndex) => { - const bindingParam = param.type === "AssignmentPattern" - ? param.left - : param; - - // TODO(nzakas): Figure out logical things to do with destructured, default, rest params - if (bindingParam.type === "Identifier") { - const name = bindingParam.name; - - if (jsdocParamNames[paramsIndex] && (name !== jsdocParamNames[paramsIndex])) { - context.report({ - node: jsdocNode, - messageId: "expected", - loc: getAbsoluteRange(jsdocNode, paramTagsByName[jsdocParamNames[paramsIndex]]), - data: { - name, - jsdocName: jsdocParamNames[paramsIndex] - } - }); - } else if (!paramTagsByName[name] && !isOverride) { - context.report({ - node: jsdocNode, - messageId: "missingParam", - data: { - name - } - }); - } - } - }); - } - - if (options.matchDescription) { - const regex = new RegExp(options.matchDescription); - - if (!regex.test(jsdoc.description)) { - context.report({ node: jsdocNode, messageId: "unsatisfiedDesc" }); - } - } - - } - - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - ArrowFunctionExpression: startFunction, - FunctionExpression: startFunction, - FunctionDeclaration: startFunction, - ClassExpression: startFunction, - ClassDeclaration: startFunction, - "ArrowFunctionExpression:exit": checkJSDoc, - "FunctionExpression:exit": checkJSDoc, - "FunctionDeclaration:exit": checkJSDoc, - "ClassExpression:exit": checkJSDoc, - "ClassDeclaration:exit": checkJSDoc, - ReturnStatement: addReturn - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/valid-typeof.js b/tools/node_modules/eslint/lib/rules/valid-typeof.js deleted file mode 100644 index 16b2a47d371ca6..00000000000000 --- a/tools/node_modules/eslint/lib/rules/valid-typeof.js +++ /dev/null @@ -1,85 +0,0 @@ -/** - * @fileoverview Ensures that the results of typeof are compared against a valid string - * @author Ian Christian Myers - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "enforce comparing `typeof` expressions against valid strings", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/valid-typeof" - }, - - schema: [ - { - type: "object", - properties: { - requireStringLiterals: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - messages: { - invalidValue: "Invalid typeof comparison value.", - notString: "Typeof comparisons should be to string literals." - } - }, - - create(context) { - - const VALID_TYPES = ["symbol", "undefined", "object", "boolean", "number", "string", "function"], - OPERATORS = ["==", "===", "!=", "!=="]; - - const requireStringLiterals = context.options[0] && context.options[0].requireStringLiterals; - - /** - * Determines whether a node is a typeof expression. - * @param {ASTNode} node The node - * @returns {boolean} `true` if the node is a typeof expression - */ - function isTypeofExpression(node) { - return node.type === "UnaryExpression" && node.operator === "typeof"; - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - - UnaryExpression(node) { - if (isTypeofExpression(node)) { - const parent = context.getAncestors().pop(); - - if (parent.type === "BinaryExpression" && OPERATORS.indexOf(parent.operator) !== -1) { - const sibling = parent.left === node ? parent.right : parent.left; - - if (sibling.type === "Literal" || sibling.type === "TemplateLiteral" && !sibling.expressions.length) { - const value = sibling.type === "Literal" ? sibling.value : sibling.quasis[0].value.cooked; - - if (VALID_TYPES.indexOf(value) === -1) { - context.report({ node: sibling, messageId: "invalidValue" }); - } - } else if (requireStringLiterals && !isTypeofExpression(sibling)) { - context.report({ node: sibling, messageId: "notString" }); - } - } - } - } - - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/vars-on-top.js b/tools/node_modules/eslint/lib/rules/vars-on-top.js deleted file mode 100644 index 92d483b6ecc7e1..00000000000000 --- a/tools/node_modules/eslint/lib/rules/vars-on-top.js +++ /dev/null @@ -1,144 +0,0 @@ -/** - * @fileoverview Rule to enforce var declarations are only at the top of a function. - * @author Danny Fritz - * @author Gyandeep Singh - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require `var` declarations be placed at the top of their containing scope", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/vars-on-top" - }, - - schema: [], - messages: { - top: "All 'var' declarations must be at the top of the function scope." - } - }, - - create(context) { - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * @param {ASTNode} node - any node - * @returns {boolean} whether the given node structurally represents a directive - */ - function looksLikeDirective(node) { - return node.type === "ExpressionStatement" && - node.expression.type === "Literal" && typeof node.expression.value === "string"; - } - - /** - * Check to see if its a ES6 import declaration - * @param {ASTNode} node - any node - * @returns {boolean} whether the given node represents a import declaration - */ - function looksLikeImport(node) { - return node.type === "ImportDeclaration" || node.type === "ImportSpecifier" || - node.type === "ImportDefaultSpecifier" || node.type === "ImportNamespaceSpecifier"; - } - - /** - * Checks whether a given node is a variable declaration or not. - * - * @param {ASTNode} node - any node - * @returns {boolean} `true` if the node is a variable declaration. - */ - function isVariableDeclaration(node) { - return ( - node.type === "VariableDeclaration" || - ( - node.type === "ExportNamedDeclaration" && - node.declaration && - node.declaration.type === "VariableDeclaration" - ) - ); - } - - /** - * Checks whether this variable is on top of the block body - * @param {ASTNode} node - The node to check - * @param {ASTNode[]} statements - collection of ASTNodes for the parent node block - * @returns {boolean} True if var is on top otherwise false - */ - function isVarOnTop(node, statements) { - const l = statements.length; - let i = 0; - - // skip over directives - for (; i < l; ++i) { - if (!looksLikeDirective(statements[i]) && !looksLikeImport(statements[i])) { - break; - } - } - - for (; i < l; ++i) { - if (!isVariableDeclaration(statements[i])) { - return false; - } - if (statements[i] === node) { - return true; - } - } - - return false; - } - - /** - * Checks whether variable is on top at the global level - * @param {ASTNode} node - The node to check - * @param {ASTNode} parent - Parent of the node - * @returns {void} - */ - function globalVarCheck(node, parent) { - if (!isVarOnTop(node, parent.body)) { - context.report({ node, messageId: "top" }); - } - } - - /** - * Checks whether variable is on top at functional block scope level - * @param {ASTNode} node - The node to check - * @param {ASTNode} parent - Parent of the node - * @param {ASTNode} grandParent - Parent of the node's parent - * @returns {void} - */ - function blockScopeVarCheck(node, parent, grandParent) { - if (!(/Function/.test(grandParent.type) && - parent.type === "BlockStatement" && - isVarOnTop(node, parent.body))) { - context.report({ node, messageId: "top" }); - } - } - - //-------------------------------------------------------------------------- - // Public API - //-------------------------------------------------------------------------- - - return { - "VariableDeclaration[kind='var']"(node) { - if (node.parent.type === "ExportNamedDeclaration") { - globalVarCheck(node.parent, node.parent.parent); - } else if (node.parent.type === "Program") { - globalVarCheck(node, node.parent); - } else { - blockScopeVarCheck(node, node.parent, node.parent.parent); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/wrap-iife.js b/tools/node_modules/eslint/lib/rules/wrap-iife.js deleted file mode 100644 index 0e54157f102f7d..00000000000000 --- a/tools/node_modules/eslint/lib/rules/wrap-iife.js +++ /dev/null @@ -1,160 +0,0 @@ -/** - * @fileoverview Rule to flag when IIFE is not wrapped in parens - * @author Ilya Volodin - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "require parentheses around immediate `function` invocations", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/wrap-iife" - }, - - schema: [ - { - enum: ["outside", "inside", "any"] - }, - { - type: "object", - properties: { - functionPrototypeMethods: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - - fixable: "code", - messages: { - wrapInvocation: "Wrap an immediate function invocation in parentheses.", - wrapExpression: "Wrap only the function expression in parens.", - moveInvocation: "Move the invocation into the parens that contain the function." - } - }, - - create(context) { - - const style = context.options[0] || "outside"; - const includeFunctionPrototypeMethods = context.options[1] && context.options[1].functionPrototypeMethods; - - const sourceCode = context.getSourceCode(); - - /** - * Check if the node is wrapped in () - * @param {ASTNode} node node to evaluate - * @returns {boolean} True if it is wrapped - * @private - */ - function wrapped(node) { - return astUtils.isParenthesised(sourceCode, node); - } - - /** - * Get the function node from an IIFE - * @param {ASTNode} node node to evaluate - * @returns {ASTNode} node that is the function expression of the given IIFE, or null if none exist - */ - function getFunctionNodeFromIIFE(node) { - const callee = node.callee; - - if (callee.type === "FunctionExpression") { - return callee; - } - - if (includeFunctionPrototypeMethods && - callee.type === "MemberExpression" && - callee.object.type === "FunctionExpression" && - (astUtils.getStaticPropertyName(callee) === "call" || astUtils.getStaticPropertyName(callee) === "apply") - ) { - return callee.object; - } - - return null; - } - - - return { - CallExpression(node) { - const innerNode = getFunctionNodeFromIIFE(node); - - if (!innerNode) { - return; - } - - const callExpressionWrapped = wrapped(node), - functionExpressionWrapped = wrapped(innerNode); - - if (!callExpressionWrapped && !functionExpressionWrapped) { - context.report({ - node, - messageId: "wrapInvocation", - fix(fixer) { - const nodeToSurround = style === "inside" ? innerNode : node; - - return fixer.replaceText(nodeToSurround, `(${sourceCode.getText(nodeToSurround)})`); - } - }); - } else if (style === "inside" && !functionExpressionWrapped) { - context.report({ - node, - messageId: "wrapExpression", - fix(fixer) { - - /* - * The outer call expression will always be wrapped at this point. - * Replace the range between the end of the function expression and the end of the call expression. - * for example, in `(function(foo) {}(bar))`, the range `(bar))` should get replaced with `)(bar)`. - * Replace the parens from the outer expression, and parenthesize the function expression. - */ - const parenAfter = sourceCode.getTokenAfter(node); - - return fixer.replaceTextRange( - [innerNode.range[1], parenAfter.range[1]], - `)${sourceCode.getText().slice(innerNode.range[1], parenAfter.range[0])}` - ); - } - }); - } else if (style === "outside" && !callExpressionWrapped) { - context.report({ - node, - messageId: "moveInvocation", - fix(fixer) { - - /* - * The inner function expression will always be wrapped at this point. - * It's only necessary to replace the range between the end of the function expression - * and the call expression. For example, in `(function(foo) {})(bar)`, the range `)(bar)` - * should get replaced with `(bar))`. - */ - const parenAfter = sourceCode.getTokenAfter(innerNode); - - return fixer.replaceTextRange( - [parenAfter.range[0], node.range[1]], - `${sourceCode.getText().slice(parenAfter.range[1], node.range[1])})` - ); - } - }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/wrap-regex.js b/tools/node_modules/eslint/lib/rules/wrap-regex.js deleted file mode 100644 index 4ecbcecbbeb0b3..00000000000000 --- a/tools/node_modules/eslint/lib/rules/wrap-regex.js +++ /dev/null @@ -1,59 +0,0 @@ -/** - * @fileoverview Rule to flag when regex literals are not wrapped in parens - * @author Matt DuVall - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "require parenthesis around regex literals", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/wrap-regex" - }, - - schema: [], - fixable: "code", - - messages: { - requireParens: "Wrap the regexp literal in parens to disambiguate the slash." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - return { - - Literal(node) { - const token = sourceCode.getFirstToken(node), - nodeType = token.type; - - if (nodeType === "RegularExpression") { - const beforeToken = sourceCode.getTokenBefore(node); - const afterToken = sourceCode.getTokenAfter(node); - const ancestors = context.getAncestors(); - const grandparent = ancestors[ancestors.length - 1]; - - if (grandparent.type === "MemberExpression" && grandparent.object === node && - !(beforeToken && beforeToken.value === "(" && afterToken && afterToken.value === ")")) { - context.report({ - node, - messageId: "requireParens", - fix: fixer => fixer.replaceText(node, `(${sourceCode.getText(node)})`) - }); - } - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/yield-star-spacing.js b/tools/node_modules/eslint/lib/rules/yield-star-spacing.js deleted file mode 100644 index 17124dd6ec7c7d..00000000000000 --- a/tools/node_modules/eslint/lib/rules/yield-star-spacing.js +++ /dev/null @@ -1,127 +0,0 @@ -/** - * @fileoverview Rule to check the spacing around the * in yield* expressions. - * @author Bryan Smith - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "require or disallow spacing around the `*` in `yield*` expressions", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/yield-star-spacing" - }, - - fixable: "whitespace", - - schema: [ - { - oneOf: [ - { - enum: ["before", "after", "both", "neither"] - }, - { - type: "object", - properties: { - before: { type: "boolean", default: false }, - after: { type: "boolean", default: true } - }, - additionalProperties: false - } - ] - } - ], - messages: { - missingBefore: "Missing space before *.", - missingAfter: "Missing space after *.", - unexpectedBefore: "Unexpected space before *.", - unexpectedAfter: "Unexpected space after *." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - const mode = (function(option) { - if (!option || typeof option === "string") { - return { - before: { before: true, after: false }, - after: { before: false, after: true }, - both: { before: true, after: true }, - neither: { before: false, after: false } - }[option || "after"]; - } - return option; - }(context.options[0])); - - /** - * Checks the spacing between two tokens before or after the star token. - * @param {string} side Either "before" or "after". - * @param {Token} leftToken `function` keyword token if side is "before", or - * star token if side is "after". - * @param {Token} rightToken Star token if side is "before", or identifier - * token if side is "after". - * @returns {void} - */ - function checkSpacing(side, leftToken, rightToken) { - if (sourceCode.isSpaceBetweenTokens(leftToken, rightToken) !== mode[side]) { - const after = leftToken.value === "*"; - const spaceRequired = mode[side]; - const node = after ? leftToken : rightToken; - let messageId = ""; - - if (spaceRequired) { - messageId = side === "before" ? "missingBefore" : "missingAfter"; - } else { - messageId = side === "before" ? "unexpectedBefore" : "unexpectedAfter"; - } - - context.report({ - node, - messageId, - fix(fixer) { - if (spaceRequired) { - if (after) { - return fixer.insertTextAfter(node, " "); - } - return fixer.insertTextBefore(node, " "); - } - return fixer.removeRange([leftToken.range[1], rightToken.range[0]]); - } - }); - } - } - - /** - * Enforces the spacing around the star if node is a yield* expression. - * @param {ASTNode} node A yield expression node. - * @returns {void} - */ - function checkExpression(node) { - if (!node.delegate) { - return; - } - - const tokens = sourceCode.getFirstTokens(node, 3); - const yieldToken = tokens[0]; - const starToken = tokens[1]; - const nextToken = tokens[2]; - - checkSpacing("before", yieldToken, starToken); - checkSpacing("after", starToken, nextToken); - } - - return { - YieldExpression: checkExpression - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/yoda.js b/tools/node_modules/eslint/lib/rules/yoda.js deleted file mode 100644 index 825634a79f6899..00000000000000 --- a/tools/node_modules/eslint/lib/rules/yoda.js +++ /dev/null @@ -1,318 +0,0 @@ -/** - * @fileoverview Rule to require or disallow yoda comparisons - * @author Nicholas C. Zakas - */ -"use strict"; - -//-------------------------------------------------------------------------- -// Requirements -//-------------------------------------------------------------------------- - -const astUtils = require("../util/ast-utils"); - -//-------------------------------------------------------------------------- -// Helpers -//-------------------------------------------------------------------------- - -/** - * Determines whether an operator is a comparison operator. - * @param {string} operator The operator to check. - * @returns {boolean} Whether or not it is a comparison operator. - */ -function isComparisonOperator(operator) { - return (/^(==|===|!=|!==|<|>|<=|>=)$/).test(operator); -} - -/** - * Determines whether an operator is an equality operator. - * @param {string} operator The operator to check. - * @returns {boolean} Whether or not it is an equality operator. - */ -function isEqualityOperator(operator) { - return (/^(==|===)$/).test(operator); -} - -/** - * Determines whether an operator is one used in a range test. - * Allowed operators are `<` and `<=`. - * @param {string} operator The operator to check. - * @returns {boolean} Whether the operator is used in range tests. - */ -function isRangeTestOperator(operator) { - return ["<", "<="].indexOf(operator) >= 0; -} - -/** - * Determines whether a non-Literal node is a negative number that should be - * treated as if it were a single Literal node. - * @param {ASTNode} node Node to test. - * @returns {boolean} True if the node is a negative number that looks like a - * real literal and should be treated as such. - */ -function looksLikeLiteral(node) { - return (node.type === "UnaryExpression" && - node.operator === "-" && - node.prefix && - node.argument.type === "Literal" && - typeof node.argument.value === "number"); -} - -/** - * Attempts to derive a Literal node from nodes that are treated like literals. - * @param {ASTNode} node Node to normalize. - * @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, defaultValue) { - if (node.type === "Literal") { - return node; - } - - if (looksLikeLiteral(node)) { - return { - type: "Literal", - value: -node.argument.value, - raw: `-${node.argument.value}` - }; - } - - if (defaultValue) { - return { - type: "Literal", - value: defaultValue, - raw: String(defaultValue) - }; - } - - return null; -} - -/** - * Checks whether two expressions reference the same value. For example: - * a = a - * a.b = a.b - * a[0] = a[0] - * a['b'] = a['b'] - * @param {ASTNode} a Left side of the comparison. - * @param {ASTNode} b Right side of the comparison. - * @returns {boolean} True if both sides match and reference the same value. - */ -function same(a, b) { - if (a.type !== b.type) { - return false; - } - - switch (a.type) { - case "Identifier": - return a.name === b.name; - - case "Literal": - return a.value === b.value; - - 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 ( - a.computed === b.computed && - same(a.object, b.object) && - same(a.property, b.property) - ); - } - - case "ThisExpression": - return true; - - default: - return false; - } -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require or disallow \"Yoda\" conditions", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/yoda" - }, - - schema: [ - { - enum: ["always", "never"] - }, - { - type: "object", - properties: { - exceptRange: { - type: "boolean", - default: false - }, - onlyEquality: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - - fixable: "code", - messages: { - expected: "Expected literal to be on the {{expectedSide}} side of {{operator}}." - } - }, - - create(context) { - - // Default to "never" (!always) if no option - const always = (context.options[0] === "always"); - const exceptRange = (context.options[1] && context.options[1].exceptRange); - const onlyEquality = (context.options[1] && context.options[1].onlyEquality); - - const sourceCode = context.getSourceCode(); - - /** - * Determines whether node represents a range test. - * A range test is a "between" test like `(0 <= x && x < 1)` or an "outside" - * test like `(x < 0 || 1 <= x)`. It must be wrapped in parentheses, and - * both operators must be `<` or `<=`. Finally, the literal on the left side - * must be less than or equal to the literal on the right side so that the - * test makes any sense. - * @param {ASTNode} node LogicalExpression node to test. - * @returns {boolean} Whether node is a range test. - */ - function isRangeTest(node) { - const left = node.left, - right = node.right; - - /** - * Determines whether node is of the form `0 <= x && x < 1`. - * @returns {boolean} Whether node is a "between" range test. - */ - function isBetweenTest() { - let leftLiteral, rightLiteral; - - return (node.operator === "&&" && - (leftLiteral = getNormalizedLiteral(left.left)) && - (rightLiteral = getNormalizedLiteral(right.right, Number.POSITIVE_INFINITY)) && - leftLiteral.value <= rightLiteral.value && - same(left.right, right.left)); - } - - /** - * Determines whether node is of the form `x < 0 || 1 <= x`. - * @returns {boolean} Whether node is an "outside" range test. - */ - function isOutsideTest() { - let leftLiteral, rightLiteral; - - return (node.operator === "||" && - (leftLiteral = getNormalizedLiteral(left.right, Number.NEGATIVE_INFINITY)) && - (rightLiteral = getNormalizedLiteral(right.left)) && - leftLiteral.value <= rightLiteral.value && - same(left.left, right.right)); - } - - /** - * Determines whether node is wrapped in parentheses. - * @returns {boolean} Whether node is preceded immediately by an open - * paren token and followed immediately by a close - * paren token. - */ - function isParenWrapped() { - return astUtils.isParenthesised(sourceCode, node); - } - - return (node.type === "LogicalExpression" && - left.type === "BinaryExpression" && - right.type === "BinaryExpression" && - isRangeTestOperator(left.operator) && - isRangeTestOperator(right.operator) && - (isBetweenTest() || isOutsideTest()) && - isParenWrapped()); - } - - const OPERATOR_FLIP_MAP = { - "===": "===", - "!==": "!==", - "==": "==", - "!=": "!=", - "<": ">", - ">": "<", - "<=": ">=", - ">=": "<=" - }; - - /** - * Returns a string representation of a BinaryExpression node with its sides/operator flipped around. - * @param {ASTNode} node The BinaryExpression node - * @returns {string} A string representation of the node with the sides and operator flipped - */ - function getFlippedString(node) { - const operatorToken = sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator); - const textBeforeOperator = sourceCode.getText().slice(sourceCode.getTokenBefore(operatorToken).range[1], operatorToken.range[0]); - const textAfterOperator = sourceCode.getText().slice(operatorToken.range[1], sourceCode.getTokenAfter(operatorToken).range[0]); - const leftText = sourceCode.getText().slice(node.range[0], sourceCode.getTokenBefore(operatorToken).range[1]); - const rightText = sourceCode.getText().slice(sourceCode.getTokenAfter(operatorToken).range[0], node.range[1]); - - return rightText + textBeforeOperator + OPERATOR_FLIP_MAP[operatorToken.value] + textAfterOperator + leftText; - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - BinaryExpression(node) { - const expectedLiteral = always ? node.left : node.right; - const expectedNonLiteral = always ? node.right : node.left; - - // If `expectedLiteral` is not a literal, and `expectedNonLiteral` is a literal, raise an error. - if ( - (expectedNonLiteral.type === "Literal" || looksLikeLiteral(expectedNonLiteral)) && - !(expectedLiteral.type === "Literal" || looksLikeLiteral(expectedLiteral)) && - !(!isEqualityOperator(node.operator) && onlyEquality) && - isComparisonOperator(node.operator) && - !(exceptRange && isRangeTest(context.getAncestors().pop())) - ) { - context.report({ - node, - messageId: "expected", - data: { - operator: node.operator, - expectedSide: always ? "left" : "right" - }, - fix: fixer => fixer.replaceText(node, getFlippedString(node)) - }); - } - - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/testers/rule-tester.js b/tools/node_modules/eslint/lib/testers/rule-tester.js deleted file mode 100644 index 6d1bba989fdeea..00000000000000 --- a/tools/node_modules/eslint/lib/testers/rule-tester.js +++ /dev/null @@ -1,602 +0,0 @@ -/** - * @fileoverview Mocha test wrapper - * @author Ilya Volodin - */ -"use strict"; - -/* global describe, it */ - -/* - * This is a wrapper around mocha to allow for DRY unittests for eslint - * Format: - * RuleTester.run("{ruleName}", { - * valid: [ - * "{code}", - * { code: "{code}", options: {options}, globals: {globals}, parser: "{parser}", settings: {settings} } - * ], - * invalid: [ - * { code: "{code}", errors: {numErrors} }, - * { code: "{code}", errors: ["{errorMessage}"] }, - * { code: "{code}", options: {options}, globals: {globals}, parser: "{parser}", settings: {settings}, errors: [{ message: "{errorMessage}", type: "{errorNodeType}"}] } - * ] - * }); - * - * Variables: - * {code} - String that represents the code to be tested - * {options} - Arguments that are passed to the configurable rules. - * {globals} - An object representing a list of variables that are - * registered as globals - * {parser} - String representing the parser to use - * {settings} - An object representing global settings for all rules - * {numErrors} - If failing case doesn't need to check error message, - * this integer will specify how many errors should be - * received - * {errorMessage} - Message that is returned by the rule on failure - * {errorNodeType} - AST node type that is returned by they rule as - * a cause of the failure. - */ - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const lodash = require("lodash"), - assert = require("assert"), - util = require("util"), - validator = require("../config/config-validator"), - ajv = require("../util/ajv"), - Linter = require("../linter"), - Environments = require("../config/environments"), - SourceCodeFixer = require("../util/source-code-fixer"), - interpolate = require("../util/interpolate"); - -//------------------------------------------------------------------------------ -// Private Members -//------------------------------------------------------------------------------ - -/* - * testerDefaultConfig must not be modified as it allows to reset the tester to - * the initial default configuration - */ -const testerDefaultConfig = { rules: {} }; -let defaultConfig = { rules: {} }; - -/* - * List every parameters possible on a test case that are not related to eslint - * configuration - */ -const RuleTesterParameters = [ - "code", - "filename", - "options", - "errors", - "output" -]; - -const hasOwnProperty = Function.call.bind(Object.hasOwnProperty); - -/** - * Clones a given value deeply. - * Note: This ignores `parent` property. - * - * @param {any} x - A value to clone. - * @returns {any} A cloned value. - */ -function cloneDeeplyExcludesParent(x) { - if (typeof x === "object" && x !== null) { - if (Array.isArray(x)) { - return x.map(cloneDeeplyExcludesParent); - } - - const retv = {}; - - for (const key in x) { - if (key !== "parent" && hasOwnProperty(x, key)) { - retv[key] = cloneDeeplyExcludesParent(x[key]); - } - } - - return retv; - } - - return x; -} - -/** - * Freezes a given value deeply. - * - * @param {any} x - A value to freeze. - * @returns {void} - */ -function freezeDeeply(x) { - if (typeof x === "object" && x !== null) { - if (Array.isArray(x)) { - x.forEach(freezeDeeply); - } else { - for (const key in x) { - if (key !== "parent" && hasOwnProperty(x, key)) { - freezeDeeply(x[key]); - } - } - } - Object.freeze(x); - } -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -// default separators for testing -const DESCRIBE = Symbol("describe"); -const IT = Symbol("it"); - -/** - * This is `it` default handler if `it` don't exist. - * @this {Mocha} - * @param {string} text - The description of the test case. - * @param {Function} method - The logic of the test case. - * @returns {any} Returned value of `method`. - */ -function itDefaultHandler(text, method) { - try { - return method.call(this); - } catch (err) { - if (err instanceof assert.AssertionError) { - err.message += ` (${util.inspect(err.actual)} ${err.operator} ${util.inspect(err.expected)})`; - } - throw err; - } -} - -/** - * This is `describe` default handler if `describe` don't exist. - * @this {Mocha} - * @param {string} text - The description of the test case. - * @param {Function} method - The logic of the test case. - * @returns {any} Returned value of `method`. - */ -function describeDefaultHandler(text, method) { - return method.call(this); -} - -class RuleTester { - - /** - * Creates a new instance of RuleTester. - * @param {Object} [testerConfig] Optional, extra configuration for the tester - * @constructor - */ - constructor(testerConfig) { - - /** - * The configuration to use for this tester. Combination of the tester - * configuration and the default configuration. - * @type {Object} - */ - this.testerConfig = lodash.merge( - - // we have to clone because merge uses the first argument for recipient - lodash.cloneDeep(defaultConfig), - testerConfig, - { rules: { "rule-tester/validate-ast": "error" } } - ); - - /** - * Rule definitions to define before tests. - * @type {Object} - */ - this.rules = {}; - this.linter = new Linter(); - } - - /** - * Set the configuration to use for all future tests - * @param {Object} config the configuration to use. - * @returns {void} - */ - static setDefaultConfig(config) { - if (typeof config !== "object") { - throw new TypeError("RuleTester.setDefaultConfig: config must be an object"); - } - defaultConfig = config; - - // Make sure the rules object exists since it is assumed to exist later - defaultConfig.rules = defaultConfig.rules || {}; - } - - /** - * Get the current configuration used for all tests - * @returns {Object} the current configuration - */ - static getDefaultConfig() { - return defaultConfig; - } - - /** - * Reset the configuration to the initial configuration of the tester removing - * any changes made until now. - * @returns {void} - */ - static resetDefaultConfig() { - defaultConfig = lodash.cloneDeep(testerDefaultConfig); - } - - - /* - * If people use `mocha test.js --watch` command, `describe` and `it` function - * instances are different for each execution. So `describe` and `it` should get fresh instance - * always. - */ - static get describe() { - return ( - this[DESCRIBE] || - (typeof describe === "function" ? describe : describeDefaultHandler) - ); - } - - static set describe(value) { - this[DESCRIBE] = value; - } - - static get it() { - return ( - this[IT] || - (typeof it === "function" ? it : itDefaultHandler) - ); - } - - static set it(value) { - this[IT] = value; - } - - /** - * Define a rule for one particular run of tests. - * @param {string} name The name of the rule to define. - * @param {Function} rule The rule definition. - * @returns {void} - */ - defineRule(name, rule) { - this.rules[name] = rule; - } - - /** - * Adds a new rule test to execute. - * @param {string} ruleName The name of the rule to run. - * @param {Function} rule The rule to test. - * @param {Object} test The collection of tests to run. - * @returns {void} - */ - run(ruleName, rule, test) { - - const testerConfig = this.testerConfig, - requiredScenarios = ["valid", "invalid"], - scenarioErrors = [], - linter = this.linter; - - if (lodash.isNil(test) || typeof test !== "object") { - throw new TypeError(`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")); - } - - - linter.defineRule(ruleName, Object.assign({}, rule, { - - // Create a wrapper rule that freezes the `context` properties. - create(context) { - freezeDeeply(context.options); - freezeDeeply(context.settings); - freezeDeeply(context.parserOptions); - - return (typeof rule === "function" ? rule : rule.create)(context); - } - })); - - linter.defineRules(this.rules); - - const ruleMap = linter.getRules(); - - /** - * Run the rule for the given item - * @param {string|Object} item Item to run the rule against - * @returns {Object} Eslint run result - * @private - */ - function runRuleForItem(item) { - let config = lodash.cloneDeep(testerConfig), - code, filename, beforeAST, afterAST; - - if (typeof item === "string") { - code = item; - } else { - code = item.code; - - /* - * Assumes everything on the item is a config except for the - * parameters used by this tester - */ - const itemConfig = lodash.omit(item, RuleTesterParameters); - - /* - * Create the config object from the tester config and this item - * specific configurations. - */ - config = lodash.merge( - config, - itemConfig - ); - } - - if (item.filename) { - filename = item.filename; - } - - if (Object.prototype.hasOwnProperty.call(item, "options")) { - assert(Array.isArray(item.options), "options must be an array"); - config.rules[ruleName] = [1].concat(item.options); - } else { - config.rules[ruleName] = 1; - } - - const schema = validator.getRuleOptionsSchema(rule); - - /* - * Setup AST getters. - * The goal is to check whether or not AST was modified when - * running the rule under test. - */ - linter.defineRule("rule-tester/validate-ast", () => ({ - Program(node) { - beforeAST = cloneDeeplyExcludesParent(node); - }, - "Program:exit"(node) { - afterAST = node; - } - })); - - if (schema) { - ajv.validateSchema(schema); - - if (ajv.errors) { - const errors = ajv.errors.map(error => { - const field = error.dataPath[0] === "." ? error.dataPath.slice(1) : error.dataPath; - - return `\t${field}: ${error.message}`; - }).join("\n"); - - throw new Error([`Schema for rule ${ruleName} is invalid:`, errors]); - } - } - - validator.validate(config, "rule-tester", ruleMap.get.bind(ruleMap), new Environments()); - - return { - messages: linter.verify(code, config, filename, true), - beforeAST, - afterAST: cloneDeeplyExcludesParent(afterAST) - }; - } - - /** - * Check if the AST was changed - * @param {ASTNode} beforeAST AST node before running - * @param {ASTNode} afterAST AST node after running - * @returns {void} - * @private - */ - function assertASTDidntChange(beforeAST, afterAST) { - if (!lodash.isEqual(beforeAST, afterAST)) { - assert.fail("Rule should not modify AST."); - } - } - - /** - * Check if the template is valid or not - * all valid cases go through this - * @param {string|Object} item Item to run the rule against - * @returns {void} - * @private - */ - function testValidTemplate(item) { - const result = runRuleForItem(item); - const messages = result.messages; - - assert.strictEqual(messages.length, 0, util.format("Should have no errors but had %d: %s", - messages.length, util.inspect(messages))); - - assertASTDidntChange(result.beforeAST, result.afterAST); - } - - /** - * Asserts that the message matches its expected value. If the expected - * value is a regular expression, it is checked against the actual - * value. - * @param {string} actual Actual value - * @param {string|RegExp} expected Expected value - * @returns {void} - * @private - */ - function assertMessageMatches(actual, expected) { - if (expected instanceof RegExp) { - - // assert.js doesn't have a built-in RegExp match function - assert.ok( - expected.test(actual), - `Expected '${actual}' to match ${expected}` - ); - } else { - assert.strictEqual(actual, expected); - } - } - - /** - * Check if the template is invalid or not - * all invalid cases go through this. - * @param {string|Object} item Item to run the rule against - * @returns {void} - * @private - */ - function testInvalidTemplate(item) { - assert.ok(item.errors || item.errors === 0, - `Did not specify errors for an invalid test of ${ruleName}`); - - const result = runRuleForItem(item); - const messages = result.messages; - - - if (typeof item.errors === "number") { - assert.strictEqual(messages.length, item.errors, util.format("Should have %d error%s but had %d: %s", - item.errors, item.errors === 1 ? "" : "s", messages.length, util.inspect(messages))); - } else { - assert.strictEqual( - messages.length, item.errors.length, - util.format( - "Should have %d error%s but had %d: %s", - item.errors.length, item.errors.length === 1 ? "" : "s", messages.length, util.inspect(messages) - ) - ); - - const hasMessageOfThisRule = messages.some(m => m.ruleId === ruleName); - - for (let i = 0, l = item.errors.length; i < l; i++) { - const error = item.errors[i]; - const message = messages[i]; - - assert(!message.fatal, `A fatal parsing error occurred: ${message.message}`); - assert(hasMessageOfThisRule, "Error rule name should be the same as the name of the rule being tested"); - - if (typeof error === "string" || error instanceof RegExp) { - - // Just an error message. - assertMessageMatches(message.message, error); - } else if (typeof error === "object") { - - /* - * Error object. - * This may have a message, messageId, data, node type, line, and/or - * column. - */ - if (hasOwnProperty(error, "message")) { - assert.ok(!hasOwnProperty(error, "messageId"), "Error should not specify both 'message' and a 'messageId'."); - assert.ok(!hasOwnProperty(error, "data"), "Error should not specify both 'data' and 'message'."); - assertMessageMatches(message.message, error.message); - } else if (hasOwnProperty(error, "messageId")) { - assert.ok( - hasOwnProperty(rule, "meta") && hasOwnProperty(rule.meta, "messages"), - "Error can not use 'messageId' if rule under test doesn't define 'meta.messages'." - ); - if (!hasOwnProperty(rule.meta.messages, error.messageId)) { - const friendlyIDList = `[${Object.keys(rule.meta.messages).map(key => `'${key}'`).join(", ")}]`; - - assert(false, `Invalid messageId '${error.messageId}'. Expected one of ${friendlyIDList}.`); - } - assert.strictEqual( - error.messageId, - message.messageId, - `messageId '${message.messageId}' does not match expected messageId '${error.messageId}'.` - ); - if (hasOwnProperty(error, "data")) { - - /* - * if data was provided, then directly compare the returned message to a synthetic - * interpolated message using the same message ID and data provided in the test. - * See https://github.com/eslint/eslint/issues/9890 for context. - */ - const unformattedOriginalMessage = rule.meta.messages[error.messageId]; - const rehydratedMessage = interpolate(unformattedOriginalMessage, error.data); - - assert.strictEqual( - message.message, - rehydratedMessage, - `Hydrated message "${rehydratedMessage}" does not match "${message.message}"` - ); - } - } - - assert.ok( - hasOwnProperty(error, "data") ? hasOwnProperty(error, "messageId") : true, - "Error must specify 'messageId' if 'data' is used." - ); - - if (error.type) { - assert.strictEqual(message.nodeType, error.type, `Error type should be ${error.type}, found ${message.nodeType}`); - } - - if (Object.prototype.hasOwnProperty.call(error, "line")) { - assert.strictEqual(message.line, error.line, `Error line should be ${error.line}`); - } - - if (Object.prototype.hasOwnProperty.call(error, "column")) { - assert.strictEqual(message.column, error.column, `Error column should be ${error.column}`); - } - - if (Object.prototype.hasOwnProperty.call(error, "endLine")) { - assert.strictEqual(message.endLine, error.endLine, `Error endLine should be ${error.endLine}`); - } - - if (Object.prototype.hasOwnProperty.call(error, "endColumn")) { - assert.strictEqual(message.endColumn, error.endColumn, `Error endColumn should be ${error.endColumn}`); - } - } else { - - // Message was an unexpected type - assert.fail(`Error should be a string, object, or RegExp, but found (${util.inspect(message)})`); - } - } - } - - if (Object.prototype.hasOwnProperty.call(item, "output")) { - if (item.output === null) { - assert.strictEqual( - messages.filter(message => message.fix).length, - 0, - "Expected no autofixes to be suggested" - ); - } else { - const fixResult = SourceCodeFixer.applyFixes(item.code, messages); - - assert.strictEqual(fixResult.output, item.output, "Output is incorrect."); - } - } - - assertASTDidntChange(result.beforeAST, result.afterAST); - } - - /* - * This creates a mocha test suite and pipes all supplied info through - * one of the templates above. - */ - RuleTester.describe(ruleName, () => { - RuleTester.describe("valid", () => { - test.valid.forEach(valid => { - RuleTester.it(typeof valid === "object" ? valid.code : valid, () => { - testValidTemplate(valid); - }); - }); - }); - - RuleTester.describe("invalid", () => { - test.invalid.forEach(invalid => { - RuleTester.it(invalid.code, () => { - testInvalidTemplate(invalid); - }); - }); - }); - }); - } -} - -RuleTester[DESCRIBE] = RuleTester[IT] = null; - -module.exports = RuleTester; diff --git a/tools/node_modules/eslint/lib/token-store/backward-token-comment-cursor.js b/tools/node_modules/eslint/lib/token-store/backward-token-comment-cursor.js deleted file mode 100644 index 7c2137a176ff21..00000000000000 --- a/tools/node_modules/eslint/lib/token-store/backward-token-comment-cursor.js +++ /dev/null @@ -1,57 +0,0 @@ -/** - * @fileoverview Define the cursor which iterates tokens and comments in reverse. - * @author Toru Nagashima - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const Cursor = require("./cursor"); -const utils = require("./utils"); - -//------------------------------------------------------------------------------ -// Exports -//------------------------------------------------------------------------------ - -/** - * The cursor which iterates tokens and comments in reverse. - */ -module.exports = class BackwardTokenCommentCursor extends Cursor { - - /** - * Initializes this cursor. - * @param {Token[]} tokens - The array of tokens. - * @param {Comment[]} comments - The array of comments. - * @param {Object} indexMap - The map from locations to indices in `tokens`. - * @param {number} startLoc - The start location of the iteration range. - * @param {number} endLoc - The end location of the iteration range. - */ - constructor(tokens, comments, indexMap, startLoc, endLoc) { - super(); - this.tokens = tokens; - this.comments = comments; - this.tokenIndex = utils.getLastIndex(tokens, indexMap, endLoc); - this.commentIndex = utils.search(comments, endLoc) - 1; - this.border = startLoc; - } - - /** @inheritdoc */ - moveNext() { - const token = (this.tokenIndex >= 0) ? this.tokens[this.tokenIndex] : null; - const comment = (this.commentIndex >= 0) ? this.comments[this.commentIndex] : null; - - if (token && (!comment || token.range[1] > comment.range[1])) { - this.current = token; - this.tokenIndex -= 1; - } else if (comment) { - this.current = comment; - this.commentIndex -= 1; - } else { - this.current = null; - } - - return Boolean(this.current) && (this.border === -1 || this.current.range[0] >= this.border); - } -}; diff --git a/tools/node_modules/eslint/lib/token-store/backward-token-cursor.js b/tools/node_modules/eslint/lib/token-store/backward-token-cursor.js deleted file mode 100644 index 93973bce443df7..00000000000000 --- a/tools/node_modules/eslint/lib/token-store/backward-token-cursor.js +++ /dev/null @@ -1,58 +0,0 @@ -/** - * @fileoverview Define the cursor which iterates tokens only in reverse. - * @author Toru Nagashima - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const Cursor = require("./cursor"); -const utils = require("./utils"); - -//------------------------------------------------------------------------------ -// Exports -//------------------------------------------------------------------------------ - -/** - * The cursor which iterates tokens only in reverse. - */ -module.exports = class BackwardTokenCursor extends Cursor { - - /** - * Initializes this cursor. - * @param {Token[]} tokens - The array of tokens. - * @param {Comment[]} comments - The array of comments. - * @param {Object} indexMap - The map from locations to indices in `tokens`. - * @param {number} startLoc - The start location of the iteration range. - * @param {number} endLoc - The end location of the iteration range. - */ - constructor(tokens, comments, indexMap, startLoc, endLoc) { - super(); - this.tokens = tokens; - this.index = utils.getLastIndex(tokens, indexMap, endLoc); - this.indexEnd = utils.getFirstIndex(tokens, indexMap, startLoc); - } - - /** @inheritdoc */ - moveNext() { - if (this.index >= this.indexEnd) { - this.current = this.tokens[this.index]; - this.index -= 1; - return true; - } - return false; - } - - /* - * - * Shorthand for performance. - * - */ - - /** @inheritdoc */ - getOneToken() { - return (this.index >= this.indexEnd) ? this.tokens[this.index] : null; - } -}; diff --git a/tools/node_modules/eslint/lib/token-store/cursor.js b/tools/node_modules/eslint/lib/token-store/cursor.js deleted file mode 100644 index 4e1595c6dcb8a3..00000000000000 --- a/tools/node_modules/eslint/lib/token-store/cursor.js +++ /dev/null @@ -1,76 +0,0 @@ -/** - * @fileoverview Define the abstract class about cursors which iterate tokens. - * @author Toru Nagashima - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Exports -//------------------------------------------------------------------------------ - -/** - * The abstract class about cursors which iterate tokens. - * - * This class has 2 abstract methods. - * - * - `current: Token | Comment | null` ... The current token. - * - `moveNext(): boolean` ... Moves this cursor to the next token. If the next token didn't exist, it returns `false`. - * - * This is similar to ES2015 Iterators. - * However, Iterators were slow (at 2017-01), so I created this class as similar to C# IEnumerable. - * - * There are the following known sub classes. - * - * - ForwardTokenCursor .......... The cursor which iterates tokens only. - * - BackwardTokenCursor ......... The cursor which iterates tokens only in reverse. - * - ForwardTokenCommentCursor ... The cursor which iterates tokens and comments. - * - BackwardTokenCommentCursor .. The cursor which iterates tokens and comments in reverse. - * - DecorativeCursor - * - FilterCursor ............ The cursor which ignores the specified tokens. - * - SkipCursor .............. The cursor which ignores the first few tokens. - * - LimitCursor ............. The cursor which limits the count of tokens. - * - */ -module.exports = class Cursor { - - /** - * Initializes this cursor. - */ - constructor() { - this.current = null; - } - - /** - * Gets the first token. - * This consumes this cursor. - * @returns {Token|Comment} The first token or null. - */ - getOneToken() { - return this.moveNext() ? this.current : null; - } - - /** - * Gets the first tokens. - * This consumes this cursor. - * @returns {(Token|Comment)[]} All tokens. - */ - getAllTokens() { - const tokens = []; - - while (this.moveNext()) { - tokens.push(this.current); - } - - return tokens; - } - - /** - * Moves this cursor to the next token. - * @returns {boolean} `true` if the next token exists. - * @abstract - */ - /* istanbul ignore next */ - moveNext() { // eslint-disable-line class-methods-use-this - throw new Error("Not implemented."); - } -}; diff --git a/tools/node_modules/eslint/lib/token-store/cursors.js b/tools/node_modules/eslint/lib/token-store/cursors.js deleted file mode 100644 index b315c7e65e1a7c..00000000000000 --- a/tools/node_modules/eslint/lib/token-store/cursors.js +++ /dev/null @@ -1,92 +0,0 @@ -/** - * @fileoverview Define 2 token factories; forward and backward. - * @author Toru Nagashima - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const BackwardTokenCommentCursor = require("./backward-token-comment-cursor"); -const BackwardTokenCursor = require("./backward-token-cursor"); -const FilterCursor = require("./filter-cursor"); -const ForwardTokenCommentCursor = require("./forward-token-comment-cursor"); -const ForwardTokenCursor = require("./forward-token-cursor"); -const LimitCursor = require("./limit-cursor"); -const SkipCursor = require("./skip-cursor"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * The cursor factory. - * @private - */ -class CursorFactory { - - /** - * Initializes this cursor. - * @param {Function} TokenCursor - The class of the cursor which iterates tokens only. - * @param {Function} TokenCommentCursor - The class of the cursor which iterates the mix of tokens and comments. - */ - constructor(TokenCursor, TokenCommentCursor) { - this.TokenCursor = TokenCursor; - this.TokenCommentCursor = TokenCommentCursor; - } - - /** - * Creates a base cursor instance that can be decorated by createCursor. - * - * @param {Token[]} tokens - The array of tokens. - * @param {Comment[]} comments - The array of comments. - * @param {Object} indexMap - The map from locations to indices in `tokens`. - * @param {number} startLoc - The start location of the iteration range. - * @param {number} endLoc - The end location of the iteration range. - * @param {boolean} includeComments - The flag to iterate comments as well. - * @returns {Cursor} The created base cursor. - */ - createBaseCursor(tokens, comments, indexMap, startLoc, endLoc, includeComments) { - const Cursor = includeComments ? this.TokenCommentCursor : this.TokenCursor; - - return new Cursor(tokens, comments, indexMap, startLoc, endLoc); - } - - /** - * Creates a cursor that iterates tokens with normalized options. - * - * @param {Token[]} tokens - The array of tokens. - * @param {Comment[]} comments - The array of comments. - * @param {Object} indexMap - The map from locations to indices in `tokens`. - * @param {number} startLoc - The start location of the iteration range. - * @param {number} endLoc - The end location of the iteration range. - * @param {boolean} includeComments - The flag to iterate comments as well. - * @param {Function|null} filter - The predicate function to choose tokens. - * @param {number} skip - The count of tokens the cursor skips. - * @param {number} count - The maximum count of tokens the cursor iterates. Zero is no iteration for backward compatibility. - * @returns {Cursor} The created cursor. - */ - createCursor(tokens, comments, indexMap, startLoc, endLoc, includeComments, filter, skip, count) { - let cursor = this.createBaseCursor(tokens, comments, indexMap, startLoc, endLoc, includeComments); - - if (filter) { - cursor = new FilterCursor(cursor, filter); - } - if (skip >= 1) { - cursor = new SkipCursor(cursor, skip); - } - if (count >= 0) { - cursor = new LimitCursor(cursor, count); - } - - return cursor; - } -} - -//------------------------------------------------------------------------------ -// Exports -//------------------------------------------------------------------------------ - -exports.forward = new CursorFactory(ForwardTokenCursor, ForwardTokenCommentCursor); -exports.backward = new CursorFactory(BackwardTokenCursor, BackwardTokenCommentCursor); diff --git a/tools/node_modules/eslint/lib/token-store/decorative-cursor.js b/tools/node_modules/eslint/lib/token-store/decorative-cursor.js deleted file mode 100644 index f0bff9c51dba76..00000000000000 --- a/tools/node_modules/eslint/lib/token-store/decorative-cursor.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * @fileoverview Define the abstract class about cursors which manipulate another cursor. - * @author Toru Nagashima - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const Cursor = require("./cursor"); - -//------------------------------------------------------------------------------ -// Exports -//------------------------------------------------------------------------------ - -/** - * The abstract class about cursors which manipulate another cursor. - */ -module.exports = class DecorativeCursor extends Cursor { - - /** - * Initializes this cursor. - * @param {Cursor} cursor - The cursor to be decorated. - */ - constructor(cursor) { - super(); - this.cursor = cursor; - } - - /** @inheritdoc */ - moveNext() { - const retv = this.cursor.moveNext(); - - this.current = this.cursor.current; - - return retv; - } -}; diff --git a/tools/node_modules/eslint/lib/token-store/filter-cursor.js b/tools/node_modules/eslint/lib/token-store/filter-cursor.js deleted file mode 100644 index 7133627bd395a1..00000000000000 --- a/tools/node_modules/eslint/lib/token-store/filter-cursor.js +++ /dev/null @@ -1,43 +0,0 @@ -/** - * @fileoverview Define the cursor which ignores specified tokens. - * @author Toru Nagashima - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const DecorativeCursor = require("./decorative-cursor"); - -//------------------------------------------------------------------------------ -// Exports -//------------------------------------------------------------------------------ - -/** - * The decorative cursor which ignores specified tokens. - */ -module.exports = class FilterCursor extends DecorativeCursor { - - /** - * Initializes this cursor. - * @param {Cursor} cursor - The cursor to be decorated. - * @param {Function} predicate - The predicate function to decide tokens this cursor iterates. - */ - constructor(cursor, predicate) { - super(cursor); - this.predicate = predicate; - } - - /** @inheritdoc */ - moveNext() { - const predicate = this.predicate; - - while (super.moveNext()) { - if (predicate(this.current)) { - return true; - } - } - return false; - } -}; diff --git a/tools/node_modules/eslint/lib/token-store/forward-token-comment-cursor.js b/tools/node_modules/eslint/lib/token-store/forward-token-comment-cursor.js deleted file mode 100644 index be08552970fcd1..00000000000000 --- a/tools/node_modules/eslint/lib/token-store/forward-token-comment-cursor.js +++ /dev/null @@ -1,57 +0,0 @@ -/** - * @fileoverview Define the cursor which iterates tokens and comments. - * @author Toru Nagashima - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const Cursor = require("./cursor"); -const utils = require("./utils"); - -//------------------------------------------------------------------------------ -// Exports -//------------------------------------------------------------------------------ - -/** - * The cursor which iterates tokens and comments. - */ -module.exports = class ForwardTokenCommentCursor extends Cursor { - - /** - * Initializes this cursor. - * @param {Token[]} tokens - The array of tokens. - * @param {Comment[]} comments - The array of comments. - * @param {Object} indexMap - The map from locations to indices in `tokens`. - * @param {number} startLoc - The start location of the iteration range. - * @param {number} endLoc - The end location of the iteration range. - */ - constructor(tokens, comments, indexMap, startLoc, endLoc) { - super(); - this.tokens = tokens; - this.comments = comments; - this.tokenIndex = utils.getFirstIndex(tokens, indexMap, startLoc); - this.commentIndex = utils.search(comments, startLoc); - this.border = endLoc; - } - - /** @inheritdoc */ - moveNext() { - const token = (this.tokenIndex < this.tokens.length) ? this.tokens[this.tokenIndex] : null; - const comment = (this.commentIndex < this.comments.length) ? this.comments[this.commentIndex] : null; - - if (token && (!comment || token.range[0] < comment.range[0])) { - this.current = token; - this.tokenIndex += 1; - } else if (comment) { - this.current = comment; - this.commentIndex += 1; - } else { - this.current = null; - } - - return Boolean(this.current) && (this.border === -1 || this.current.range[1] <= this.border); - } -}; diff --git a/tools/node_modules/eslint/lib/token-store/forward-token-cursor.js b/tools/node_modules/eslint/lib/token-store/forward-token-cursor.js deleted file mode 100644 index 523ed398fa3d9e..00000000000000 --- a/tools/node_modules/eslint/lib/token-store/forward-token-cursor.js +++ /dev/null @@ -1,63 +0,0 @@ -/** - * @fileoverview Define the cursor which iterates tokens only. - * @author Toru Nagashima - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const Cursor = require("./cursor"); -const utils = require("./utils"); - -//------------------------------------------------------------------------------ -// Exports -//------------------------------------------------------------------------------ - -/** - * The cursor which iterates tokens only. - */ -module.exports = class ForwardTokenCursor extends Cursor { - - /** - * Initializes this cursor. - * @param {Token[]} tokens - The array of tokens. - * @param {Comment[]} comments - The array of comments. - * @param {Object} indexMap - The map from locations to indices in `tokens`. - * @param {number} startLoc - The start location of the iteration range. - * @param {number} endLoc - The end location of the iteration range. - */ - constructor(tokens, comments, indexMap, startLoc, endLoc) { - super(); - this.tokens = tokens; - this.index = utils.getFirstIndex(tokens, indexMap, startLoc); - this.indexEnd = utils.getLastIndex(tokens, indexMap, endLoc); - } - - /** @inheritdoc */ - moveNext() { - if (this.index <= this.indexEnd) { - this.current = this.tokens[this.index]; - this.index += 1; - return true; - } - return false; - } - - /* - * - * Shorthand for performance. - * - */ - - /** @inheritdoc */ - getOneToken() { - return (this.index <= this.indexEnd) ? this.tokens[this.index] : null; - } - - /** @inheritdoc */ - getAllTokens() { - return this.tokens.slice(this.index, this.indexEnd + 1); - } -}; diff --git a/tools/node_modules/eslint/lib/token-store/index.js b/tools/node_modules/eslint/lib/token-store/index.js deleted file mode 100644 index d59a0bba03b26e..00000000000000 --- a/tools/node_modules/eslint/lib/token-store/index.js +++ /dev/null @@ -1,633 +0,0 @@ -/** - * @fileoverview Object to handle access and retrieval of tokens. - * @author Brandon Mills - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const assert = require("assert"); -const cursors = require("./cursors"); -const ForwardTokenCursor = require("./forward-token-cursor"); -const PaddedTokenCursor = require("./padded-token-cursor"); -const utils = require("./utils"); -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const TOKENS = Symbol("tokens"); -const COMMENTS = Symbol("comments"); -const INDEX_MAP = Symbol("indexMap"); - -/** - * Creates the map from locations to indices in `tokens`. - * - * The first/last location of tokens is mapped to the index of the token. - * The first/last location of comments is mapped to the index of the next token of each comment. - * - * @param {Token[]} tokens - The array of tokens. - * @param {Comment[]} comments - The array of comments. - * @returns {Object} The map from locations to indices in `tokens`. - * @private - */ -function createIndexMap(tokens, comments) { - const map = Object.create(null); - let tokenIndex = 0; - let commentIndex = 0; - let nextStart = 0; - let range = null; - - while (tokenIndex < tokens.length || commentIndex < comments.length) { - nextStart = (commentIndex < comments.length) ? comments[commentIndex].range[0] : Number.MAX_SAFE_INTEGER; - while (tokenIndex < tokens.length && (range = tokens[tokenIndex].range)[0] < nextStart) { - map[range[0]] = tokenIndex; - map[range[1] - 1] = tokenIndex; - tokenIndex += 1; - } - - nextStart = (tokenIndex < tokens.length) ? tokens[tokenIndex].range[0] : Number.MAX_SAFE_INTEGER; - while (commentIndex < comments.length && (range = comments[commentIndex].range)[0] < nextStart) { - map[range[0]] = tokenIndex; - map[range[1] - 1] = tokenIndex; - commentIndex += 1; - } - } - - return map; -} - -/** - * Creates the cursor iterates tokens with options. - * - * @param {CursorFactory} factory - The cursor factory to initialize cursor. - * @param {Token[]} tokens - The array of tokens. - * @param {Comment[]} comments - The array of comments. - * @param {Object} indexMap - The map from locations to indices in `tokens`. - * @param {number} startLoc - The start location of the iteration range. - * @param {number} endLoc - The end location of the iteration range. - * @param {number|Function|Object} [opts=0] - The option object. If this is a number then it's `opts.skip`. If this is a function then it's `opts.filter`. - * @param {boolean} [opts.includeComments=false] - The flag to iterate comments as well. - * @param {Function|null} [opts.filter=null] - The predicate function to choose tokens. - * @param {number} [opts.skip=0] - The count of tokens the cursor skips. - * @returns {Cursor} The created cursor. - * @private - */ -function createCursorWithSkip(factory, tokens, comments, indexMap, startLoc, endLoc, opts) { - let includeComments = false; - let skip = 0; - let filter = null; - - if (typeof opts === "number") { - skip = opts | 0; - } else if (typeof opts === "function") { - filter = opts; - } else if (opts) { - includeComments = !!opts.includeComments; - skip = opts.skip | 0; - filter = opts.filter || null; - } - assert(skip >= 0, "options.skip should be zero or a positive integer."); - assert(!filter || typeof filter === "function", "options.filter should be a function."); - - return factory.createCursor(tokens, comments, indexMap, startLoc, endLoc, includeComments, filter, skip, -1); -} - -/** - * Creates the cursor iterates tokens with options. - * - * @param {CursorFactory} factory - The cursor factory to initialize cursor. - * @param {Token[]} tokens - The array of tokens. - * @param {Comment[]} comments - The array of comments. - * @param {Object} indexMap - The map from locations to indices in `tokens`. - * @param {number} startLoc - The start location of the iteration range. - * @param {number} endLoc - The end location of the iteration range. - * @param {number|Function|Object} [opts=0] - The option object. If this is a number then it's `opts.count`. If this is a function then it's `opts.filter`. - * @param {boolean} [opts.includeComments] - The flag to iterate comments as well. - * @param {Function|null} [opts.filter=null] - The predicate function to choose tokens. - * @param {number} [opts.count=0] - The maximum count of tokens the cursor iterates. Zero is no iteration for backward compatibility. - * @returns {Cursor} The created cursor. - * @private - */ -function createCursorWithCount(factory, tokens, comments, indexMap, startLoc, endLoc, opts) { - let includeComments = false; - let count = 0; - let countExists = false; - let filter = null; - - if (typeof opts === "number") { - count = opts | 0; - countExists = true; - } else if (typeof opts === "function") { - filter = opts; - } else if (opts) { - includeComments = !!opts.includeComments; - count = opts.count | 0; - countExists = typeof opts.count === "number"; - filter = opts.filter || null; - } - assert(count >= 0, "options.count should be zero or a positive integer."); - assert(!filter || typeof filter === "function", "options.filter should be a function."); - - return factory.createCursor(tokens, comments, indexMap, startLoc, endLoc, includeComments, filter, 0, countExists ? count : -1); -} - -/** - * Creates the cursor iterates tokens with options. - * This is overload function of the below. - * - * @param {Token[]} tokens - The array of tokens. - * @param {Comment[]} comments - The array of comments. - * @param {Object} indexMap - The map from locations to indices in `tokens`. - * @param {number} startLoc - The start location of the iteration range. - * @param {number} endLoc - The end location of the iteration range. - * @param {Function|Object} opts - The option object. If this is a function then it's `opts.filter`. - * @param {boolean} [opts.includeComments] - The flag to iterate comments as well. - * @param {Function|null} [opts.filter=null] - The predicate function to choose tokens. - * @param {number} [opts.count=0] - The maximum count of tokens the cursor iterates. Zero is no iteration for backward compatibility. - * @returns {Cursor} The created cursor. - * @private - */ -/** - * Creates the cursor iterates tokens with options. - * - * @param {Token[]} tokens - The array of tokens. - * @param {Comment[]} comments - The array of comments. - * @param {Object} indexMap - The map from locations to indices in `tokens`. - * @param {number} startLoc - The start location of the iteration range. - * @param {number} endLoc - The end location of the iteration range. - * @param {number} [beforeCount=0] - The number of tokens before the node to retrieve. - * @param {boolean} [afterCount=0] - The number of tokens after the node to retrieve. - * @returns {Cursor} The created cursor. - * @private - */ -function createCursorWithPadding(tokens, comments, indexMap, startLoc, endLoc, beforeCount, afterCount) { - if (typeof beforeCount === "undefined" && typeof afterCount === "undefined") { - return new ForwardTokenCursor(tokens, comments, indexMap, startLoc, endLoc); - } - if (typeof beforeCount === "number" || typeof beforeCount === "undefined") { - return new PaddedTokenCursor(tokens, comments, indexMap, startLoc, endLoc, beforeCount | 0, afterCount | 0); - } - return createCursorWithCount(cursors.forward, tokens, comments, indexMap, startLoc, endLoc, beforeCount); -} - -/** - * Gets comment tokens that are adjacent to the current cursor position. - * @param {Cursor} cursor - A cursor instance. - * @returns {Array} An array of comment tokens adjacent to the current cursor position. - * @private - */ -function getAdjacentCommentTokensFromCursor(cursor) { - const tokens = []; - let currentToken = cursor.getOneToken(); - - while (currentToken && astUtils.isCommentToken(currentToken)) { - tokens.push(currentToken); - currentToken = cursor.getOneToken(); - } - - return tokens; -} - -//------------------------------------------------------------------------------ -// Exports -//------------------------------------------------------------------------------ - -/** - * The token store. - * - * This class provides methods to get tokens by locations as fast as possible. - * The methods are a part of public API, so we should be careful if it changes this class. - * - * People can get tokens in O(1) by the hash map which is mapping from the location of tokens/comments to tokens. - * Also people can get a mix of tokens and comments in O(log k), the k is the number of comments. - * Assuming that comments to be much fewer than tokens, this does not make hash map from token's locations to comments to reduce memory cost. - * This uses binary-searching instead for comments. - */ -module.exports = class TokenStore { - - /** - * Initializes this token store. - * @param {Token[]} tokens - The array of tokens. - * @param {Comment[]} comments - The array of comments. - */ - constructor(tokens, comments) { - this[TOKENS] = tokens; - this[COMMENTS] = comments; - this[INDEX_MAP] = createIndexMap(tokens, comments); - } - - //-------------------------------------------------------------------------- - // Gets single token. - //-------------------------------------------------------------------------- - - /** - * Gets the token starting at the specified index. - * @param {number} offset - Index of the start of the token's range. - * @param {Object} [options=0] - The option object. - * @param {boolean} [options.includeComments=false] - The flag to iterate comments as well. - * @returns {Token|null} The token starting at index, or null if no such token. - */ - getTokenByRangeStart(offset, options) { - const includeComments = options && options.includeComments; - const token = cursors.forward.createBaseCursor( - this[TOKENS], - this[COMMENTS], - this[INDEX_MAP], - offset, - -1, - includeComments - ).getOneToken(); - - if (token && token.range[0] === offset) { - return token; - } - return null; - } - - /** - * Gets the first token of the given node. - * @param {ASTNode} node - The AST node. - * @param {number|Function|Object} [options=0] - The option object. If this is a number then it's `options.skip`. If this is a function then it's `options.filter`. - * @param {boolean} [options.includeComments=false] - The flag to iterate comments as well. - * @param {Function|null} [options.filter=null] - The predicate function to choose tokens. - * @param {number} [options.skip=0] - The count of tokens the cursor skips. - * @returns {Token|null} An object representing the token. - */ - getFirstToken(node, options) { - return createCursorWithSkip( - cursors.forward, - this[TOKENS], - this[COMMENTS], - this[INDEX_MAP], - node.range[0], - node.range[1], - options - ).getOneToken(); - } - - /** - * Gets the last token of the given node. - * @param {ASTNode} node - The AST node. - * @param {number|Function|Object} [options=0] - The option object. Same options as getFirstToken() - * @returns {Token|null} An object representing the token. - */ - getLastToken(node, options) { - return createCursorWithSkip( - cursors.backward, - this[TOKENS], - this[COMMENTS], - this[INDEX_MAP], - node.range[0], - node.range[1], - options - ).getOneToken(); - } - - /** - * Gets the token that precedes a given node or token. - * @param {ASTNode|Token|Comment} node - The AST node or token. - * @param {number|Function|Object} [options=0] - The option object. Same options as getFirstToken() - * @returns {Token|null} An object representing the token. - */ - getTokenBefore(node, options) { - return createCursorWithSkip( - cursors.backward, - this[TOKENS], - this[COMMENTS], - this[INDEX_MAP], - -1, - node.range[0], - options - ).getOneToken(); - } - - /** - * Gets the token that follows a given node or token. - * @param {ASTNode|Token|Comment} node - The AST node or token. - * @param {number|Function|Object} [options=0] - The option object. Same options as getFirstToken() - * @returns {Token|null} An object representing the token. - */ - getTokenAfter(node, options) { - return createCursorWithSkip( - cursors.forward, - this[TOKENS], - this[COMMENTS], - this[INDEX_MAP], - node.range[1], - -1, - options - ).getOneToken(); - } - - /** - * Gets the first token between two non-overlapping nodes. - * @param {ASTNode|Token|Comment} left - Node before the desired token range. - * @param {ASTNode|Token|Comment} right - Node after the desired token range. - * @param {number|Function|Object} [options=0] - The option object. Same options as getFirstToken() - * @returns {Token|null} An object representing the token. - */ - getFirstTokenBetween(left, right, options) { - return createCursorWithSkip( - cursors.forward, - this[TOKENS], - this[COMMENTS], - this[INDEX_MAP], - left.range[1], - right.range[0], - options - ).getOneToken(); - } - - /** - * Gets the last token between two non-overlapping nodes. - * @param {ASTNode|Token|Comment} left Node before the desired token range. - * @param {ASTNode|Token|Comment} right Node after the desired token range. - * @param {number|Function|Object} [options=0] - The option object. Same options as getFirstToken() - * @returns {Token|null} An object representing the token. - */ - getLastTokenBetween(left, right, options) { - return createCursorWithSkip( - cursors.backward, - this[TOKENS], - this[COMMENTS], - this[INDEX_MAP], - left.range[1], - right.range[0], - options - ).getOneToken(); - } - - /** - * Gets the token that precedes a given node or token in the token stream. - * This is defined for backward compatibility. Use `includeComments` option instead. - * TODO: We have a plan to remove this in a future major version. - * @param {ASTNode|Token|Comment} node The AST node or token. - * @param {number} [skip=0] A number of tokens to skip. - * @returns {Token|null} An object representing the token. - * @deprecated - */ - getTokenOrCommentBefore(node, skip) { - return this.getTokenBefore(node, { includeComments: true, skip }); - } - - /** - * Gets the token that follows a given node or token in the token stream. - * This is defined for backward compatibility. Use `includeComments` option instead. - * TODO: We have a plan to remove this in a future major version. - * @param {ASTNode|Token|Comment} node The AST node or token. - * @param {number} [skip=0] A number of tokens to skip. - * @returns {Token|null} An object representing the token. - * @deprecated - */ - getTokenOrCommentAfter(node, skip) { - return this.getTokenAfter(node, { includeComments: true, skip }); - } - - //-------------------------------------------------------------------------- - // Gets multiple tokens. - //-------------------------------------------------------------------------- - - /** - * Gets the first `count` tokens of the given node. - * @param {ASTNode} node - The AST node. - * @param {number|Function|Object} [options=0] - The option object. If this is a number then it's `options.count`. If this is a function then it's `options.filter`. - * @param {boolean} [options.includeComments=false] - The flag to iterate comments as well. - * @param {Function|null} [options.filter=null] - The predicate function to choose tokens. - * @param {number} [options.count=0] - The maximum count of tokens the cursor iterates. - * @returns {Token[]} Tokens. - */ - getFirstTokens(node, options) { - return createCursorWithCount( - cursors.forward, - this[TOKENS], - this[COMMENTS], - this[INDEX_MAP], - node.range[0], - node.range[1], - options - ).getAllTokens(); - } - - /** - * Gets the last `count` tokens of the given node. - * @param {ASTNode} node - The AST node. - * @param {number|Function|Object} [options=0] - The option object. Same options as getFirstTokens() - * @returns {Token[]} Tokens. - */ - getLastTokens(node, options) { - return createCursorWithCount( - cursors.backward, - this[TOKENS], - this[COMMENTS], - this[INDEX_MAP], - node.range[0], - node.range[1], - options - ).getAllTokens().reverse(); - } - - /** - * Gets the `count` tokens that precedes a given node or token. - * @param {ASTNode|Token|Comment} node - The AST node or token. - * @param {number|Function|Object} [options=0] - The option object. Same options as getFirstTokens() - * @returns {Token[]} Tokens. - */ - getTokensBefore(node, options) { - return createCursorWithCount( - cursors.backward, - this[TOKENS], - this[COMMENTS], - this[INDEX_MAP], - -1, - node.range[0], - options - ).getAllTokens().reverse(); - } - - /** - * Gets the `count` tokens that follows a given node or token. - * @param {ASTNode|Token|Comment} node - The AST node or token. - * @param {number|Function|Object} [options=0] - The option object. Same options as getFirstTokens() - * @returns {Token[]} Tokens. - */ - getTokensAfter(node, options) { - return createCursorWithCount( - cursors.forward, - this[TOKENS], - this[COMMENTS], - this[INDEX_MAP], - node.range[1], - -1, - options - ).getAllTokens(); - } - - /** - * Gets the first `count` tokens between two non-overlapping nodes. - * @param {ASTNode|Token|Comment} left - Node before the desired token range. - * @param {ASTNode|Token|Comment} right - Node after the desired token range. - * @param {number|Function|Object} [options=0] - The option object. Same options as getFirstTokens() - * @returns {Token[]} Tokens between left and right. - */ - getFirstTokensBetween(left, right, options) { - return createCursorWithCount( - cursors.forward, - this[TOKENS], - this[COMMENTS], - this[INDEX_MAP], - left.range[1], - right.range[0], - options - ).getAllTokens(); - } - - /** - * Gets the last `count` tokens between two non-overlapping nodes. - * @param {ASTNode|Token|Comment} left Node before the desired token range. - * @param {ASTNode|Token|Comment} right Node after the desired token range. - * @param {number|Function|Object} [options=0] - The option object. Same options as getFirstTokens() - * @returns {Token[]} Tokens between left and right. - */ - getLastTokensBetween(left, right, options) { - return createCursorWithCount( - cursors.backward, - this[TOKENS], - this[COMMENTS], - this[INDEX_MAP], - left.range[1], - right.range[0], - options - ).getAllTokens().reverse(); - } - - /** - * Gets all tokens that are related to the given node. - * @param {ASTNode} node - The AST node. - * @param {Function|Object} options The option object. If this is a function then it's `options.filter`. - * @param {boolean} [options.includeComments=false] - The flag to iterate comments as well. - * @param {Function|null} [options.filter=null] - The predicate function to choose tokens. - * @param {number} [options.count=0] - The maximum count of tokens the cursor iterates. - * @returns {Token[]} Array of objects representing tokens. - */ - /** - * Gets all tokens that are related to the given node. - * @param {ASTNode} node - The AST node. - * @param {int} [beforeCount=0] - The number of tokens before the node to retrieve. - * @param {int} [afterCount=0] - The number of tokens after the node to retrieve. - * @returns {Token[]} Array of objects representing tokens. - */ - getTokens(node, beforeCount, afterCount) { - return createCursorWithPadding( - this[TOKENS], - this[COMMENTS], - this[INDEX_MAP], - node.range[0], - node.range[1], - beforeCount, - afterCount - ).getAllTokens(); - } - - /** - * Gets all of the tokens between two non-overlapping nodes. - * @param {ASTNode|Token|Comment} left Node before the desired token range. - * @param {ASTNode|Token|Comment} right Node after the desired token range. - * @param {Function|Object} options The option object. If this is a function then it's `options.filter`. - * @param {boolean} [options.includeComments=false] - The flag to iterate comments as well. - * @param {Function|null} [options.filter=null] - The predicate function to choose tokens. - * @param {number} [options.count=0] - The maximum count of tokens the cursor iterates. - * @returns {Token[]} Tokens between left and right. - */ - /** - * Gets all of the tokens between two non-overlapping nodes. - * @param {ASTNode|Token|Comment} left Node before the desired token range. - * @param {ASTNode|Token|Comment} right Node after the desired token range. - * @param {int} [padding=0] Number of extra tokens on either side of center. - * @returns {Token[]} Tokens between left and right. - */ - getTokensBetween(left, right, padding) { - return createCursorWithPadding( - this[TOKENS], - this[COMMENTS], - this[INDEX_MAP], - left.range[1], - right.range[0], - padding, - padding - ).getAllTokens(); - } - - //-------------------------------------------------------------------------- - // Others. - //-------------------------------------------------------------------------- - - /** - * Checks whether any comments exist or not between the given 2 nodes. - * - * @param {ASTNode} left - The node to check. - * @param {ASTNode} right - The node to check. - * @returns {boolean} `true` if one or more comments exist. - */ - commentsExistBetween(left, right) { - const index = utils.search(this[COMMENTS], left.range[1]); - - return ( - index < this[COMMENTS].length && - this[COMMENTS][index].range[1] <= right.range[0] - ); - } - - /** - * Gets all comment tokens directly before the given node or token. - * @param {ASTNode|token} nodeOrToken The AST node or token to check for adjacent comment tokens. - * @returns {Array} An array of comments in occurrence order. - */ - getCommentsBefore(nodeOrToken) { - const cursor = createCursorWithCount( - cursors.backward, - this[TOKENS], - this[COMMENTS], - this[INDEX_MAP], - -1, - nodeOrToken.range[0], - { includeComments: true } - ); - - return getAdjacentCommentTokensFromCursor(cursor).reverse(); - } - - /** - * Gets all comment tokens directly after the given node or token. - * @param {ASTNode|token} nodeOrToken The AST node or token to check for adjacent comment tokens. - * @returns {Array} An array of comments in occurrence order. - */ - getCommentsAfter(nodeOrToken) { - const cursor = createCursorWithCount( - cursors.forward, - this[TOKENS], - this[COMMENTS], - this[INDEX_MAP], - nodeOrToken.range[1], - -1, - { includeComments: true } - ); - - return getAdjacentCommentTokensFromCursor(cursor); - } - - /** - * Gets all comment tokens inside the given node. - * @param {ASTNode} node The AST node to get the comments for. - * @returns {Array} An array of comments in occurrence order. - */ - getCommentsInside(node) { - return this.getTokens(node, { - includeComments: true, - filter: astUtils.isCommentToken - }); - } -}; diff --git a/tools/node_modules/eslint/lib/token-store/limit-cursor.js b/tools/node_modules/eslint/lib/token-store/limit-cursor.js deleted file mode 100644 index efb46cf0e3f40d..00000000000000 --- a/tools/node_modules/eslint/lib/token-store/limit-cursor.js +++ /dev/null @@ -1,40 +0,0 @@ -/** - * @fileoverview Define the cursor which limits the number of tokens. - * @author Toru Nagashima - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const DecorativeCursor = require("./decorative-cursor"); - -//------------------------------------------------------------------------------ -// Exports -//------------------------------------------------------------------------------ - -/** - * The decorative cursor which limits the number of tokens. - */ -module.exports = class LimitCursor extends DecorativeCursor { - - /** - * Initializes this cursor. - * @param {Cursor} cursor - The cursor to be decorated. - * @param {number} count - The count of tokens this cursor iterates. - */ - constructor(cursor, count) { - super(cursor); - this.count = count; - } - - /** @inheritdoc */ - moveNext() { - if (this.count > 0) { - this.count -= 1; - return super.moveNext(); - } - return false; - } -}; diff --git a/tools/node_modules/eslint/lib/token-store/padded-token-cursor.js b/tools/node_modules/eslint/lib/token-store/padded-token-cursor.js deleted file mode 100644 index c083aed1e9bab9..00000000000000 --- a/tools/node_modules/eslint/lib/token-store/padded-token-cursor.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * @fileoverview Define the cursor which iterates tokens only, with inflated range. - * @author Toru Nagashima - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const ForwardTokenCursor = require("./forward-token-cursor"); - -//------------------------------------------------------------------------------ -// Exports -//------------------------------------------------------------------------------ - -/** - * The cursor which iterates tokens only, with inflated range. - * This is for the backward compatibility of padding options. - */ -module.exports = class PaddedTokenCursor extends ForwardTokenCursor { - - /** - * Initializes this cursor. - * @param {Token[]} tokens - The array of tokens. - * @param {Comment[]} comments - The array of comments. - * @param {Object} indexMap - The map from locations to indices in `tokens`. - * @param {number} startLoc - The start location of the iteration range. - * @param {number} endLoc - The end location of the iteration range. - * @param {number} beforeCount - The number of tokens this cursor iterates before start. - * @param {number} afterCount - The number of tokens this cursor iterates after end. - */ - constructor(tokens, comments, indexMap, startLoc, endLoc, beforeCount, afterCount) { - super(tokens, comments, indexMap, startLoc, endLoc); - this.index = Math.max(0, this.index - beforeCount); - this.indexEnd = Math.min(tokens.length - 1, this.indexEnd + afterCount); - } -}; diff --git a/tools/node_modules/eslint/lib/token-store/skip-cursor.js b/tools/node_modules/eslint/lib/token-store/skip-cursor.js deleted file mode 100644 index ab34dfab0db3c6..00000000000000 --- a/tools/node_modules/eslint/lib/token-store/skip-cursor.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * @fileoverview Define the cursor which ignores the first few tokens. - * @author Toru Nagashima - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const DecorativeCursor = require("./decorative-cursor"); - -//------------------------------------------------------------------------------ -// Exports -//------------------------------------------------------------------------------ - -/** - * The decorative cursor which ignores the first few tokens. - */ -module.exports = class SkipCursor extends DecorativeCursor { - - /** - * Initializes this cursor. - * @param {Cursor} cursor - The cursor to be decorated. - * @param {number} count - The count of tokens this cursor skips. - */ - constructor(cursor, count) { - super(cursor); - this.count = count; - } - - /** @inheritdoc */ - moveNext() { - while (this.count > 0) { - this.count -= 1; - if (!super.moveNext()) { - return false; - } - } - return super.moveNext(); - } -}; diff --git a/tools/node_modules/eslint/lib/token-store/utils.js b/tools/node_modules/eslint/lib/token-store/utils.js deleted file mode 100644 index 34b0a9af6da68d..00000000000000 --- a/tools/node_modules/eslint/lib/token-store/utils.js +++ /dev/null @@ -1,104 +0,0 @@ -/** - * @fileoverview Define utilify functions for token store. - * @author Toru Nagashima - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const lodash = require("lodash"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Gets `token.range[0]` from the given token. - * - * @param {Node|Token|Comment} token - The token to get. - * @returns {number} The start location. - * @private - */ -function getStartLocation(token) { - return token.range[0]; -} - -//------------------------------------------------------------------------------ -// Exports -//------------------------------------------------------------------------------ - -/** - * Binary-searches the index of the first token which is after the given location. - * If it was not found, this returns `tokens.length`. - * - * @param {(Token|Comment)[]} tokens - It searches the token in this list. - * @param {number} location - The location to search. - * @returns {number} The found index or `tokens.length`. - */ -exports.search = function search(tokens, location) { - return lodash.sortedIndexBy( - tokens, - { range: [location] }, - getStartLocation - ); -}; - -/** - * Gets the index of the `startLoc` in `tokens`. - * `startLoc` can be the value of `node.range[1]`, so this checks about `startLoc - 1` as well. - * - * @param {(Token|Comment)[]} tokens - The tokens to find an index. - * @param {Object} indexMap - The map from locations to indices. - * @param {number} startLoc - The location to get an index. - * @returns {number} The index. - */ -exports.getFirstIndex = function getFirstIndex(tokens, indexMap, startLoc) { - if (startLoc in indexMap) { - return indexMap[startLoc]; - } - if ((startLoc - 1) in indexMap) { - const index = indexMap[startLoc - 1]; - const token = (index >= 0 && index < tokens.length) ? tokens[index] : null; - - /* - * For the map of "comment's location -> token's index", it points the next token of a comment. - * In that case, +1 is unnecessary. - */ - if (token && token.range[0] >= startLoc) { - return index; - } - return index + 1; - } - return 0; -}; - -/** - * Gets the index of the `endLoc` in `tokens`. - * The information of end locations are recorded at `endLoc - 1` in `indexMap`, so this checks about `endLoc - 1` as well. - * - * @param {(Token|Comment)[]} tokens - The tokens to find an index. - * @param {Object} indexMap - The map from locations to indices. - * @param {number} endLoc - The location to get an index. - * @returns {number} The index. - */ -exports.getLastIndex = function getLastIndex(tokens, indexMap, endLoc) { - if (endLoc in indexMap) { - return indexMap[endLoc] - 1; - } - if ((endLoc - 1) in indexMap) { - const index = indexMap[endLoc - 1]; - const token = (index >= 0 && index < tokens.length) ? tokens[index] : null; - - /* - * For the map of "comment's location -> token's index", it points the next token of a comment. - * In that case, -1 is necessary. - */ - if (token && token.range[1] > endLoc) { - return index - 1; - } - return index; - } - return tokens.length - 1; -}; diff --git a/tools/node_modules/eslint/lib/util/ajv.js b/tools/node_modules/eslint/lib/util/ajv.js deleted file mode 100644 index ecf0ebd172cd51..00000000000000 --- a/tools/node_modules/eslint/lib/util/ajv.js +++ /dev/null @@ -1,31 +0,0 @@ -/** - * @fileoverview The instance of Ajv validator. - * @author Evgeny Poberezkin - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const Ajv = require("ajv"), - metaSchema = require("ajv/lib/refs/json-schema-draft-04.json"); - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -const ajv = new Ajv({ - meta: false, - useDefaults: true, - validateSchema: false, - missingRefs: "ignore", - verbose: true, - schemaId: "auto" -}); - -ajv.addMetaSchema(metaSchema); -// eslint-disable-next-line no-underscore-dangle -ajv._opts.defaultMeta = metaSchema.id; - -module.exports = ajv; diff --git a/tools/node_modules/eslint/lib/util/apply-disable-directives.js b/tools/node_modules/eslint/lib/util/apply-disable-directives.js deleted file mode 100644 index c764a9b7020a04..00000000000000 --- a/tools/node_modules/eslint/lib/util/apply-disable-directives.js +++ /dev/null @@ -1,159 +0,0 @@ -/** - * @fileoverview A module that filters reported problems based on `eslint-disable` and `eslint-enable` comments - * @author Teddy Katz - */ - -"use strict"; - -const lodash = require("lodash"); - -/** - * Compares the locations of two objects in a source file - * @param {{line: number, column: number}} itemA The first object - * @param {{line: number, column: number}} itemB The second object - * @returns {number} A value less than 1 if itemA appears before itemB in the source file, greater than 1 if - * itemA appears after itemB in the source file, or 0 if itemA and itemB have the same location. - */ -function compareLocations(itemA, itemB) { - return itemA.line - itemB.line || itemA.column - itemB.column; -} - -/** - * This is the same as the exported function, except that it - * doesn't handle disable-line and disable-next-line directives, and it always reports unused - * disable directives. - * @param {Object} options options for applying directives. This is the same as the options - * for the exported function, except that `reportUnusedDisableDirectives` is not supported - * (this function always reports unused disable directives). - * @returns {{problems: Problem[], unusedDisableDirectives: Problem[]}} An object with a list - * of filtered problems and unused eslint-disable directives - */ -function applyDirectives(options) { - const problems = []; - let nextDirectiveIndex = 0; - let currentGlobalDisableDirective = null; - const disabledRuleMap = new Map(); - - // enabledRules is only used when there is a current global disable directive. - const enabledRules = new Set(); - const usedDisableDirectives = new Set(); - - for (const problem of options.problems) { - while ( - nextDirectiveIndex < options.directives.length && - compareLocations(options.directives[nextDirectiveIndex], problem) <= 0 - ) { - const directive = options.directives[nextDirectiveIndex++]; - - switch (directive.type) { - case "disable": - if (directive.ruleId === null) { - currentGlobalDisableDirective = directive; - disabledRuleMap.clear(); - enabledRules.clear(); - } else if (currentGlobalDisableDirective) { - enabledRules.delete(directive.ruleId); - disabledRuleMap.set(directive.ruleId, directive); - } else { - disabledRuleMap.set(directive.ruleId, directive); - } - break; - - case "enable": - if (directive.ruleId === null) { - currentGlobalDisableDirective = null; - disabledRuleMap.clear(); - } else if (currentGlobalDisableDirective) { - enabledRules.add(directive.ruleId); - disabledRuleMap.delete(directive.ruleId); - } else { - disabledRuleMap.delete(directive.ruleId); - } - break; - - // no default - } - } - - if (disabledRuleMap.has(problem.ruleId)) { - usedDisableDirectives.add(disabledRuleMap.get(problem.ruleId)); - } else if (currentGlobalDisableDirective && !enabledRules.has(problem.ruleId)) { - usedDisableDirectives.add(currentGlobalDisableDirective); - } else { - problems.push(problem); - } - } - - const unusedDisableDirectives = options.directives - .filter(directive => directive.type === "disable" && !usedDisableDirectives.has(directive)) - .map(directive => ({ - ruleId: null, - message: directive.ruleId - ? `Unused eslint-disable directive (no problems were reported from '${directive.ruleId}').` - : "Unused eslint-disable directive (no problems were reported).", - line: directive.unprocessedDirective.line, - column: directive.unprocessedDirective.column, - severity: 2, - nodeType: null - })); - - return { problems, unusedDisableDirectives }; -} - -/** - * Given a list of directive comments (i.e. metadata about eslint-disable and eslint-enable comments) and a list - * of reported problems, determines which problems should be reported. - * @param {Object} options Information about directives and problems - * @param {{ - * type: ("disable"|"enable"|"disable-line"|"disable-next-line"), - * ruleId: (string|null), - * line: number, - * column: number - * }} options.directives Directive comments found in the file, with one-based columns. - * Two directive comments can only have the same location if they also have the same type (e.g. a single eslint-disable - * comment for two different rules is represented as two directives). - * @param {{ruleId: (string|null), line: number, column: number}[]} options.problems - * A list of problems reported by rules, sorted by increasing location in the file, with one-based columns. - * @param {boolean} options.reportUnusedDisableDirectives If `true`, adds additional problems for unused directives - * @returns {{ruleId: (string|null), line: number, column: number}[]} - * A list of reported problems that were not disabled by the directive comments. - */ -module.exports = options => { - const blockDirectives = options.directives - .filter(directive => directive.type === "disable" || directive.type === "enable") - .map(directive => Object.assign({}, directive, { unprocessedDirective: directive })) - .sort(compareLocations); - - const lineDirectives = lodash.flatMap(options.directives, directive => { - switch (directive.type) { - case "disable": - case "enable": - return []; - - case "disable-line": - return [ - { type: "disable", line: directive.line, column: 1, ruleId: directive.ruleId, unprocessedDirective: directive }, - { type: "enable", line: directive.line + 1, column: 0, ruleId: directive.ruleId, unprocessedDirective: directive } - ]; - - case "disable-next-line": - return [ - { type: "disable", line: directive.line + 1, column: 1, ruleId: directive.ruleId, unprocessedDirective: directive }, - { type: "enable", line: directive.line + 2, column: 0, ruleId: directive.ruleId, unprocessedDirective: directive } - ]; - - default: - throw new TypeError(`Unrecognized directive type '${directive.type}'`); - } - }).sort(compareLocations); - - const blockDirectivesResult = applyDirectives({ problems: options.problems, directives: blockDirectives }); - const lineDirectivesResult = applyDirectives({ problems: blockDirectivesResult.problems, directives: lineDirectives }); - - return options.reportUnusedDisableDirectives - ? lineDirectivesResult.problems - .concat(blockDirectivesResult.unusedDisableDirectives) - .concat(lineDirectivesResult.unusedDisableDirectives) - .sort(compareLocations) - : lineDirectivesResult.problems; -}; diff --git a/tools/node_modules/eslint/lib/util/ast-utils.js b/tools/node_modules/eslint/lib/util/ast-utils.js deleted file mode 100644 index a188c7fa1c659b..00000000000000 --- a/tools/node_modules/eslint/lib/util/ast-utils.js +++ /dev/null @@ -1,1346 +0,0 @@ -/** - * @fileoverview Common utils for AST. - * @author Gyandeep Singh - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const esutils = require("esutils"); -const espree = require("espree"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const anyFunctionPattern = /^(?:Function(?:Declaration|Expression)|ArrowFunctionExpression)$/; -const anyLoopPattern = /^(?:DoWhile|For|ForIn|ForOf|While)Statement$/; -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 COMMENTS_IGNORE_PATTERN = /^\s*(?:eslint|jshint\s+|jslint\s+|istanbul\s+|globals?\s+|exported\s+|jscs)/; -const LINEBREAKS = new Set(["\r\n", "\r", "\n", "\u2028", "\u2029"]); -const LINEBREAK_MATCHER = /\r\n|[\r\n\u2028\u2029]/; -const SHEBANG_MATCHER = /^#!([^\r\n]+)/; - -// A set of node types that can contain a list of statements -const STATEMENT_LIST_PARENTS = new Set(["Program", "BlockStatement", "SwitchCase"]); - -/** - * Checks reference if is non initializer and writable. - * @param {Reference} reference - A reference to check. - * @param {int} index - The index of the reference in the references. - * @param {Reference[]} references - The array that the reference belongs to. - * @returns {boolean} Success/Failure - * @private - */ -function isModifyingReference(reference, index, references) { - const identifier = reference.identifier; - - /* - * Destructuring assignments can have multiple default value, so - * possibly there are multiple writeable references for the same - * identifier. - */ - const modifyingDifferentIdentifier = index === 0 || - references[index - 1].identifier !== identifier; - - return (identifier && - reference.init === false && - reference.isWrite() && - modifyingDifferentIdentifier - ); -} - -/** - * Checks whether the given string starts with uppercase or not. - * - * @param {string} s - The string to check. - * @returns {boolean} `true` if the string starts with uppercase. - */ -function startsWithUpperCase(s) { - return s[0] !== s[0].toLocaleLowerCase(); -} - -/** - * Checks whether or not a node is a constructor. - * @param {ASTNode} node - A function node to check. - * @returns {boolean} Wehether or not a node is a constructor. - */ -function isES5Constructor(node) { - return (node.id && startsWithUpperCase(node.id.name)); -} - -/** - * Finds a function node from ancestors of a node. - * @param {ASTNode} node - A start node to find. - * @returns {Node|null} A found function node. - */ -function getUpperFunction(node) { - for (let currentNode = node; currentNode; currentNode = currentNode.parent) { - if (anyFunctionPattern.test(currentNode.type)) { - return currentNode; - } - } - 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) { - for (let currentNode = node; currentNode && !isFunction(currentNode); currentNode = currentNode.parent) { - if (isLoop(currentNode)) { - return true; - } - } - - return false; -} - -/** - * Checks whether or not a node is `null` or `undefined`. - * @param {ASTNode} node - A node to check. - * @returns {boolean} Whether or not the node is a `null` or `undefined`. - * @public - */ -function isNullOrUndefined(node) { - return ( - module.exports.isNullLiteral(node) || - (node.type === "Identifier" && node.name === "undefined") || - (node.type === "UnaryExpression" && node.operator === "void") - ); -} - -/** - * Checks whether or not a node is callee. - * @param {ASTNode} node - A node to check. - * @returns {boolean} Whether or not the node is callee. - */ -function isCallee(node) { - return node.parent.type === "CallExpression" && node.parent.callee === node; -} - -/** - * Checks whether or not a node is `Reflect.apply`. - * @param {ASTNode} node - A node to check. - * @returns {boolean} Whether or not the node is a `Reflect.apply`. - */ -function isReflectApply(node) { - return ( - node.type === "MemberExpression" && - node.object.type === "Identifier" && - node.object.name === "Reflect" && - node.property.type === "Identifier" && - node.property.name === "apply" && - node.computed === false - ); -} - -/** - * Checks whether or not a node is `Array.from`. - * @param {ASTNode} node - A node to check. - * @returns {boolean} Whether or not the node is a `Array.from`. - */ -function isArrayFromMethod(node) { - return ( - node.type === "MemberExpression" && - node.object.type === "Identifier" && - arrayOrTypedArrayPattern.test(node.object.name) && - node.property.type === "Identifier" && - node.property.name === "from" && - node.computed === false - ); -} - -/** - * Checks whether or not a node is a method which has `thisArg`. - * @param {ASTNode} node - A node to check. - * @returns {boolean} Whether or not the node is a method which has `thisArg`. - */ -function isMethodWhichHasThisArg(node) { - for ( - let currentNode = node; - currentNode.type === "MemberExpression" && !currentNode.computed; - currentNode = currentNode.property - ) { - if (currentNode.property.type === "Identifier") { - return arrayMethodPattern.test(currentNode.property.name); - } - } - - return false; -} - -/** - * Creates the negate function of the given function. - * @param {Function} f - The function to negate. - * @returns {Function} Negated function. - */ -function negate(f) { - return token => !f(token); -} - -/** - * Checks whether or not a node has a `@this` tag in its comments. - * @param {ASTNode} node - A node to check. - * @param {SourceCode} sourceCode - A SourceCode instance to get comments. - * @returns {boolean} Whether or not the node has a `@this` tag in its comments. - */ -function hasJSDocThisTag(node, sourceCode) { - const jsdocComment = sourceCode.getJSDocComment(node); - - if (jsdocComment && thisTagPattern.test(jsdocComment.value)) { - return true; - } - - // Checks `@this` in its leading comments for callbacks, - // because callbacks don't have its JSDoc comment. - // e.g. - // sinon.test(/* @this sinon.Sandbox */function() { this.spy(); }); - return sourceCode.getCommentsBefore(node).some(comment => thisTagPattern.test(comment.value)); -} - -/** - * Determines if a node is surrounded by parentheses. - * @param {SourceCode} sourceCode The ESLint source code object - * @param {ASTNode} node The node to be checked. - * @returns {boolean} True if the node is parenthesised. - * @private - */ -function isParenthesised(sourceCode, node) { - const previousToken = sourceCode.getTokenBefore(node), - nextToken = sourceCode.getTokenAfter(node); - - return Boolean(previousToken && nextToken) && - previousToken.value === "(" && previousToken.range[1] <= node.range[0] && - nextToken.value === ")" && nextToken.range[0] >= node.range[1]; -} - -/** - * Checks if the given token is an arrow token or not. - * - * @param {Token} token - The token to check. - * @returns {boolean} `true` if the token is an arrow token. - */ -function isArrowToken(token) { - return token.value === "=>" && token.type === "Punctuator"; -} - -/** - * Checks if the given token is a comma token or not. - * - * @param {Token} token - The token to check. - * @returns {boolean} `true` if the token is a comma token. - */ -function isCommaToken(token) { - return token.value === "," && token.type === "Punctuator"; -} - -/** - * Checks if the given token is a semicolon token or not. - * - * @param {Token} token - The token to check. - * @returns {boolean} `true` if the token is a semicolon token. - */ -function isSemicolonToken(token) { - return token.value === ";" && token.type === "Punctuator"; -} - -/** - * Checks if the given token is a colon token or not. - * - * @param {Token} token - The token to check. - * @returns {boolean} `true` if the token is a colon token. - */ -function isColonToken(token) { - return token.value === ":" && token.type === "Punctuator"; -} - -/** - * Checks if the given token is an opening parenthesis token or not. - * - * @param {Token} token - The token to check. - * @returns {boolean} `true` if the token is an opening parenthesis token. - */ -function isOpeningParenToken(token) { - return token.value === "(" && token.type === "Punctuator"; -} - -/** - * Checks if the given token is a closing parenthesis token or not. - * - * @param {Token} token - The token to check. - * @returns {boolean} `true` if the token is a closing parenthesis token. - */ -function isClosingParenToken(token) { - return token.value === ")" && token.type === "Punctuator"; -} - -/** - * Checks if the given token is an opening square bracket token or not. - * - * @param {Token} token - The token to check. - * @returns {boolean} `true` if the token is an opening square bracket token. - */ -function isOpeningBracketToken(token) { - return token.value === "[" && token.type === "Punctuator"; -} - -/** - * Checks if the given token is a closing square bracket token or not. - * - * @param {Token} token - The token to check. - * @returns {boolean} `true` if the token is a closing square bracket token. - */ -function isClosingBracketToken(token) { - return token.value === "]" && token.type === "Punctuator"; -} - -/** - * Checks if the given token is an opening brace token or not. - * - * @param {Token} token - The token to check. - * @returns {boolean} `true` if the token is an opening brace token. - */ -function isOpeningBraceToken(token) { - return token.value === "{" && token.type === "Punctuator"; -} - -/** - * Checks if the given token is a closing brace token or not. - * - * @param {Token} token - The token to check. - * @returns {boolean} `true` if the token is a closing brace token. - */ -function isClosingBraceToken(token) { - return token.value === "}" && token.type === "Punctuator"; -} - -/** - * Checks if the given token is a comment token or not. - * - * @param {Token} token - The token to check. - * @returns {boolean} `true` if the token is a comment token. - */ -function isCommentToken(token) { - return token.type === "Line" || token.type === "Block" || token.type === "Shebang"; -} - -/** - * Checks if the given token is a keyword token or not. - * - * @param {Token} token - The token to check. - * @returns {boolean} `true` if the token is a keyword token. - */ -function isKeywordToken(token) { - return token.type === "Keyword"; -} - -/** - * 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) { - return node.id - ? sourceCode.getTokenAfter(node.id, isOpeningParenToken) - : sourceCode.getFirstToken(node, isOpeningParenToken); -} - -/** - * Creates a version of the LINEBREAK_MATCHER regex with the global flag. - * Global regexes are mutable, so this needs to be a function instead of a constant. - * @returns {RegExp} A global regular expression that matches line terminators - */ -function createGlobalLinebreakMatcher() { - return new RegExp(LINEBREAK_MATCHER.source, "g"); -} - -/** - * Checks whether or not the tokens of two given nodes are same. - * @param {ASTNode} left - A node 1 to compare. - * @param {ASTNode} right - A node 2 to compare. - * @param {SourceCode} sourceCode - The ESLint source code object. - * @returns {boolean} the source code for the given node. - */ -function equalTokens(left, right, sourceCode) { - const tokensL = sourceCode.getTokens(left); - const tokensR = sourceCode.getTokens(right); - - if (tokensL.length !== tokensR.length) { - return false; - } - for (let i = 0; i < tokensL.length; ++i) { - if (tokensL[i].type !== tokensR[i].type || - tokensL[i].value !== tokensR[i].value - ) { - return false; - } - } - - return true; -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = { - COMMENTS_IGNORE_PATTERN, - LINEBREAKS, - LINEBREAK_MATCHER, - SHEBANG_MATCHER, - STATEMENT_LIST_PARENTS, - - /** - * Determines whether two adjacent tokens are on the same line. - * @param {Object} left - The left token object. - * @param {Object} right - The right token object. - * @returns {boolean} Whether or not the tokens are on the same line. - * @public - */ - isTokenOnSameLine(left, right) { - return left.loc.end.line === right.loc.start.line; - }, - - isNullOrUndefined, - isCallee, - isES5Constructor, - getUpperFunction, - isFunction, - isLoop, - isInLoop, - isArrayFromMethod, - isParenthesised, - createGlobalLinebreakMatcher, - equalTokens, - - isArrowToken, - isClosingBraceToken, - isClosingBracketToken, - isClosingParenToken, - isColonToken, - isCommaToken, - isCommentToken, - isKeywordToken, - isNotClosingBraceToken: negate(isClosingBraceToken), - isNotClosingBracketToken: negate(isClosingBracketToken), - isNotClosingParenToken: negate(isClosingParenToken), - isNotColonToken: negate(isColonToken), - isNotCommaToken: negate(isCommaToken), - isNotOpeningBraceToken: negate(isOpeningBraceToken), - isNotOpeningBracketToken: negate(isOpeningBracketToken), - isNotOpeningParenToken: negate(isOpeningParenToken), - isNotSemicolonToken: negate(isSemicolonToken), - isOpeningBraceToken, - isOpeningBracketToken, - isOpeningParenToken, - isSemicolonToken, - - /** - * Checks whether or not a given node is a string literal. - * @param {ASTNode} node - A node to check. - * @returns {boolean} `true` if the node is a string literal. - */ - isStringLiteral(node) { - return ( - (node.type === "Literal" && typeof node.value === "string") || - node.type === "TemplateLiteral" - ); - }, - - /** - * Checks whether a given node is a breakable statement or not. - * The node is breakable if the node is one of the following type: - * - * - DoWhileStatement - * - ForInStatement - * - ForOfStatement - * - ForStatement - * - SwitchStatement - * - WhileStatement - * - * @param {ASTNode} node - A node to check. - * @returns {boolean} `true` if the node is breakable. - */ - isBreakableStatement(node) { - return breakableTypePattern.test(node.type); - }, - - /** - * Gets the label if the parent node of a given node is a LabeledStatement. - * - * @param {ASTNode} node - A node to get. - * @returns {string|null} The label or `null`. - */ - getLabel(node) { - if (node.parent.type === "LabeledStatement") { - return node.parent.label.name; - } - return null; - }, - - /** - * Gets references which are non initializer and writable. - * @param {Reference[]} references - An array of references. - * @returns {Reference[]} An array of only references which are non initializer and writable. - * @public - */ - getModifyingReferences(references) { - return references.filter(isModifyingReference); - }, - - /** - * Validate that a string passed in is surrounded by the specified character - * @param {string} val The text to check. - * @param {string} character The character to see if it's surrounded by. - * @returns {boolean} True if the text is surrounded by the character, false if not. - * @private - */ - isSurroundedBy(val, character) { - return val[0] === character && val[val.length - 1] === character; - }, - - /** - * Returns whether the provided node is an ESLint directive comment or not - * @param {Line|Block} node The comment token to be checked - * @returns {boolean} `true` if the node is an ESLint directive comment - */ - isDirectiveComment(node) { - const comment = node.value.trim(); - - return ( - node.type === "Line" && comment.indexOf("eslint-") === 0 || - node.type === "Block" && ( - comment.indexOf("global ") === 0 || - comment.indexOf("eslint ") === 0 || - comment.indexOf("eslint-") === 0 - ) - ); - }, - - /** - * Gets the trailing statement of a given node. - * - * if (code) - * consequent; - * - * When taking this `IfStatement`, returns `consequent;` statement. - * - * @param {ASTNode} A node to get. - * @returns {ASTNode|null} The trailing statement's node. - */ - getTrailingStatement: esutils.ast.trailingStatement, - - /** - * Finds the variable by a given name in a given scope and its upper scopes. - * - * @param {eslint-scope.Scope} initScope - A scope to start find. - * @param {string} name - A variable name to find. - * @returns {eslint-scope.Variable|null} A found variable or `null`. - */ - getVariableByName(initScope, name) { - let scope = initScope; - - while (scope) { - const variable = scope.set.get(name); - - if (variable) { - return variable; - } - - scope = scope.upper; - } - - return null; - }, - - /** - * Checks whether or not a given function node is the default `this` binding. - * - * First, this checks the node: - * - * - The function name does not start with uppercase (it's a constructor). - * - The function does not have a JSDoc comment that has a @this tag. - * - * Next, this checks the location of the node. - * If the location is below, this judges `this` is valid. - * - * - The location is not on an object literal. - * - The location is not assigned to a variable which starts with an uppercase letter. - * - The location is not on an ES2015 class. - * - Its `bind`/`call`/`apply` method is not called directly. - * - The function is not a callback of array methods (such as `.forEach()`) if `thisArg` is given. - * - * @param {ASTNode} node - A function node to check. - * @param {SourceCode} sourceCode - A SourceCode instance to get comments. - * @returns {boolean} The function node is the default `this` binding. - */ - isDefaultThisBinding(node, sourceCode) { - if (isES5Constructor(node) || hasJSDocThisTag(node, sourceCode)) { - return false; - } - const isAnonymous = node.id === null; - let currentNode = node; - - while (currentNode) { - const parent = currentNode.parent; - - switch (parent.type) { - - /* - * Looks up the destination. - * e.g., obj.foo = nativeFoo || function foo() { ... }; - */ - case "LogicalExpression": - case "ConditionalExpression": - currentNode = parent; - break; - - /* - * If the upper function is IIFE, checks the destination of the return value. - * e.g. - * obj.foo = (function() { - * // setup... - * return function foo() { ... }; - * })(); - * obj.foo = (() => - * function foo() { ... } - * )(); - */ - case "ReturnStatement": { - const func = getUpperFunction(parent); - - if (func === null || !isCallee(func)) { - return true; - } - currentNode = func.parent; - break; - } - case "ArrowFunctionExpression": - if (currentNode !== parent.body || !isCallee(parent)) { - return true; - } - currentNode = parent.parent; - break; - - /* - * e.g. - * var obj = { foo() { ... } }; - * var obj = { foo: function() { ... } }; - * class A { constructor() { ... } } - * class A { foo() { ... } } - * class A { get foo() { ... } } - * class A { set foo() { ... } } - * class A { static foo() { ... } } - */ - case "Property": - case "MethodDefinition": - return parent.value !== currentNode; - - /* - * e.g. - * obj.foo = function foo() { ... }; - * Foo = function() { ... }; - * [obj.foo = function foo() { ... }] = a; - * [Foo = function() { ... }] = a; - */ - case "AssignmentExpression": - case "AssignmentPattern": - if (parent.left.type === "MemberExpression") { - return false; - } - if ( - isAnonymous && - parent.left.type === "Identifier" && - startsWithUpperCase(parent.left.name) - ) { - return false; - } - return true; - - /* - * e.g. - * var Foo = function() { ... }; - */ - case "VariableDeclarator": - return !( - isAnonymous && - parent.init === currentNode && - parent.id.type === "Identifier" && - startsWithUpperCase(parent.id.name) - ); - - /* - * e.g. - * var foo = function foo() { ... }.bind(obj); - * (function foo() { ... }).call(obj); - * (function foo() { ... }).apply(obj, []); - */ - case "MemberExpression": - return ( - parent.object !== currentNode || - parent.property.type !== "Identifier" || - !bindOrCallOrApplyPattern.test(parent.property.name) || - !isCallee(parent) || - parent.parent.arguments.length === 0 || - isNullOrUndefined(parent.parent.arguments[0]) - ); - - /* - * e.g. - * Reflect.apply(function() {}, obj, []); - * Array.from([], function() {}, obj); - * list.forEach(function() {}, obj); - */ - case "CallExpression": - if (isReflectApply(parent.callee)) { - return ( - parent.arguments.length !== 3 || - parent.arguments[0] !== currentNode || - isNullOrUndefined(parent.arguments[1]) - ); - } - if (isArrayFromMethod(parent.callee)) { - return ( - parent.arguments.length !== 3 || - parent.arguments[1] !== currentNode || - isNullOrUndefined(parent.arguments[2]) - ); - } - if (isMethodWhichHasThisArg(parent.callee)) { - return ( - parent.arguments.length !== 2 || - parent.arguments[0] !== currentNode || - isNullOrUndefined(parent.arguments[1]) - ); - } - return true; - - // Otherwise `this` is default. - default: - return true; - } - } - - /* istanbul ignore next */ - return true; - }, - - /** - * Get the precedence level based on the node type - * @param {ASTNode} node node to evaluate - * @returns {int} precedence level - * @private - */ - getPrecedence(node) { - switch (node.type) { - case "SequenceExpression": - return 0; - - case "AssignmentExpression": - case "ArrowFunctionExpression": - case "YieldExpression": - return 1; - - case "ConditionalExpression": - return 3; - - case "LogicalExpression": - switch (node.operator) { - case "||": - return 4; - case "&&": - return 5; - - // no default - } - - /* falls through */ - - case "BinaryExpression": - - switch (node.operator) { - case "|": - return 6; - case "^": - return 7; - case "&": - return 8; - case "==": - case "!=": - case "===": - case "!==": - return 9; - case "<": - case "<=": - case ">": - case ">=": - case "in": - case "instanceof": - return 10; - case "<<": - case ">>": - case ">>>": - return 11; - case "+": - case "-": - return 12; - case "*": - case "/": - case "%": - return 13; - case "**": - return 15; - - // no default - } - - /* falls through */ - - case "UnaryExpression": - case "AwaitExpression": - return 16; - - case "UpdateExpression": - return 17; - - case "CallExpression": - return 18; - - case "NewExpression": - return 19; - - default: - return 20; - } - }, - - /** - * Checks whether the given node is an empty block node or not. - * - * @param {ASTNode|null} node - The node to check. - * @returns {boolean} `true` if the node is an empty block. - */ - isEmptyBlock(node) { - return Boolean(node && node.type === "BlockStatement" && node.body.length === 0); - }, - - /** - * Checks whether the given node is an empty function node or not. - * - * @param {ASTNode|null} node - The node to check. - * @returns {boolean} `true` if the node is an empty function. - */ - isEmptyFunction(node) { - return isFunction(node) && module.exports.isEmptyBlock(node.body); - }, - - /** - * Gets the property name of a given node. - * The node can be a MemberExpression, a Property, or a MethodDefinition. - * - * If the name is dynamic, this returns `null`. - * - * For examples: - * - * a.b // => "b" - * a["b"] // => "b" - * a['b'] // => "b" - * a[`b`] // => "b" - * a[100] // => "100" - * a[b] // => null - * a["a" + "b"] // => null - * a[tag`b`] // => null - * a[`${b}`] // => null - * - * let a = {b: 1} // => "b" - * let a = {["b"]: 1} // => "b" - * let a = {['b']: 1} // => "b" - * let a = {[`b`]: 1} // => "b" - * let a = {[100]: 1} // => "100" - * let a = {[b]: 1} // => null - * let a = {["a" + "b"]: 1} // => null - * let a = {[tag`b`]: 1} // => null - * let a = {[`${b}`]: 1} // => null - * - * @param {ASTNode} node - The node to get. - * @returns {string|null} The property name if static. Otherwise, null. - */ - getStaticPropertyName(node) { - let prop; - - switch (node && node.type) { - case "Property": - case "MethodDefinition": - prop = node.key; - break; - - case "MemberExpression": - prop = node.property; - break; - - // no default - } - - switch (prop && prop.type) { - case "Literal": - return String(prop.value); - - case "TemplateLiteral": - if (prop.expressions.length === 0 && prop.quasis.length === 1) { - return prop.quasis[0].value.cooked; - } - break; - - case "Identifier": - if (!node.computed) { - return prop.name; - } - break; - - // no default - } - - return null; - }, - - /** - * Get directives from directive prologue of a Program or Function node. - * @param {ASTNode} node - The node to check. - * @returns {ASTNode[]} The directives found in the directive prologue. - */ - getDirectivePrologue(node) { - const directives = []; - - // Directive prologues only occur at the top of files or functions. - if ( - node.type === "Program" || - node.type === "FunctionDeclaration" || - node.type === "FunctionExpression" || - - /* - * Do not check arrow functions with implicit return. - * `() => "use strict";` returns the string `"use strict"`. - */ - (node.type === "ArrowFunctionExpression" && node.body.type === "BlockStatement") - ) { - const statements = node.type === "Program" ? node.body : node.body.body; - - for (const statement of statements) { - if ( - statement.type === "ExpressionStatement" && - statement.expression.type === "Literal" - ) { - directives.push(statement); - } else { - break; - } - } - } - - return directives; - }, - - - /** - * Determines whether this node is a decimal integer literal. If a node is a decimal integer literal, a dot added - * after the node will be parsed as a decimal point, rather than a property-access dot. - * @param {ASTNode} node - The node to check. - * @returns {boolean} `true` if this node is a decimal integer. - * @example - * - * 5 // true - * 5. // false - * 5.0 // false - * 05 // false - * 0x5 // false - * 0b101 // false - * 0o5 // false - * 5e0 // false - * '5' // false - */ - 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"; - } - 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 = sourceCode.getTokenBefore(node.body, isArrowToken); - - 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) - }; - }, - - /** - * 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]); - }, - - /* - * Determine if a node has a possiblity to be an Error object - * @param {ASTNode} node ASTNode to check - * @returns {boolean} True if there is a chance it contains an Error obj - */ - couldBeError(node) { - switch (node.type) { - case "Identifier": - case "CallExpression": - case "NewExpression": - case "MemberExpression": - case "TaggedTemplateExpression": - case "YieldExpression": - case "AwaitExpression": - return true; // possibly an error object. - - case "AssignmentExpression": - return module.exports.couldBeError(node.right); - - case "SequenceExpression": { - const exprs = node.expressions; - - return exprs.length !== 0 && module.exports.couldBeError(exprs[exprs.length - 1]); - } - - case "LogicalExpression": - return module.exports.couldBeError(node.left) || module.exports.couldBeError(node.right); - - case "ConditionalExpression": - return module.exports.couldBeError(node.consequent) || module.exports.couldBeError(node.alternate); - - default: - return false; - } - }, - - /** - * Determines whether the given node is a `null` literal. - * @param {ASTNode} node The node to check - * @returns {boolean} `true` if the node is a `null` literal - */ - isNullLiteral(node) { - - /* - * Checking `node.value === null` does not guarantee that a literal is a null literal. - * When parsing values that cannot be represented in the current environment (e.g. unicode - * regexes in Node 4), `node.value` is set to `null` because it wouldn't be possible to - * set `node.value` to a unicode regex. To make sure a literal is actually `null`, check - * `node.regex` instead. Also see: https://github.com/eslint/eslint/issues/8020 - */ - return node.type === "Literal" && node.value === null && !node.regex; - }, - - /** - * Determines whether two tokens can safely be placed next to each other without merging into a single token - * @param {Token|string} leftValue The left token. If this is a string, it will be tokenized and the last token will be used. - * @param {Token|string} rightValue The right token. If this is a string, it will be tokenized and the first token will be used. - * @returns {boolean} If the tokens cannot be safely placed next to each other, returns `false`. If the tokens can be placed - * next to each other, behavior is undefined (although it should return `true` in most cases). - */ - canTokensBeAdjacent(leftValue, rightValue) { - let leftToken; - - if (typeof leftValue === "string") { - const leftTokens = espree.tokenize(leftValue, { ecmaVersion: 2015 }); - - leftToken = leftTokens[leftTokens.length - 1]; - } else { - leftToken = leftValue; - } - - const rightToken = typeof rightValue === "string" ? espree.tokenize(rightValue, { ecmaVersion: 2015 })[0] : rightValue; - - if (leftToken.type === "Punctuator" || rightToken.type === "Punctuator") { - if (leftToken.type === "Punctuator" && rightToken.type === "Punctuator") { - const PLUS_TOKENS = new Set(["+", "++"]); - const MINUS_TOKENS = new Set(["-", "--"]); - - return !( - PLUS_TOKENS.has(leftToken.value) && PLUS_TOKENS.has(rightToken.value) || - MINUS_TOKENS.has(leftToken.value) && MINUS_TOKENS.has(rightToken.value) - ); - } - return true; - } - - if ( - leftToken.type === "String" || rightToken.type === "String" || - leftToken.type === "Template" || rightToken.type === "Template" - ) { - return true; - } - - if (leftToken.type !== "Numeric" && rightToken.type === "Numeric" && rightToken.value.startsWith(".")) { - return true; - } - - return false; - } -}; diff --git a/tools/node_modules/eslint/lib/util/config-comment-parser.js b/tools/node_modules/eslint/lib/util/config-comment-parser.js deleted file mode 100644 index 8ee0230cb26a3f..00000000000000 --- a/tools/node_modules/eslint/lib/util/config-comment-parser.js +++ /dev/null @@ -1,141 +0,0 @@ -/** - * @fileoverview Config Comment Parser - * @author Nicholas C. Zakas - */ - -/* eslint-disable class-methods-use-this*/ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const levn = require("levn"), - ConfigOps = require("../config/config-ops"); - -const debug = require("debug")("eslint:config-comment-parser"); - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -/** - * Object to parse ESLint configuration comments inside JavaScript files. - * @name ConfigCommentParser - */ -module.exports = class ConfigCommentParser { - - /** - * Parses a list of "name:string_value" or/and "name" options divided by comma or - * whitespace. Used for "global" and "exported" comments. - * @param {string} string The string to parse. - * @param {Comment} comment The comment node which has the string. - * @returns {Object} Result map object of names and string values, or null values if no value was provided - */ - parseStringConfig(string, comment) { - debug("Parsing String config"); - - const items = {}; - - // Collapse whitespace around `:` and `,` to make parsing easier - const trimmedString = string.replace(/\s*([:,])\s*/g, "$1"); - - trimmedString.split(/\s|,+/).forEach(name => { - if (!name) { - return; - } - - // value defaults to null (if not provided), e.g: "foo" => ["foo", null] - const [key, value = null] = name.split(":"); - - items[key] = { value, comment }; - }); - return items; - } - - /** - * Parses a JSON-like config. - * @param {string} string The string to parse. - * @param {Object} location Start line and column of comments for potential error message. - * @returns {({success: true, config: Object}|{success: false, error: Problem})} Result map object - */ - parseJsonConfig(string, location) { - debug("Parsing JSON config"); - - let items = {}; - - // Parses a JSON-like comment by the same way as parsing CLI option. - try { - items = levn.parse("Object", string) || {}; - - // Some tests say that it should ignore invalid comments such as `/*eslint no-alert:abc*/`. - // Also, commaless notations have invalid severity: - // "no-alert: 2 no-console: 2" --> {"no-alert": "2 no-console: 2"} - // Should ignore that case as well. - if (ConfigOps.isEverySeverityValid(items)) { - return { - success: true, - config: items - }; - } - } catch (ex) { - - debug("Levn parsing failed; falling back to manual parsing."); - - // ignore to parse the string by a fallback. - } - - /* - * Optionator cannot parse commaless notations. - * But we are supporting that. So this is a fallback for that. - */ - items = {}; - const normalizedString = string.replace(/([a-zA-Z0-9\-/]+):/g, "\"$1\":").replace(/(]|[0-9])\s+(?=")/, "$1,"); - - try { - items = JSON.parse(`{${normalizedString}}`); - } catch (ex) { - debug("Manual parsing failed."); - - return { - success: false, - error: { - ruleId: null, - fatal: true, - severity: 2, - message: `Failed to parse JSON from '${normalizedString}': ${ex.message}`, - line: location.start.line, - column: location.start.column + 1 - } - }; - - } - - return { - success: true, - config: items - }; - } - - /** - * Parses a config of values separated by comma. - * @param {string} string The string to parse. - * @returns {Object} Result map of values and true values - */ - parseListConfig(string) { - debug("Parsing list config"); - - const items = {}; - - // Collapse whitespace around commas - string.replace(/\s*,\s*/g, ",").split(/,+/).forEach(name => { - const trimmedName = name.trim(); - - if (trimmedName) { - items[trimmedName] = true; - } - }); - return items; - } - -}; diff --git a/tools/node_modules/eslint/lib/util/file-finder.js b/tools/node_modules/eslint/lib/util/file-finder.js deleted file mode 100644 index e273e4d46c7990..00000000000000 --- a/tools/node_modules/eslint/lib/util/file-finder.js +++ /dev/null @@ -1,144 +0,0 @@ -/** - * @fileoverview Util class to find config files. - * @author Aliaksei Shytkin - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const fs = require("fs"), - path = require("path"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Get the entries for a directory. Including a try-catch may be detrimental to - * function performance, so move it out here a separate function. - * @param {string} directory The directory to search in. - * @returns {string[]} The entries in the directory or an empty array on error. - * @private - */ -function getDirectoryEntries(directory) { - try { - - return fs.readdirSync(directory); - } catch (ex) { - return []; - } -} - -/** - * Create a hash of filenames from a directory listing - * @param {string[]} entries Array of directory entries. - * @param {string} directory Path to a current directory. - * @param {string[]} supportedConfigs List of support filenames. - * @returns {Object} Hashmap of filenames - */ -function normalizeDirectoryEntries(entries, directory, supportedConfigs) { - const fileHash = {}; - - entries.forEach(entry => { - if (supportedConfigs.indexOf(entry) >= 0) { - const resolvedEntry = path.resolve(directory, entry); - - if (fs.statSync(resolvedEntry).isFile()) { - fileHash[entry] = resolvedEntry; - } - } - }); - return fileHash; -} - -//------------------------------------------------------------------------------ -// API -//------------------------------------------------------------------------------ - -/** - * FileFinder class - */ -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 = {}; - } - - /** - * 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} relativeDirectory The directory to start the search from. - * @returns {GeneratorFunction} to iterate the file paths found - */ - *findAllInDirectoryAndParents(relativeDirectory) { - const cache = this.cache; - - const initialDirectory = relativeDirectory - ? path.resolve(this.cwd, relativeDirectory) - : this.cwd; - - if (Object.prototype.hasOwnProperty.call(cache, initialDirectory)) { - yield* cache[initialDirectory]; - return; // to avoid doing the normal loop afterwards - } - - const dirs = []; - const fileNames = this.fileNames; - let searched = 0; - let directory = initialDirectory; - - do { - dirs[searched++] = directory; - cache[directory] = []; - - const filesMap = normalizeDirectoryEntries(getDirectoryEntries(directory), directory, fileNames); - - if (Object.keys(filesMap).length) { - for (let k = 0; k < fileNames.length; k++) { - - 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); - } - yield filePath; - break; - } - } - } - - const child = directory; - - // Assign parent directory to directory. - directory = path.dirname(directory); - - if (directory === child) { - return; - } - - } while (!Object.prototype.hasOwnProperty.call(cache, directory)); - - // Add what has been cached previously to the cache of each directory searched. - for (let i = 0; i < searched; i++) { - cache[dirs[i]].push(...cache[directory]); - } - - yield* cache[dirs[0]]; - } -} - -module.exports = FileFinder; diff --git a/tools/node_modules/eslint/lib/util/fix-tracker.js b/tools/node_modules/eslint/lib/util/fix-tracker.js deleted file mode 100644 index 3c9bf63d257b99..00000000000000 --- a/tools/node_modules/eslint/lib/util/fix-tracker.js +++ /dev/null @@ -1,120 +0,0 @@ -/** - * @fileoverview Helper class to aid in constructing fix commands. - * @author Alan Pierce - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("../util/ast-utils"); - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -/** - * A helper class to combine fix options into a fix command. Currently, it - * exposes some "retain" methods that extend the range of the text being - * replaced so that other fixes won't touch that region in the same pass. - */ -class FixTracker { - - /** - * Create a new FixTracker. - * - * @param {ruleFixer} fixer A ruleFixer instance. - * @param {SourceCode} sourceCode A SourceCode object for the current code. - */ - constructor(fixer, sourceCode) { - this.fixer = fixer; - this.sourceCode = sourceCode; - this.retainedRange = null; - } - - /** - * Mark the given range as "retained", meaning that other fixes may not - * may not modify this region in the same pass. - * - * @param {int[]} range The range to retain. - * @returns {FixTracker} The same RuleFixer, for chained calls. - */ - retainRange(range) { - this.retainedRange = range; - return this; - } - - /** - * Given a node, find the function containing it (or the entire program) and - * mark it as retained, meaning that other fixes may not modify it in this - * pass. This is useful for avoiding conflicts in fixes that modify control - * flow. - * - * @param {ASTNode} node The node to use as a starting point. - * @returns {FixTracker} The same RuleFixer, for chained calls. - */ - retainEnclosingFunction(node) { - const functionNode = astUtils.getUpperFunction(node); - - return this.retainRange(functionNode ? functionNode.range : this.sourceCode.ast.range); - } - - /** - * Given a node or token, find the token before and afterward, and mark that - * range as retained, meaning that other fixes may not modify it in this - * pass. This is useful for avoiding conflicts in fixes that make a small - * change to the code where the AST should not be changed. - * - * @param {ASTNode|Token} nodeOrToken The node or token to use as a starting - * point. The token to the left and right are use in the range. - * @returns {FixTracker} The same RuleFixer, for chained calls. - */ - retainSurroundingTokens(nodeOrToken) { - const tokenBefore = this.sourceCode.getTokenBefore(nodeOrToken) || nodeOrToken; - const tokenAfter = this.sourceCode.getTokenAfter(nodeOrToken) || nodeOrToken; - - return this.retainRange([tokenBefore.range[0], tokenAfter.range[1]]); - } - - /** - * Create a fix command that replaces the given range with the given text, - * accounting for any retained ranges. - * - * @param {int[]} range The range to remove in the fix. - * @param {string} text The text to insert in place of the range. - * @returns {Object} The fix command. - */ - replaceTextRange(range, text) { - let actualRange; - - if (this.retainedRange) { - actualRange = [ - Math.min(this.retainedRange[0], range[0]), - Math.max(this.retainedRange[1], range[1]) - ]; - } else { - actualRange = range; - } - - return this.fixer.replaceTextRange( - actualRange, - this.sourceCode.text.slice(actualRange[0], range[0]) + - text + - this.sourceCode.text.slice(range[1], actualRange[1]) - ); - } - - /** - * Create a fix command that removes the given node or token, accounting for - * any retained ranges. - * - * @param {ASTNode|Token} nodeOrToken The node or token to remove. - * @returns {Object} The fix command. - */ - remove(nodeOrToken) { - return this.replaceTextRange(nodeOrToken.range, ""); - } -} - -module.exports = FixTracker; diff --git a/tools/node_modules/eslint/lib/util/glob-utils.js b/tools/node_modules/eslint/lib/util/glob-utils.js deleted file mode 100644 index fd4cfa00851d05..00000000000000 --- a/tools/node_modules/eslint/lib/util/glob-utils.js +++ /dev/null @@ -1,274 +0,0 @@ -/** - * @fileoverview Utilities for working with globs and the filesystem. - * @author Ian VanSchooten - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const lodash = require("lodash"), - fs = require("fs"), - path = require("path"), - GlobSync = require("./glob"), - - pathUtils = require("./path-utils"), - IgnoredPaths = require("./ignored-paths"); - -const debug = require("debug")("eslint:glob-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks whether a directory exists at the given location - * @param {string} resolvedPath A path from the CWD - * @returns {boolean} `true` if a directory exists - */ -function directoryExists(resolvedPath) { - return fs.existsSync(resolvedPath) && fs.statSync(resolvedPath).isDirectory(); -} - -/** - * Checks if a provided path is a directory and returns a glob string matching - * all files under that directory if so, the path itself otherwise. - * - * Reason for this is that `glob` needs `/**` to collect all the files under a - * directory where as our previous implementation without `glob` simply walked - * a directory that is passed. So this is to maintain backwards compatibility. - * - * Also makes sure all path separators are POSIX style for `glob` compatibility. - * - * @param {Object} [options] An options object - * @param {string[]} [options.extensions=[".js"]] An array of accepted extensions - * @param {string} [options.cwd=process.cwd()] The cwd to use to resolve relative pathnames - * @returns {Function} A function that takes a pathname and returns a glob that - * matches all files with the provided extensions if - * pathname is a directory. - */ -function processPath(options) { - const cwd = (options && options.cwd) || process.cwd(); - let extensions = (options && options.extensions) || [".js"]; - - extensions = extensions.map(ext => ext.replace(/^\./, "")); - - let suffix = "/**"; - - if (extensions.length === 1) { - suffix += `/*.${extensions[0]}`; - } else { - suffix += `/*.{${extensions.join(",")}}`; - } - - /** - * A function that converts a directory name to a glob pattern - * - * @param {string} pathname The directory path to be modified - * @returns {string} The glob path or the file path itself - * @private - */ - return function(pathname) { - let newPath = pathname; - const resolvedPath = path.resolve(cwd, pathname); - - if (directoryExists(resolvedPath)) { - newPath = pathname.replace(/[/\\]$/, "") + suffix; - } - - return pathUtils.convertPathToPosix(newPath); - }; -} - -/** - * The error type when no files match a glob. - */ -class NoFilesFoundError extends Error { - - /** - * @param {string} pattern - The glob pattern which was not found. - */ - constructor(pattern) { - super(`No files matching '${pattern}' were found.`); - - this.messageTemplate = "file-not-found"; - this.messageData = { pattern }; - } - -} - -/** - * The error type when there are files matched by a glob, but all of them have been ignored. - */ -class AllFilesIgnoredError extends Error { - - /** - * @param {string} pattern - The glob pattern which was not found. - */ - constructor(pattern) { - super(`All files matched by '${pattern}' are ignored.`); - this.messageTemplate = "all-files-ignored"; - this.messageData = { pattern }; - } -} - -const NORMAL_LINT = {}; -const SILENTLY_IGNORE = {}; -const IGNORE_AND_WARN = {}; - -/** - * Tests whether a file should be linted or ignored - * @param {string} filename The file to be processed - * @param {{ignore: (boolean|null)}} options If `ignore` is false, updates the behavior to - * not process custom ignore paths, and lint files specified by direct path even if they - * match the default ignore path - * @param {boolean} isDirectPath True if the file was provided as a direct path - * (as opposed to being resolved from a glob) - * @param {IgnoredPaths} ignoredPaths An instance of IgnoredPaths to check whether a given - * file is ignored. - * @returns {(NORMAL_LINT|SILENTLY_IGNORE|IGNORE_AND_WARN)} A directive for how the - * file should be processed (either linted normally, or silently ignored, or ignored - * with a warning that it is being ignored) - */ -function testFileAgainstIgnorePatterns(filename, options, isDirectPath, ignoredPaths) { - const shouldProcessCustomIgnores = options.ignore !== false; - const shouldLintIgnoredDirectPaths = options.ignore === false; - const fileMatchesIgnorePatterns = ignoredPaths.contains(filename, "default") || - (shouldProcessCustomIgnores && ignoredPaths.contains(filename, "custom")); - - if (fileMatchesIgnorePatterns && isDirectPath && !shouldLintIgnoredDirectPaths) { - return IGNORE_AND_WARN; - } - - if (!fileMatchesIgnorePatterns || (isDirectPath && shouldLintIgnoredDirectPaths)) { - return NORMAL_LINT; - } - - return SILENTLY_IGNORE; -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -/** - * Resolves any directory patterns into glob-based patterns for easier handling. - * @param {string[]} patterns File patterns (such as passed on the command line). - * @param {Object} options An options object. - * @param {string} [options.globInputPaths] False disables glob resolution. - * @returns {string[]} The equivalent glob patterns and filepath strings. - */ -function resolveFileGlobPatterns(patterns, options) { - if (options.globInputPaths === false) { - return patterns; - } - - const processPathExtensions = processPath(options); - - return patterns.map(processPathExtensions); -} - -const dotfilesPattern = /(?:(?:^\.)|(?:[/\\]\.))[^/\\.].*/; - -/** - * Build a list of absolute filesnames on which ESLint will act. - * Ignored files are excluded from the results, as are duplicates. - * - * @param {string[]} globPatterns Glob patterns. - * @param {Object} [providedOptions] An options object. - * @param {string} [providedOptions.cwd] CWD (considered for relative filenames) - * @param {boolean} [providedOptions.ignore] False disables use of .eslintignore. - * @param {string} [providedOptions.ignorePath] The ignore file to use instead of .eslintignore. - * @param {string} [providedOptions.ignorePattern] A pattern of files to ignore. - * @param {string} [providedOptions.globInputPaths] False disables glob resolution. - * @returns {string[]} Resolved absolute filenames. - */ -function listFilesToProcess(globPatterns, providedOptions) { - const options = providedOptions || { ignore: true }; - const cwd = options.cwd || process.cwd(); - - const getIgnorePaths = lodash.memoize( - optionsObj => - new IgnoredPaths(optionsObj) - ); - - /* - * The test "should use default options if none are provided" (source-code-utils.js) checks that 'module.exports.resolveFileGlobPatterns' was called. - * So it cannot use the local function "resolveFileGlobPatterns". - */ - const resolvedGlobPatterns = module.exports.resolveFileGlobPatterns(globPatterns, options); - - debug("Creating list of files to process."); - const resolvedPathsByGlobPattern = resolvedGlobPatterns.map(pattern => { - const file = path.resolve(cwd, pattern); - - if (options.globInputPaths === false || (fs.existsSync(file) && fs.statSync(file).isFile())) { - const ignoredPaths = getIgnorePaths(options); - const fullPath = options.globInputPaths === false ? file : fs.realpathSync(file); - - return [{ - filename: fullPath, - behavior: testFileAgainstIgnorePatterns(fullPath, options, true, ignoredPaths) - }]; - } - - // regex to find .hidden or /.hidden patterns, but not ./relative or ../relative - const globIncludesDotfiles = dotfilesPattern.test(pattern); - let newOptions = options; - - if (!options.dotfiles) { - newOptions = Object.assign({}, options, { dotfiles: globIncludesDotfiles }); - } - - const ignoredPaths = getIgnorePaths(newOptions); - const shouldIgnore = ignoredPaths.getIgnoredFoldersGlobChecker(); - const globOptions = { - nodir: true, - dot: true, - cwd - }; - - return new GlobSync(pattern, globOptions, shouldIgnore).found.map(globMatch => { - const relativePath = path.resolve(cwd, globMatch); - - return { - filename: relativePath, - behavior: testFileAgainstIgnorePatterns(relativePath, options, false, ignoredPaths) - }; - }); - }); - - const allPathDescriptors = resolvedPathsByGlobPattern.reduce((pathsForAllGlobs, pathsForCurrentGlob, index) => { - if (pathsForCurrentGlob.every(pathDescriptor => pathDescriptor.behavior === SILENTLY_IGNORE)) { - throw new (pathsForCurrentGlob.length ? AllFilesIgnoredError : NoFilesFoundError)(globPatterns[index]); - } - - pathsForCurrentGlob.forEach(pathDescriptor => { - switch (pathDescriptor.behavior) { - case NORMAL_LINT: - pathsForAllGlobs.push({ filename: pathDescriptor.filename, ignored: false }); - break; - case IGNORE_AND_WARN: - pathsForAllGlobs.push({ filename: pathDescriptor.filename, ignored: true }); - break; - case SILENTLY_IGNORE: - - // do nothing - break; - - default: - throw new Error(`Unexpected file behavior for ${pathDescriptor.filename}`); - } - }); - - return pathsForAllGlobs; - }, []); - - return lodash.uniqBy(allPathDescriptors, pathDescriptor => pathDescriptor.filename); -} - -module.exports = { - resolveFileGlobPatterns, - listFilesToProcess -}; diff --git a/tools/node_modules/eslint/lib/util/glob.js b/tools/node_modules/eslint/lib/util/glob.js deleted file mode 100644 index f352dae7a4dd3f..00000000000000 --- a/tools/node_modules/eslint/lib/util/glob.js +++ /dev/null @@ -1,63 +0,0 @@ -/** - * @fileoverview An inherited `glob.GlobSync` to support .gitignore patterns. - * @author Kael Zhang - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const Sync = require("glob").GlobSync, - util = require("util"); - -//------------------------------------------------------------------------------ -// Private -//------------------------------------------------------------------------------ - -const IGNORE = Symbol("ignore"); - -/** - * Subclass of `glob.GlobSync` - * @param {string} pattern Pattern to be matched. - * @param {Object} options `options` for `glob` - * @param {function()} shouldIgnore Method to check whether a directory should be ignored. - * @constructor - */ -function GlobSync(pattern, options, shouldIgnore) { - - /** - * We don't put this thing to argument `options` to avoid - * further problems, such as `options` validation. - * - * Use `Symbol` as much as possible to avoid confliction. - */ - this[IGNORE] = shouldIgnore; - - Sync.call(this, pattern, options); -} - -util.inherits(GlobSync, Sync); - -/* eslint no-underscore-dangle: ["error", { "allow": ["_readdir", "_mark"] }] */ - -GlobSync.prototype._readdir = function(abs, inGlobStar) { - - /** - * `options.nodir` makes `options.mark` as `true`. - * Mark `abs` first - * to make sure `"node_modules"` will be ignored immediately with ignore pattern `"node_modules/"`. - * - * There is a built-in cache about marked `File.Stat` in `glob`, so that we could not worry about the extra invocation of `this._mark()` - */ - const marked = this._mark(abs); - - if (this[IGNORE](marked)) { - return null; - } - - return Sync.prototype._readdir.call(this, abs, inGlobStar); -}; - - -module.exports = GlobSync; diff --git a/tools/node_modules/eslint/lib/util/hash.js b/tools/node_modules/eslint/lib/util/hash.js deleted file mode 100644 index 6d7ef8bf1b2c64..00000000000000 --- a/tools/node_modules/eslint/lib/util/hash.js +++ /dev/null @@ -1,35 +0,0 @@ -/** - * @fileoverview Defining the hashing function in one place. - * @author Michael Ficarra - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const murmur = require("imurmurhash"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -//------------------------------------------------------------------------------ -// Private -//------------------------------------------------------------------------------ - -/** - * hash the given string - * @param {string} str the string to hash - * @returns {string} the hash - */ -function hash(str) { - return murmur(str).result().toString(36); -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = hash; diff --git a/tools/node_modules/eslint/lib/util/ignored-paths.js b/tools/node_modules/eslint/lib/util/ignored-paths.js deleted file mode 100644 index de4a79cde336a1..00000000000000 --- a/tools/node_modules/eslint/lib/util/ignored-paths.js +++ /dev/null @@ -1,381 +0,0 @@ -/** - * @fileoverview Responsible for loading ignore config files and managing ignore patterns - * @author Jonathan Rajavuori - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const fs = require("fs"), - path = require("path"), - ignore = require("ignore"), - pathUtils = require("./path-utils"); - -const debug = require("debug")("eslint:ignored-paths"); - -//------------------------------------------------------------------------------ -// Constants -//------------------------------------------------------------------------------ - -const ESLINT_IGNORE_FILENAME = ".eslintignore"; - -/** - * Adds `"*"` at the end of `"node_modules/"`, - * so that subtle directories could be re-included by .gitignore patterns - * such as `"!node_modules/should_not_ignored"` - */ -const DEFAULT_IGNORE_DIRS = [ - "/node_modules/*", - "/bower_components/*" -]; -const DEFAULT_OPTIONS = { - dotfiles: false, - cwd: process.cwd() -}; - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Find a file in the current directory. - * @param {string} cwd Current working directory - * @param {string} name File name - * @returns {string} Path of ignore file or an empty string. - */ -function findFile(cwd, name) { - const ignoreFilePath = path.resolve(cwd, name); - - return fs.existsSync(ignoreFilePath) && fs.statSync(ignoreFilePath).isFile() ? ignoreFilePath : ""; -} - -/** - * Find an ignore file in the current directory. - * @param {string} cwd Current working directory - * @returns {string} Path of ignore file or an empty string. - */ -function findIgnoreFile(cwd) { - return findFile(cwd, ESLINT_IGNORE_FILENAME); -} - -/** - * Find an package.json file in the current directory. - * @param {string} cwd Current working directory - * @returns {string} Path of package.json file or an empty string. - */ -function findPackageJSONFile(cwd) { - return findFile(cwd, "package.json"); -} - -/** - * Merge options with defaults - * @param {Object} options Options to merge with DEFAULT_OPTIONS constant - * @returns {Object} Merged options - */ -function mergeDefaultOptions(options) { - return Object.assign({}, DEFAULT_OPTIONS, options); -} - -/* eslint-disable valid-jsdoc */ -/** - * Normalize the path separators in a given string. - * On Windows environment, this replaces `\` by `/`. - * Otherwrise, this does nothing. - * @param {string} str The path string to normalize. - * @returns {string} The normalized path. - */ -const normalizePathSeps = path.sep === "/" - ? (str => str) - : ((seps, str) => str.replace(seps, "/")).bind(null, new RegExp(`\\${path.sep}`, "g")); -/* eslint-enable valid-jsdoc */ - -/** - * Converts a glob pattern to a new glob pattern relative to a different directory - * @param {string} globPattern The glob pattern, relative the the old base directory - * @param {string} relativePathToOldBaseDir A relative path from the new base directory to the old one - * @returns {string} A glob pattern relative to the new base directory - */ -function relativize(globPattern, relativePathToOldBaseDir) { - if (relativePathToOldBaseDir === "") { - return globPattern; - } - - const prefix = globPattern.startsWith("!") ? "!" : ""; - const globWithoutPrefix = globPattern.replace(/^!/, ""); - - if (globWithoutPrefix.startsWith("/")) { - return `${prefix}/${normalizePathSeps(relativePathToOldBaseDir)}${globWithoutPrefix}`; - } - - return globPattern; -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -/** - * IgnoredPaths class - */ -class IgnoredPaths { - - /** - * @param {Object} providedOptions object containing 'ignore', 'ignorePath' and 'patterns' properties - */ - constructor(providedOptions) { - const options = mergeDefaultOptions(providedOptions); - - this.cache = {}; - - this.defaultPatterns = [].concat(DEFAULT_IGNORE_DIRS, options.patterns || []); - - this.ignoreFileDir = options.ignore !== false && options.ignorePath - ? path.dirname(path.resolve(options.cwd, options.ignorePath)) - : options.cwd; - this.options = options; - this._baseDir = null; - - this.ig = { - custom: ignore(), - default: ignore() - }; - - this.defaultPatterns.forEach(pattern => this.addPatternRelativeToCwd(this.ig.default, pattern)); - if (options.dotfiles !== true) { - - /* - * ignore files beginning with a dot, but not files in a parent or - * ancestor directory (which in relative format will begin with `../`). - */ - this.addPatternRelativeToCwd(this.ig.default, ".*"); - this.addPatternRelativeToCwd(this.ig.default, "!../"); - } - - /* - * 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.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"); - } - } - - if (ignorePath) { - debug(`Adding ${ignorePath}`); - this.addIgnoreFile(this.ig.custom, ignorePath); - this.addIgnoreFile(this.ig.default, ignorePath); - } else { - try { - - // if the ignoreFile does not exist, check package.json for eslintIgnore - const packageJSONPath = findPackageJSONFile(options.cwd); - - if (packageJSONPath) { - let packageJSONOptions; - - try { - packageJSONOptions = JSON.parse(fs.readFileSync(packageJSONPath, "utf8")); - } catch (e) { - debug("Could not read package.json file to check eslintIgnore property"); - e.messageTemplate = "failed-to-read-json"; - e.messageData = { - path: packageJSONPath, - message: e.message - }; - throw e; - } - - if (packageJSONOptions.eslintIgnore) { - if (Array.isArray(packageJSONOptions.eslintIgnore)) { - packageJSONOptions.eslintIgnore.forEach(pattern => { - this.addPatternRelativeToIgnoreFile(this.ig.custom, pattern); - this.addPatternRelativeToIgnoreFile(this.ig.default, pattern); - }); - } else { - throw new TypeError("Package.json eslintIgnore property requires an array of paths"); - } - } - } - } catch (e) { - debug("Could not find package.json to check eslintIgnore property"); - throw e; - } - } - - if (options.ignorePattern) { - this.addPatternRelativeToCwd(this.ig.custom, options.ignorePattern); - this.addPatternRelativeToCwd(this.ig.default, options.ignorePattern); - } - } - } - - /* - * If `ignoreFileDir` is a subdirectory of `cwd`, all paths will be normalized to be relative to `cwd`. - * Otherwise, all paths will be normalized to be relative to `ignoreFileDir`. - * This ensures that the final normalized ignore rule will not contain `..`, which is forbidden in - * ignore rules. - */ - - addPatternRelativeToCwd(ig, pattern) { - const baseDir = this.getBaseDir(); - const cookedPattern = baseDir === this.options.cwd - ? pattern - : relativize(pattern, path.relative(baseDir, this.options.cwd)); - - ig.addPattern(cookedPattern); - debug("addPatternRelativeToCwd:\n original = %j\n cooked = %j", pattern, cookedPattern); - } - - addPatternRelativeToIgnoreFile(ig, pattern) { - const baseDir = this.getBaseDir(); - const cookedPattern = baseDir === this.ignoreFileDir - ? pattern - : relativize(pattern, path.relative(baseDir, this.ignoreFileDir)); - - ig.addPattern(cookedPattern); - debug("addPatternRelativeToIgnoreFile:\n original = %j\n cooked = %j", pattern, cookedPattern); - } - - // Detect the common ancestor - getBaseDir() { - if (!this._baseDir) { - const a = path.resolve(this.options.cwd); - const b = path.resolve(this.ignoreFileDir); - let lastSepPos = 0; - - // Set the shorter one (it's the common ancestor if one includes the other). - this._baseDir = a.length < b.length ? a : b; - - // Set the common ancestor. - for (let i = 0; i < a.length && i < b.length; ++i) { - if (a[i] !== b[i]) { - this._baseDir = a.slice(0, lastSepPos); - break; - } - if (a[i] === path.sep) { - lastSepPos = i; - } - } - - // If it's only Windows drive letter, it needs \ - if (/^[A-Z]:$/.test(this._baseDir)) { - this._baseDir += "\\"; - } - - debug("baseDir = %j", this._baseDir); - } - return this._baseDir; - } - - /** - * read ignore filepath - * @param {string} filePath, file to add to ig - * @returns {Array} raw ignore rules - */ - readIgnoreFile(filePath) { - if (typeof this.cache[filePath] === "undefined") { - this.cache[filePath] = fs.readFileSync(filePath, "utf8").split(/\r?\n/g).filter(Boolean); - } - return this.cache[filePath]; - } - - /** - * add ignore file to node-ignore instance - * @param {Object} ig instance of node-ignore - * @param {string} filePath file to add to ig - * @returns {void} - */ - addIgnoreFile(ig, filePath) { - ig.ignoreFiles.push(filePath); - this - .readIgnoreFile(filePath) - .forEach(ignoreRule => this.addPatternRelativeToIgnoreFile(ig, ignoreRule)); - } - - /** - * Determine whether a file path is included in the default or custom ignore patterns - * @param {string} filepath Path to check - * @param {string} [category=undefined] check 'default', 'custom' or both (undefined) - * @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 = pathUtils.getRelativePath(absolutePath, this.getBaseDir()); - - if (typeof category === "undefined") { - result = (this.ig.default.filter([relativePath]).length === 0) || - (this.ig.custom.filter([relativePath]).length === 0); - } else { - result = (this.ig[category].filter([relativePath]).length === 0); - } - debug("contains:"); - debug(" target = %j", filepath); - debug(" result = %j", result); - - 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. - */ - getIgnoredFoldersGlobChecker() { - const baseDir = this.getBaseDir(); - const ig = ignore(); - - DEFAULT_IGNORE_DIRS.forEach(ignoreDir => this.addPatternRelativeToCwd(ig, ignoreDir)); - - if (this.options.dotfiles !== true) { - - // Ignore hidden folders. (This cannot be ".*", or else it's not possible to unignore hidden files) - ig.add([".*/*", "!../*"]); - } - - if (this.options.ignore) { - ig.add(this.ig.custom); - } - - const filter = ig.createFilter(); - - return function(absolutePath) { - const relative = pathUtils.getRelativePath(absolutePath, baseDir); - - if (!relative) { - return false; - } - - return !filter(relative); - }; - } -} - -module.exports = IgnoredPaths; diff --git a/tools/node_modules/eslint/lib/util/interpolate.js b/tools/node_modules/eslint/lib/util/interpolate.js deleted file mode 100644 index cefdcca5454bc1..00000000000000 --- a/tools/node_modules/eslint/lib/util/interpolate.js +++ /dev/null @@ -1,28 +0,0 @@ -/** - * @fileoverview Interpolate keys from an object into a string with {{ }} markers. - * @author Jed Fox - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = (text, data) => { - if (!data) { - return text; - } - - // Substitution content for any {{ }} markers. - return text.replace(/\{\{([^{}]+?)\}\}/g, (fullMatch, termWithWhitespace) => { - const term = termWithWhitespace.trim(); - - if (term in data) { - return data[term]; - } - - // Preserve old behavior: If parameter name not provided, don't replace it. - return fullMatch; - }); -}; diff --git a/tools/node_modules/eslint/lib/util/keywords.js b/tools/node_modules/eslint/lib/util/keywords.js deleted file mode 100644 index 3fbb77771df5c9..00000000000000 --- a/tools/node_modules/eslint/lib/util/keywords.js +++ /dev/null @@ -1,67 +0,0 @@ -/** - * @fileoverview A shared list of ES3 keywords. - * @author Josh Perez - */ -"use strict"; - -module.exports = [ - "abstract", - "boolean", - "break", - "byte", - "case", - "catch", - "char", - "class", - "const", - "continue", - "debugger", - "default", - "delete", - "do", - "double", - "else", - "enum", - "export", - "extends", - "false", - "final", - "finally", - "float", - "for", - "function", - "goto", - "if", - "implements", - "import", - "in", - "instanceof", - "int", - "interface", - "long", - "native", - "new", - "null", - "package", - "private", - "protected", - "public", - "return", - "short", - "static", - "super", - "switch", - "synchronized", - "this", - "throw", - "throws", - "transient", - "true", - "try", - "typeof", - "var", - "void", - "volatile", - "while", - "with" -]; diff --git a/tools/node_modules/eslint/lib/util/lint-result-cache.js b/tools/node_modules/eslint/lib/util/lint-result-cache.js deleted file mode 100644 index f1e5aabfebf324..00000000000000 --- a/tools/node_modules/eslint/lib/util/lint-result-cache.js +++ /dev/null @@ -1,146 +0,0 @@ -/** - * @fileoverview Utility for caching lint results. - * @author Kevin Partington - */ -"use strict"; - -//----------------------------------------------------------------------------- -// Requirements -//----------------------------------------------------------------------------- - -const assert = require("assert"), - fs = require("fs"), - fileEntryCache = require("file-entry-cache"), - hash = require("./hash"), - pkg = require("../../package.json"), - stringify = require("json-stable-stringify-without-jsonify"); - -//----------------------------------------------------------------------------- -// Helpers -//----------------------------------------------------------------------------- - -const configHashCache = new WeakMap(); - -/** - * Calculates the hash of the config file used to validate a given file - * @param {Object} configHelper The config helper for retrieving configuration information - * @param {string} filename The path of the file to retrieve a config object for to calculate the hash - * @returns {string} The hash of the config - */ -function hashOfConfigFor(configHelper, filename) { - const config = configHelper.getConfig(filename); - - if (!configHashCache.has(config)) { - configHashCache.set(config, hash(`${pkg.version}_${stringify(config)}`)); - } - - return configHashCache.get(config); -} - -//----------------------------------------------------------------------------- -// Public Interface -//----------------------------------------------------------------------------- - -/** - * Lint result cache. This wraps around the file-entry-cache module, - * transparently removing properties that are difficult or expensive to - * serialize and adding them back in on retrieval. - */ -class LintResultCache { - - /** - * Creates a new LintResultCache instance. - * @constructor - * @param {string} cacheFileLocation The cache file location. - * @param {Object} configHelper The configuration helper (used for - * configuration lookup by file path). - */ - constructor(cacheFileLocation, configHelper) { - assert(cacheFileLocation, "Cache file location is required"); - assert(configHelper, "Config helper is required"); - - this.fileEntryCache = fileEntryCache.create(cacheFileLocation); - this.configHelper = configHelper; - } - - /** - * Retrieve cached lint results for a given file path, if present in the - * cache. If the file is present and has not been changed, rebuild any - * missing result information. - * @param {string} filePath The file for which to retrieve lint results. - * @returns {Object|null} The rebuilt lint results, or null if the file is - * changed or not in the filesystem. - */ - getCachedLintResults(filePath) { - - /* - * Cached lint results are valid if and only if: - * 1. The file is present in the filesystem - * 2. The file has not changed since the time it was previously linted - * 3. The ESLint configuration has not changed since the time the file - * was previously linted - * If any of these are not true, we will not reuse the lint results. - */ - - const fileDescriptor = this.fileEntryCache.getFileDescriptor(filePath); - const hashOfConfig = hashOfConfigFor(this.configHelper, filePath); - const changed = fileDescriptor.changed || fileDescriptor.meta.hashOfConfig !== hashOfConfig; - - if (fileDescriptor.notFound || changed) { - return null; - } - - // If source is present but null, need to reread the file from the filesystem. - if (fileDescriptor.meta.results && fileDescriptor.meta.results.source === null) { - fileDescriptor.meta.results.source = fs.readFileSync(filePath, "utf-8"); - } - - return fileDescriptor.meta.results; - } - - /** - * Set the cached lint results for a given file path, after removing any - * information that will be both unnecessary and difficult to serialize. - * Avoids caching results with an "output" property (meaning fixes were - * applied), to prevent potentially incorrect results if fixes are not - * written to disk. - * @param {string} filePath The file for which to set lint results. - * @param {Object} result The lint result to be set for the file. - * @returns {void} - */ - setCachedLintResults(filePath, result) { - if (result && Object.prototype.hasOwnProperty.call(result, "output")) { - return; - } - - const fileDescriptor = this.fileEntryCache.getFileDescriptor(filePath); - - if (fileDescriptor && !fileDescriptor.notFound) { - - // Serialize the result, except that we want to remove the file source if present. - const resultToSerialize = Object.assign({}, result); - - /* - * Set result.source to null. - * In `getCachedLintResults`, if source is explicitly null, we will - * read the file from the filesystem to set the value again. - */ - if (Object.prototype.hasOwnProperty.call(resultToSerialize, "source")) { - resultToSerialize.source = null; - } - - fileDescriptor.meta.results = resultToSerialize; - fileDescriptor.meta.hashOfConfig = hashOfConfigFor(this.configHelper, result.filePath); - } - } - - /** - * Persists the in-memory cache to disk. - * @returns {void} - */ - reconcile() { - this.fileEntryCache.reconcile(); - } -} - -module.exports = LintResultCache; diff --git a/tools/node_modules/eslint/lib/util/logging.js b/tools/node_modules/eslint/lib/util/logging.js deleted file mode 100644 index 3eb898c34f8a88..00000000000000 --- a/tools/node_modules/eslint/lib/util/logging.js +++ /dev/null @@ -1,28 +0,0 @@ -/** - * @fileoverview Handle logging for ESLint - * @author Gyandeep Singh - */ - -"use strict"; - -/* eslint no-console: "off" */ - -/* istanbul ignore next */ -module.exports = { - - /** - * Cover for console.log - * @returns {void} - */ - info(...args) { - console.log(...args); - }, - - /** - * Cover for console.error - * @returns {void} - */ - error(...args) { - console.error(...args); - } -}; diff --git a/tools/node_modules/eslint/lib/util/module-resolver.js b/tools/node_modules/eslint/lib/util/module-resolver.js deleted file mode 100644 index 1e9b663304f832..00000000000000 --- a/tools/node_modules/eslint/lib/util/module-resolver.js +++ /dev/null @@ -1,83 +0,0 @@ -/** - * @fileoverview Implements the Node.js require.resolve algorithm - * @author Nicholas C. Zakas - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const Module = require("module"); - -//------------------------------------------------------------------------------ -// Private -//------------------------------------------------------------------------------ - -const DEFAULT_OPTIONS = { - - /* - * module.paths is an array of paths to search for resolving things relative - * to this file. Module.globalPaths contains all of the special Node.js - * directories that can also be searched for modules. - * - * Need to check for existence of module.paths because Jest seems not to - * include it. See https://github.com/eslint/eslint/issues/5791. - */ - lookupPaths: module.paths ? module.paths.concat(Module.globalPaths) : Module.globalPaths.concat() -}; - -/** - * Resolves modules based on a set of options. - */ -class ModuleResolver { - - /** - * 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 - * lookup paths. - * @param {string} name The module name to resolve. - * @param {string} extraLookupPath An extra path to look into for the module. - * This path is used with the highest priority. - * @returns {string} The resolved file path for the module. - * @throws {Error} If the module cannot be resolved. - */ - resolve(name, extraLookupPath) { - - /* - * First, clone the lookup paths so we're not messing things up for - * subsequent calls to this function. Then, move the extraLookupPath to the - * top of the lookup paths list so it will be searched first. - */ - const lookupPaths = [extraLookupPath, ...this.options.lookupPaths]; - - /** - * Module._findPath is an internal method to Node.js, then one they use to - * lookup file paths when require() is called. So, we are hooking into the - * exact same logic that Node.js uses. - */ - const result = Module._findPath(name, lookupPaths); // eslint-disable-line no-underscore-dangle - - if (!result) { - throw new Error(`Cannot find module '${name}'`); - } - - return result; - } -} - -//------------------------------------------------------------------------------ -// Public API -//------------------------------------------------------------------------------ - -module.exports = ModuleResolver; diff --git a/tools/node_modules/eslint/lib/util/naming.js b/tools/node_modules/eslint/lib/util/naming.js deleted file mode 100644 index aaf00237820b27..00000000000000 --- a/tools/node_modules/eslint/lib/util/naming.js +++ /dev/null @@ -1,107 +0,0 @@ -/** - * @fileoverview Common helpers for naming of plugins, formatters and configs - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const pathUtils = require("../util/path-utils"); - -//------------------------------------------------------------------------------ -// Private -//------------------------------------------------------------------------------ - -const NAMESPACE_REGEX = /^@.*\//i; - -/** - * Brings package name to correct format based on prefix - * @param {string} name The name of the package. - * @param {string} prefix Can be either "eslint-plugin", "eslint-config" or "eslint-formatter" - * @returns {string} Normalized name of the package - * @private - */ -function normalizePackageName(name, prefix) { - let normalizedName = name; - - /** - * On Windows, name can come in with Windows slashes instead of Unix slashes. - * Normalize to Unix first to avoid errors later on. - * https://github.com/eslint/eslint/issues/5644 - */ - if (normalizedName.indexOf("\\") > -1) { - normalizedName = pathUtils.convertPathToPosix(normalizedName); - } - - if (normalizedName.charAt(0) === "@") { - - /** - * it's a scoped package - * package name is the prefix, or just a username - */ - const scopedPackageShortcutRegex = new RegExp(`^(@[^/]+)(?:/(?:${prefix})?)?$`), - scopedPackageNameRegex = new RegExp(`^${prefix}(-|$)`); - - if (scopedPackageShortcutRegex.test(normalizedName)) { - normalizedName = normalizedName.replace(scopedPackageShortcutRegex, `$1/${prefix}`); - } else if (!scopedPackageNameRegex.test(normalizedName.split("/")[1])) { - - /** - * for scoped packages, insert the prefix after the first / unless - * the path is already @scope/eslint or @scope/eslint-xxx-yyy - */ - normalizedName = normalizedName.replace(/^@([^/]+)\/(.*)$/, `@$1/${prefix}-$2`); - } - } else if (normalizedName.indexOf(`${prefix}-`) !== 0) { - normalizedName = `${prefix}-${normalizedName}`; - } - - return normalizedName; -} - -/** - * Removes the prefix from a fullname. - * @param {string} fullname The term which may have the prefix. - * @param {string} prefix The prefix to remove. - * @returns {string} The term without prefix. - */ -function getShorthandName(fullname, prefix) { - if (fullname[0] === "@") { - let matchResult = new RegExp(`^(@[^/]+)/${prefix}$`).exec(fullname); - - if (matchResult) { - return matchResult[1]; - } - - matchResult = new RegExp(`^(@[^/]+)/${prefix}-(.+)$`).exec(fullname); - if (matchResult) { - return `${matchResult[1]}/${matchResult[2]}`; - } - } else if (fullname.startsWith(`${prefix}-`)) { - return fullname.slice(prefix.length + 1); - } - - return fullname; -} - -/** - * Gets the scope (namespace) of a term. - * @param {string} term The term which may have the namespace. - * @returns {string} The namepace of the term if it has one. - */ -function getNamespaceFromTerm(term) { - const match = term.match(NAMESPACE_REGEX); - - return match ? match[0] : ""; -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = { - normalizePackageName, - getShorthandName, - getNamespaceFromTerm -}; diff --git a/tools/node_modules/eslint/lib/util/node-event-generator.js b/tools/node_modules/eslint/lib/util/node-event-generator.js deleted file mode 100644 index 1ae56643196cd1..00000000000000 --- a/tools/node_modules/eslint/lib/util/node-event-generator.js +++ /dev/null @@ -1,308 +0,0 @@ -/** - * @fileoverview The event generator for AST nodes. - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const esquery = require("esquery"); -const lodash = require("lodash"); - -//------------------------------------------------------------------------------ -// Typedefs -//------------------------------------------------------------------------------ - -/** - * An object describing an AST selector - * @typedef {Object} ASTSelector - * @property {string} rawSelector The string that was parsed into this selector - * @property {boolean} isExit `true` if this should be emitted when exiting the node rather than when entering - * @property {Object} parsedSelector An object (from esquery) describing the matching behavior of the selector - * @property {string[]|null} listenerTypes A list of node types that could possibly cause the selector to match, - * or `null` if all node types could cause a match - * @property {number} attributeCount The total number of classes, pseudo-classes, and attribute queries in this selector - * @property {number} identifierCount The total number of identifier queries in this selector - */ - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Gets the possible types of a selector - * @param {Object} parsedSelector An object (from esquery) describing the matching behavior of the selector - * @returns {string[]|null} The node types that could possibly trigger this selector, or `null` if all node types could trigger it - */ -function getPossibleTypes(parsedSelector) { - switch (parsedSelector.type) { - case "identifier": - return [parsedSelector.value]; - - case "matches": { - const typesForComponents = parsedSelector.selectors.map(getPossibleTypes); - - if (typesForComponents.every(Boolean)) { - return lodash.union(...typesForComponents); - } - return null; - } - - case "compound": { - const typesForComponents = parsedSelector.selectors.map(getPossibleTypes).filter(typesForComponent => typesForComponent); - - // If all of the components could match any type, then the compound could also match any type. - if (!typesForComponents.length) { - return null; - } - - /* - * If at least one of the components could only match a particular type, the compound could only match - * the intersection of those types. - */ - return lodash.intersection(...typesForComponents); - } - - case "child": - case "descendant": - case "sibling": - case "adjacent": - return getPossibleTypes(parsedSelector.right); - - default: - return null; - - } -} - -/** - * Counts the number of class, pseudo-class, and attribute queries in this selector - * @param {Object} parsedSelector An object (from esquery) describing the selector's matching behavior - * @returns {number} The number of class, pseudo-class, and attribute queries in this selector - */ -function countClassAttributes(parsedSelector) { - switch (parsedSelector.type) { - case "child": - case "descendant": - case "sibling": - case "adjacent": - return countClassAttributes(parsedSelector.left) + countClassAttributes(parsedSelector.right); - - case "compound": - case "not": - case "matches": - return parsedSelector.selectors.reduce((sum, childSelector) => sum + countClassAttributes(childSelector), 0); - - case "attribute": - case "field": - case "nth-child": - case "nth-last-child": - return 1; - - default: - return 0; - } -} - -/** - * Counts the number of identifier queries in this selector - * @param {Object} parsedSelector An object (from esquery) describing the selector's matching behavior - * @returns {number} The number of identifier queries - */ -function countIdentifiers(parsedSelector) { - switch (parsedSelector.type) { - case "child": - case "descendant": - case "sibling": - case "adjacent": - return countIdentifiers(parsedSelector.left) + countIdentifiers(parsedSelector.right); - - case "compound": - case "not": - case "matches": - return parsedSelector.selectors.reduce((sum, childSelector) => sum + countIdentifiers(childSelector), 0); - - case "identifier": - return 1; - - default: - return 0; - } -} - -/** - * Compares the specificity of two selector objects, with CSS-like rules. - * @param {ASTSelector} selectorA An AST selector descriptor - * @param {ASTSelector} selectorB Another AST selector descriptor - * @returns {number} - * a value less than 0 if selectorA is less specific than selectorB - * a value greater than 0 if selectorA is more specific than selectorB - * a value less than 0 if selectorA and selectorB have the same specificity, and selectorA <= selectorB alphabetically - * a value greater than 0 if selectorA and selectorB have the same specificity, and selectorA > selectorB alphabetically - */ -function compareSpecificity(selectorA, selectorB) { - return selectorA.attributeCount - selectorB.attributeCount || - selectorA.identifierCount - selectorB.identifierCount || - (selectorA.rawSelector <= selectorB.rawSelector ? -1 : 1); -} - -/** - * Parses a raw selector string, and throws a useful error if parsing fails. - * @param {string} rawSelector A raw AST selector - * @returns {Object} An object (from esquery) describing the matching behavior of this selector - * @throws {Error} An error if the selector is invalid - */ -function tryParseSelector(rawSelector) { - try { - return esquery.parse(rawSelector.replace(/:exit$/, "")); - } catch (err) { - if (typeof err.offset === "number") { - throw new SyntaxError(`Syntax error in selector "${rawSelector}" at position ${err.offset}: ${err.message}`); - } - throw err; - } -} - -/** - * Parses a raw selector string, and returns the parsed selector along with specificity and type information. - * @param {string} rawSelector A raw AST selector - * @returns {ASTSelector} A selector descriptor - */ -const parseSelector = lodash.memoize(rawSelector => { - const parsedSelector = tryParseSelector(rawSelector); - - return { - rawSelector, - isExit: rawSelector.endsWith(":exit"), - parsedSelector, - listenerTypes: getPossibleTypes(parsedSelector), - attributeCount: countClassAttributes(parsedSelector), - identifierCount: countIdentifiers(parsedSelector) - }; -}); - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -/** - * The event generator for AST nodes. - * This implements below interface. - * - * ```ts - * interface EventGenerator { - * emitter: SafeEmitter; - * enterNode(node: ASTNode): void; - * leaveNode(node: ASTNode): void; - * } - * ``` - */ -class NodeEventGenerator { - - /** - * @param {SafeEmitter} emitter - * An SafeEmitter which is the destination of events. This emitter must already - * have registered listeners for all of the events that it needs to listen for. - * (See lib/util/safe-emitter.js for more details on `SafeEmitter`.) - * @returns {NodeEventGenerator} new instance - */ - constructor(emitter) { - this.emitter = emitter; - this.currentAncestry = []; - this.enterSelectorsByNodeType = new Map(); - this.exitSelectorsByNodeType = new Map(); - this.anyTypeEnterSelectors = []; - this.anyTypeExitSelectors = []; - - emitter.eventNames().forEach(rawSelector => { - const selector = parseSelector(rawSelector); - - if (selector.listenerTypes) { - selector.listenerTypes.forEach(nodeType => { - const typeMap = selector.isExit ? this.exitSelectorsByNodeType : this.enterSelectorsByNodeType; - - if (!typeMap.has(nodeType)) { - typeMap.set(nodeType, []); - } - typeMap.get(nodeType).push(selector); - }); - } else { - (selector.isExit ? this.anyTypeExitSelectors : this.anyTypeEnterSelectors).push(selector); - } - }); - - this.anyTypeEnterSelectors.sort(compareSpecificity); - this.anyTypeExitSelectors.sort(compareSpecificity); - this.enterSelectorsByNodeType.forEach(selectorList => selectorList.sort(compareSpecificity)); - this.exitSelectorsByNodeType.forEach(selectorList => selectorList.sort(compareSpecificity)); - } - - /** - * Checks a selector against a node, and emits it if it matches - * @param {ASTNode} node The node to check - * @param {ASTSelector} selector An AST selector descriptor - * @returns {void} - */ - applySelector(node, selector) { - if (esquery.matches(node, selector.parsedSelector, this.currentAncestry)) { - this.emitter.emit(selector.rawSelector, node); - } - } - - /** - * Applies all appropriate selectors to a node, in specificity order - * @param {ASTNode} node The node to check - * @param {boolean} isExit `false` if the node is currently being entered, `true` if it's currently being exited - * @returns {void} - */ - applySelectors(node, isExit) { - const selectorsByNodeType = (isExit ? this.exitSelectorsByNodeType : this.enterSelectorsByNodeType).get(node.type) || []; - const anyTypeSelectors = isExit ? this.anyTypeExitSelectors : this.anyTypeEnterSelectors; - - /* - * selectorsByNodeType and anyTypeSelectors were already sorted by specificity in the constructor. - * Iterate through each of them, applying selectors in the right order. - */ - let selectorsByTypeIndex = 0; - let anyTypeSelectorsIndex = 0; - - while (selectorsByTypeIndex < selectorsByNodeType.length || anyTypeSelectorsIndex < anyTypeSelectors.length) { - if ( - selectorsByTypeIndex >= selectorsByNodeType.length || - anyTypeSelectorsIndex < anyTypeSelectors.length && - compareSpecificity(anyTypeSelectors[anyTypeSelectorsIndex], selectorsByNodeType[selectorsByTypeIndex]) < 0 - ) { - this.applySelector(node, anyTypeSelectors[anyTypeSelectorsIndex++]); - } else { - this.applySelector(node, selectorsByNodeType[selectorsByTypeIndex++]); - } - } - } - - /** - * Emits an event of entering AST node. - * @param {ASTNode} node - A node which was entered. - * @returns {void} - */ - enterNode(node) { - if (node.parent) { - this.currentAncestry.unshift(node.parent); - } - this.applySelectors(node, false); - } - - /** - * Emits an event of leaving AST node. - * @param {ASTNode} node - A node which was left. - * @returns {void} - */ - leaveNode(node) { - this.applySelectors(node, true); - this.currentAncestry.shift(); - } -} - -module.exports = NodeEventGenerator; diff --git a/tools/node_modules/eslint/lib/util/npm-utils.js b/tools/node_modules/eslint/lib/util/npm-utils.js deleted file mode 100644 index ddf8f24cc76993..00000000000000 --- a/tools/node_modules/eslint/lib/util/npm-utils.js +++ /dev/null @@ -1,183 +0,0 @@ -/** - * @fileoverview Utility for executing npm commands. - * @author Ian VanSchooten - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const fs = require("fs"), - spawn = require("cross-spawn"), - path = require("path"), - log = require("./logging"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Find the closest package.json file, starting at process.cwd (by default), - * and working up to root. - * - * @param {string} [startDir=process.cwd()] Starting directory - * @returns {string} Absolute path to closest package.json file - */ -function findPackageJson(startDir) { - let dir = path.resolve(startDir || process.cwd()); - - do { - const pkgFile = path.join(dir, "package.json"); - - if (!fs.existsSync(pkgFile) || !fs.statSync(pkgFile).isFile()) { - dir = path.join(dir, ".."); - continue; - } - return pkgFile; - } while (dir !== path.resolve(dir, "..")); - return null; -} - -//------------------------------------------------------------------------------ -// Private -//------------------------------------------------------------------------------ - -/** - * Install node modules synchronously and save to devDependencies in package.json - * @param {string|string[]} packages Node module or modules to install - * @returns {void} - */ -function installSyncSaveDev(packages) { - const packageList = Array.isArray(packages) ? packages : [packages]; - const npmProcess = spawn.sync("npm", ["i", "--save-dev"].concat(packageList), - { stdio: "inherit" }); - const error = npmProcess.error; - - if (error && error.code === "ENOENT") { - const pluralS = packageList.length > 1 ? "s" : ""; - - log.error(`Could not execute npm. Please install the following package${pluralS} with a package manager of your choice: ${packageList.join(", ")}`); - } -} - -/** - * Fetch `peerDependencies` of the given package by `npm show` command. - * @param {string} packageName The package name to fetch peerDependencies. - * @returns {Object} Gotten peerDependencies. Returns null if npm was not found. - */ -function fetchPeerDependencies(packageName) { - const npmProcess = spawn.sync( - "npm", - ["show", "--json", packageName, "peerDependencies"], - { encoding: "utf8" } - ); - - const error = npmProcess.error; - - if (error && error.code === "ENOENT") { - return null; - } - const fetchedText = npmProcess.stdout.trim(); - - return JSON.parse(fetchedText || "{}"); - - -} - -/** - * Check whether node modules are include in a project's package.json. - * - * @param {string[]} packages Array of node module names - * @param {Object} opt Options Object - * @param {boolean} opt.dependencies Set to true to check for direct dependencies - * @param {boolean} opt.devDependencies Set to true to check for development dependencies - * @param {boolean} opt.startdir Directory to begin searching from - * @returns {Object} An object whose keys are the module names - * and values are booleans indicating installation. - */ -function check(packages, opt) { - let deps = []; - const pkgJson = (opt) ? findPackageJson(opt.startDir) : findPackageJson(); - let fileJson; - - if (!pkgJson) { - throw new Error("Could not find a package.json file. Run 'npm init' to create one."); - } - - try { - fileJson = JSON.parse(fs.readFileSync(pkgJson, "utf8")); - } catch (e) { - const error = new Error(e); - - error.messageTemplate = "failed-to-read-json"; - error.messageData = { - path: pkgJson, - message: e.message - }; - throw error; - } - - if (opt.devDependencies && typeof fileJson.devDependencies === "object") { - deps = deps.concat(Object.keys(fileJson.devDependencies)); - } - if (opt.dependencies && typeof fileJson.dependencies === "object") { - deps = deps.concat(Object.keys(fileJson.dependencies)); - } - return packages.reduce((status, pkg) => { - status[pkg] = deps.indexOf(pkg) !== -1; - return status; - }, {}); -} - -/** - * Check whether node modules are included in the dependencies of a project's - * package.json. - * - * Convienience wrapper around check(). - * - * @param {string[]} packages Array of node modules to check. - * @param {string} rootDir The directory contianing a package.json - * @returns {Object} An object whose keys are the module names - * and values are booleans indicating installation. - */ -function checkDeps(packages, rootDir) { - return check(packages, { dependencies: true, startDir: rootDir }); -} - -/** - * Check whether node modules are included in the devDependencies of a project's - * package.json. - * - * Convienience wrapper around check(). - * - * @param {string[]} packages Array of node modules to check. - * @returns {Object} An object whose keys are the module names - * and values are booleans indicating installation. - */ -function checkDevDeps(packages) { - return check(packages, { devDependencies: true }); -} - -/** - * Check whether package.json is found in current path. - * - * @param {string=} startDir Starting directory - * @returns {boolean} Whether a package.json is found in current path. - */ -function checkPackageJson(startDir) { - return !!findPackageJson(startDir); -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = { - installSyncSaveDev, - fetchPeerDependencies, - checkDeps, - checkDevDeps, - checkPackageJson -}; diff --git a/tools/node_modules/eslint/lib/util/path-utils.js b/tools/node_modules/eslint/lib/util/path-utils.js deleted file mode 100644 index 07cf4e790664ae..00000000000000 --- a/tools/node_modules/eslint/lib/util/path-utils.js +++ /dev/null @@ -1,72 +0,0 @@ -/** - * @fileoverview Common helpers for operations on filenames and paths - * @author Ian VanSchooten - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const path = require("path"); - -//------------------------------------------------------------------------------ -// Private -//------------------------------------------------------------------------------ - -/** - * Replace Windows with posix style paths - * - * @param {string} filepath Path to convert - * @returns {string} Converted filepath - */ -function convertPathToPosix(filepath) { - const normalizedFilepath = path.normalize(filepath); - const posixFilepath = normalizedFilepath.replace(/\\/g, "/"); - - return posixFilepath; -} - -/** - * Converts an absolute filepath to a relative path from a given base path - * - * For example, if the filepath is `/my/awesome/project/foo.bar`, - * and the base directory is `/my/awesome/project/`, - * then this function should return `foo.bar`. - * - * path.relative() does something similar, but it requires a baseDir (`from` argument). - * This function makes it optional and just removes a leading slash if the baseDir is not given. - * - * It does not take into account symlinks (for now). - * - * @param {string} filepath Path to convert to relative path. If already relative, - * it will be assumed to be relative to process.cwd(), - * converted to absolute, and then processed. - * @param {string} [baseDir] Absolute base directory to resolve the filepath from. - * If not provided, all this function will do is remove - * a leading slash. - * @returns {string} Relative filepath - */ -function getRelativePath(filepath, baseDir) { - const absolutePath = path.isAbsolute(filepath) - ? filepath - : path.resolve(filepath); - - if (baseDir) { - if (!path.isAbsolute(baseDir)) { - throw new Error(`baseDir should be an absolute path: ${baseDir}`); - } - return path.relative(baseDir, absolutePath); - } - return absolutePath.replace(/^\//, ""); - -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = { - convertPathToPosix, - getRelativePath -}; diff --git a/tools/node_modules/eslint/lib/util/patterns/letters.js b/tools/node_modules/eslint/lib/util/patterns/letters.js deleted file mode 100644 index eb255d8f001b70..00000000000000 --- a/tools/node_modules/eslint/lib/util/patterns/letters.js +++ /dev/null @@ -1,36 +0,0 @@ -/** - * @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/node_modules/eslint/lib/util/report-translator.js b/tools/node_modules/eslint/lib/util/report-translator.js deleted file mode 100644 index 3dfdca0e4944d3..00000000000000 --- a/tools/node_modules/eslint/lib/util/report-translator.js +++ /dev/null @@ -1,281 +0,0 @@ -/** - * @fileoverview A helper that translates context.report() calls from the rule API into generic problem objects - * @author Teddy Katz - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const assert = require("assert"); -const ruleFixer = require("./rule-fixer"); -const interpolate = require("./interpolate"); - -//------------------------------------------------------------------------------ -// Typedefs -//------------------------------------------------------------------------------ - -/** - * An error message description - * @typedef {Object} MessageDescriptor - * @property {ASTNode} [node] The reported node - * @property {Location} loc The location of the problem. - * @property {string} message The problem message. - * @property {Object} [data] Optional data to use to fill in placeholders in the - * message. - * @property {Function} [fix] The function to call that creates a fix command. - */ - -/** - * Information about the report - * @typedef {Object} ReportInfo - * @property {string} ruleId - * @property {(0|1|2)} severity - * @property {(string|undefined)} message - * @property {(string|undefined)} messageId - * @property {number} line - * @property {number} column - * @property {(number|undefined)} endLine - * @property {(number|undefined)} endColumn - * @property {(string|null)} nodeType - * @property {string} source - * @property {({text: string, range: (number[]|null)}|null)} fix - */ - -//------------------------------------------------------------------------------ -// Module Definition -//------------------------------------------------------------------------------ - - -/** - * Translates a multi-argument context.report() call into a single object argument call - * @param {...*} args A list of arguments passed to `context.report` - * @returns {MessageDescriptor} A normalized object containing report information - */ -function normalizeMultiArgReportCall(...args) { - - // If there is one argument, it is considered to be a new-style call already. - if (args.length === 1) { - - // Shallow clone the object to avoid surprises if reusing the descriptor - return Object.assign({}, args[0]); - } - - // If the second argument is a string, the arguments are interpreted as [node, message, data, fix]. - if (typeof args[1] === "string") { - return { - node: args[0], - message: args[1], - data: args[2], - fix: args[3] - }; - } - - // Otherwise, the arguments are interpreted as [node, loc, message, data, fix]. - return { - node: args[0], - loc: args[1], - message: args[2], - data: args[3], - fix: args[4] - }; -} - -/** - * Asserts that either a loc or a node was provided, and the node is valid if it was provided. - * @param {MessageDescriptor} descriptor A descriptor to validate - * @returns {void} - * @throws AssertionError if neither a node nor a loc was provided, or if the node is not an object - */ -function assertValidNodeInfo(descriptor) { - if (descriptor.node) { - assert(typeof descriptor.node === "object", "Node must be an object"); - } else { - assert(descriptor.loc, "Node must be provided when reporting error if location is not provided"); - } -} - -/** - * Normalizes a MessageDescriptor to always have a `loc` with `start` and `end` properties - * @param {MessageDescriptor} descriptor A descriptor for the report from a rule. - * @returns {{start: Location, end: (Location|null)}} An updated location that infers the `start` and `end` properties - * from the `node` of the original descriptor, or infers the `start` from the `loc` of the original descriptor. - */ -function normalizeReportLoc(descriptor) { - if (descriptor.loc) { - if (descriptor.loc.start) { - return descriptor.loc; - } - return { start: descriptor.loc, end: null }; - } - return descriptor.node.loc; -} - -/** - * Compares items in a fixes array by range. - * @param {Fix} a The first message. - * @param {Fix} b The second message. - * @returns {int} -1 if a comes before b, 1 if a comes after b, 0 if equal. - * @private - */ -function compareFixesByRange(a, b) { - return a.range[0] - b.range[0] || a.range[1] - b.range[1]; -} - -/** - * Merges the given fixes array into one. - * @param {Fix[]} fixes The fixes to merge. - * @param {SourceCode} sourceCode The source code object to get the text between fixes. - * @returns {{text: string, range: number[]}} The merged fixes - */ -function mergeFixes(fixes, sourceCode) { - if (fixes.length === 0) { - return null; - } - if (fixes.length === 1) { - return fixes[0]; - } - - fixes.sort(compareFixesByRange); - - const originalText = sourceCode.text; - const start = fixes[0].range[0]; - const end = fixes[fixes.length - 1].range[1]; - let text = ""; - let lastPos = Number.MIN_SAFE_INTEGER; - - for (const fix of fixes) { - assert(fix.range[0] >= lastPos, "Fix objects must not be overlapped in a report."); - - if (fix.range[0] >= 0) { - text += originalText.slice(Math.max(0, start, lastPos), fix.range[0]); - } - text += fix.text; - lastPos = fix.range[1]; - } - text += originalText.slice(Math.max(0, start, lastPos), end); - - return { range: [start, end], text }; -} - -/** - * Gets one fix object from the given descriptor. - * If the descriptor retrieves multiple fixes, this merges those to one. - * @param {MessageDescriptor} descriptor The report descriptor. - * @param {SourceCode} sourceCode The source code object to get text between fixes. - * @returns {({text: string, range: number[]}|null)} The fix for the descriptor - */ -function normalizeFixes(descriptor, sourceCode) { - if (typeof descriptor.fix !== "function") { - return null; - } - - // @type {null | Fix | Fix[] | IterableIterator} - const fix = descriptor.fix(ruleFixer); - - // Merge to one. - if (fix && Symbol.iterator in fix) { - return mergeFixes(Array.from(fix), sourceCode); - } - return fix; -} - -/** - * Creates information about the report from a descriptor - * @param {Object} options Information about the problem - * @param {string} options.ruleId Rule ID - * @param {(0|1|2)} options.severity Rule severity - * @param {(ASTNode|null)} options.node Node - * @param {string} options.message Error message - * @param {string} [options.messageId] The error message ID. - * @param {{start: SourceLocation, end: (SourceLocation|null)}} options.loc Start and end location - * @param {{text: string, range: (number[]|null)}} options.fix The fix object - * @returns {function(...args): ReportInfo} Function that returns information about the report - */ -function createProblem(options) { - const problem = { - ruleId: options.ruleId, - severity: options.severity, - message: options.message, - line: options.loc.start.line, - column: options.loc.start.column + 1, - nodeType: options.node && options.node.type || null - }; - - /* - * If this isn’t in the conditional, some of the tests fail - * because `messageId` is present in the problem object - */ - if (options.messageId) { - problem.messageId = options.messageId; - } - - if (options.loc.end) { - problem.endLine = options.loc.end.line; - problem.endColumn = options.loc.end.column + 1; - } - - if (options.fix) { - problem.fix = options.fix; - } - - return problem; -} - -/** - * Returns a function that converts the arguments of a `context.report` call from a rule into a reported - * problem for the Node.js API. - * @param {{ruleId: string, severity: number, sourceCode: SourceCode, messageIds: Object}} metadata Metadata for the reported problem - * @param {SourceCode} sourceCode The `SourceCode` instance for the text being linted - * @returns {function(...args): ReportInfo} Function that returns information about the report - */ - -module.exports = function createReportTranslator(metadata) { - - /* - * `createReportTranslator` gets called once per enabled rule per file. It needs to be very performant. - * The report translator itself (i.e. the function that `createReportTranslator` returns) gets - * called every time a rule reports a problem, which happens much less frequently (usually, the vast - * majority of rules don't report any problems for a given file). - */ - return (...args) => { - const descriptor = normalizeMultiArgReportCall(...args); - - assertValidNodeInfo(descriptor); - - let computedMessage; - - if (descriptor.messageId) { - if (!metadata.messageIds) { - throw new TypeError("context.report() called with a messageId, but no messages were present in the rule metadata."); - } - const id = descriptor.messageId; - const messages = metadata.messageIds; - - if (descriptor.message) { - throw new TypeError("context.report() called with a message and a messageId. Please only pass one."); - } - if (!messages || !Object.prototype.hasOwnProperty.call(messages, id)) { - throw new TypeError(`context.report() called with a messageId of '${id}' which is not present in the 'messages' config: ${JSON.stringify(messages, null, 2)}`); - } - computedMessage = messages[id]; - } else if (descriptor.message) { - computedMessage = descriptor.message; - } else { - throw new TypeError("Missing `message` property in report() call; add a message that describes the linting problem."); - } - - - return createProblem({ - ruleId: metadata.ruleId, - severity: metadata.severity, - node: descriptor.node, - message: interpolate(computedMessage, descriptor.data), - messageId: descriptor.messageId, - loc: normalizeReportLoc(descriptor), - fix: normalizeFixes(descriptor, metadata.sourceCode) - }); - }; -}; diff --git a/tools/node_modules/eslint/lib/util/rule-fixer.js b/tools/node_modules/eslint/lib/util/rule-fixer.js deleted file mode 100644 index bdd80d13b162d4..00000000000000 --- a/tools/node_modules/eslint/lib/util/rule-fixer.js +++ /dev/null @@ -1,140 +0,0 @@ -/** - * @fileoverview An object that creates fix commands for rules. - * @author Nicholas C. Zakas - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -// none! - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Creates a fix command that inserts text at the specified index in the source text. - * @param {int} index The 0-based index at which to insert the new text. - * @param {string} text The text to insert. - * @returns {Object} The fix command. - * @private - */ -function insertTextAt(index, text) { - return { - range: [index, index], - text - }; -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -/** - * Creates code fixing commands for rules. - */ - -const ruleFixer = Object.freeze({ - - /** - * Creates a fix command that inserts text after the given node or token. - * The fix is not applied until applyFixes() is called. - * @param {ASTNode|Token} nodeOrToken The node or token to insert after. - * @param {string} text The text to insert. - * @returns {Object} The fix command. - */ - insertTextAfter(nodeOrToken, text) { - return this.insertTextAfterRange(nodeOrToken.range, text); - }, - - /** - * Creates a fix command that inserts text after the specified range in the source text. - * The fix is not applied until applyFixes() is called. - * @param {int[]} range The range to replace, first item is start of range, second - * is end of range. - * @param {string} text The text to insert. - * @returns {Object} The fix command. - */ - insertTextAfterRange(range, text) { - return insertTextAt(range[1], text); - }, - - /** - * Creates a fix command that inserts text before the given node or token. - * The fix is not applied until applyFixes() is called. - * @param {ASTNode|Token} nodeOrToken The node or token to insert before. - * @param {string} text The text to insert. - * @returns {Object} The fix command. - */ - insertTextBefore(nodeOrToken, text) { - return this.insertTextBeforeRange(nodeOrToken.range, text); - }, - - /** - * Creates a fix command that inserts text before the specified range in the source text. - * The fix is not applied until applyFixes() is called. - * @param {int[]} range The range to replace, first item is start of range, second - * is end of range. - * @param {string} text The text to insert. - * @returns {Object} The fix command. - */ - insertTextBeforeRange(range, text) { - return insertTextAt(range[0], text); - }, - - /** - * Creates a fix command that replaces text at the node or token. - * The fix is not applied until applyFixes() is called. - * @param {ASTNode|Token} nodeOrToken The node or token to remove. - * @param {string} text The text to insert. - * @returns {Object} The fix command. - */ - replaceText(nodeOrToken, text) { - return this.replaceTextRange(nodeOrToken.range, text); - }, - - /** - * Creates a fix command that replaces text at the specified range in the source text. - * The fix is not applied until applyFixes() is called. - * @param {int[]} range The range to replace, first item is start of range, second - * is end of range. - * @param {string} text The text to insert. - * @returns {Object} The fix command. - */ - replaceTextRange(range, text) { - return { - range, - text - }; - }, - - /** - * Creates a fix command that removes the node or token from the source. - * The fix is not applied until applyFixes() is called. - * @param {ASTNode|Token} nodeOrToken The node or token to remove. - * @returns {Object} The fix command. - */ - remove(nodeOrToken) { - return this.removeRange(nodeOrToken.range); - }, - - /** - * Creates a fix command that removes the specified range of text from the source. - * The fix is not applied until applyFixes() is called. - * @param {int[]} range The range to remove, first item is start of range, second - * is end of range. - * @returns {Object} The fix command. - */ - removeRange(range) { - return { - range, - text: "" - }; - } - -}); - - -module.exports = ruleFixer; diff --git a/tools/node_modules/eslint/lib/util/safe-emitter.js b/tools/node_modules/eslint/lib/util/safe-emitter.js deleted file mode 100644 index ab212230d398e4..00000000000000 --- a/tools/node_modules/eslint/lib/util/safe-emitter.js +++ /dev/null @@ -1,52 +0,0 @@ -/** - * @fileoverview A variant of EventEmitter which does not give listeners information about each other - * @author Teddy Katz - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Typedefs -//------------------------------------------------------------------------------ - -/** - * An event emitter - * @typedef {Object} SafeEmitter - * @property {function(eventName: string, listenerFunc: Function): void} on Adds a listener for a given event name - * @property {function(eventName: string, arg1?: any, arg2?: any, arg3?: any)} emit Emits an event with a given name. - * This calls all the listeners that were listening for that name, with `arg1`, `arg2`, and `arg3` as arguments. - * @property {function(): string[]} eventNames Gets the list of event names that have registered listeners. - */ - -/** - * Creates an object which can listen for and emit events. - * This is similar to the EventEmitter API in Node's standard library, but it has a few differences. - * The goal is to allow multiple modules to attach arbitrary listeners to the same emitter, without - * letting the modules know about each other at all. - * 1. It has no special keys like `error` and `newListener`, which would allow modules to detect when - * another module throws an error or registers a listener. - * 2. It calls listener functions without any `this` value. (`EventEmitter` calls listeners with a - * `this` value of the emitter instance, which would give listeners access to other listeners.) - * @returns {SafeEmitter} An emitter - */ -module.exports = () => { - const listeners = Object.create(null); - - return Object.freeze({ - on(eventName, listener) { - if (eventName in listeners) { - listeners[eventName].push(listener); - } else { - listeners[eventName] = [listener]; - } - }, - emit(eventName, ...args) { - if (eventName in listeners) { - listeners[eventName].forEach(listener => listener(...args)); - } - }, - eventNames() { - return Object.keys(listeners); - } - }); -}; diff --git a/tools/node_modules/eslint/lib/util/source-code-fixer.js b/tools/node_modules/eslint/lib/util/source-code-fixer.js deleted file mode 100644 index 53dc1dc6be73c4..00000000000000 --- a/tools/node_modules/eslint/lib/util/source-code-fixer.js +++ /dev/null @@ -1,152 +0,0 @@ -/** - * @fileoverview An object that caches and applies source code fixes. - * @author Nicholas C. Zakas - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const debug = require("debug")("eslint:source-code-fixer"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const BOM = "\uFEFF"; - -/** - * Compares items in a messages array by range. - * @param {Message} a The first message. - * @param {Message} b The second message. - * @returns {int} -1 if a comes before b, 1 if a comes after b, 0 if equal. - * @private - */ -function compareMessagesByFixRange(a, b) { - return a.fix.range[0] - b.fix.range[0] || a.fix.range[1] - b.fix.range[1]; -} - -/** - * Compares items in a messages array by line and column. - * @param {Message} a The first message. - * @param {Message} b The second message. - * @returns {int} -1 if a comes before b, 1 if a comes after b, 0 if equal. - * @private - */ -function compareMessagesByLocation(a, b) { - return a.line - b.line || a.column - b.column; -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -/** - * Utility for apply fixes to source code. - * @constructor - */ -function SourceCodeFixer() { - Object.freeze(this); -} - -/** - * Applies the fixes specified by the messages to the given text. Tries to be - * smart about the fixes and won't apply fixes over the same area in the text. - * @param {string} sourceText The text to apply the changes to. - * @param {Message[]} messages The array of messages reported by ESLint. - * @param {boolean|Function} [shouldFix=true] Determines whether each message should be fixed - * @returns {Object} An object containing the fixed text and any unfixed messages. - */ -SourceCodeFixer.applyFixes = function(sourceText, messages, shouldFix) { - debug("Applying fixes"); - - if (shouldFix === false) { - debug("shouldFix parameter was false, not attempting fixes"); - return { - fixed: false, - messages, - output: sourceText - }; - } - - // clone the array - const remainingMessages = [], - fixes = [], - bom = sourceText.startsWith(BOM) ? BOM : "", - text = bom ? sourceText.slice(1) : sourceText; - let lastPos = Number.NEGATIVE_INFINITY, - output = bom; - - /** - * Try to use the 'fix' from a problem. - * @param {Message} problem The message object to apply fixes from - * @returns {boolean} Whether fix was successfully applied - */ - function attemptFix(problem) { - const fix = problem.fix; - const start = fix.range[0]; - const end = fix.range[1]; - - // Remain it as a problem if it's overlapped or it's a negative range - if (lastPos >= start || start > end) { - remainingMessages.push(problem); - return false; - } - - // Remove BOM. - if ((start < 0 && end >= 0) || (start === 0 && fix.text.startsWith(BOM))) { - output = ""; - } - - // Make output to this fix. - output += text.slice(Math.max(0, lastPos), Math.max(0, start)); - output += fix.text; - lastPos = end; - return true; - } - - messages.forEach(problem => { - if (Object.prototype.hasOwnProperty.call(problem, "fix")) { - fixes.push(problem); - } else { - remainingMessages.push(problem); - } - }); - - if (fixes.length) { - debug("Found fixes to apply"); - let fixesWereApplied = false; - - for (const problem of fixes.sort(compareMessagesByFixRange)) { - if (typeof shouldFix !== "function" || shouldFix(problem)) { - attemptFix(problem); - - /* - * The only time attemptFix will fail is if a previous fix was - * applied which conflicts with it. So we can mark this as true. - */ - fixesWereApplied = true; - } else { - remainingMessages.push(problem); - } - } - output += text.slice(Math.max(0, lastPos)); - - return { - fixed: fixesWereApplied, - messages: remainingMessages.sort(compareMessagesByLocation), - output - }; - } - - debug("No fixes to apply"); - return { - fixed: false, - messages, - output: bom + text - }; - -}; - -module.exports = SourceCodeFixer; diff --git a/tools/node_modules/eslint/lib/util/source-code-utils.js b/tools/node_modules/eslint/lib/util/source-code-utils.js deleted file mode 100644 index cac13d37067dfc..00000000000000 --- a/tools/node_modules/eslint/lib/util/source-code-utils.js +++ /dev/null @@ -1,105 +0,0 @@ -/** - * @fileoverview Tools for obtaining SourceCode objects. - * @author Ian VanSchooten - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const CLIEngine = require("../cli-engine"), - globUtils = require("./glob-utils"), - baseDefaultOptions = require("../../conf/default-cli-options"); - -const debug = require("debug")("eslint:source-code-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Get the SourceCode object for a single file - * @param {string} filename The fully resolved filename to get SourceCode from. - * @param {Object} options A CLIEngine options object. - * @returns {Array} Array of the SourceCode object representing the file - * and fatal error message. - */ -function getSourceCodeOfFile(filename, options) { - debug("getting sourceCode of", filename); - const opts = Object.assign({}, options, { rules: {} }); - const cli = new CLIEngine(opts); - const results = cli.executeOnFiles([filename]); - - if (results && results.results[0] && results.results[0].messages[0] && results.results[0].messages[0].fatal) { - const msg = results.results[0].messages[0]; - - throw new Error(`(${filename}:${msg.line}:${msg.column}) ${msg.message}`); - } - const sourceCode = cli.linter.getSourceCode(); - - return sourceCode; -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - - -/** - * This callback is used to measure execution status in a progress bar - * @callback progressCallback - * @param {number} The total number of times the callback will be called. - */ - -/** - * Gets the SourceCode of a single file, or set of files. - * @param {string[]|string} patterns A filename, directory name, or glob, or an array of them - * @param {Object} [providedOptions] A CLIEngine options object. If not provided, the default cli options will be used. - * @param {progressCallback} [providedCallback] Callback for reporting execution status - * @returns {Object} The SourceCode of all processed files. - */ -function getSourceCodeOfFiles(patterns, providedOptions, providedCallback) { - const sourceCodes = {}; - const globPatternsList = typeof patterns === "string" ? [patterns] : patterns; - let options, callback; - - const defaultOptions = Object.assign({}, baseDefaultOptions, { cwd: process.cwd() }); - - if (typeof providedOptions === "undefined") { - options = defaultOptions; - callback = null; - } else if (typeof providedOptions === "function") { - callback = providedOptions; - options = defaultOptions; - } else if (typeof providedOptions === "object") { - options = Object.assign({}, defaultOptions, providedOptions); - callback = providedCallback; - } - debug("constructed options:", options); - - const filenames = globUtils.listFilesToProcess(globPatternsList, options) - .filter(fileInfo => !fileInfo.ignored) - .reduce((files, fileInfo) => files.concat(fileInfo.filename), []); - - if (filenames.length === 0) { - debug(`Did not find any files matching pattern(s): ${globPatternsList}`); - } - filenames.forEach(filename => { - const sourceCode = getSourceCodeOfFile(filename, options); - - if (sourceCode) { - debug("got sourceCode of", filename); - sourceCodes[filename] = sourceCode; - } - if (callback) { - callback(filenames.length); // eslint-disable-line callback-return - } - }); - return sourceCodes; -} - -module.exports = { - getSourceCodeOfFiles -}; diff --git a/tools/node_modules/eslint/lib/util/source-code.js b/tools/node_modules/eslint/lib/util/source-code.js deleted file mode 100644 index 4e90ac1aa92721..00000000000000 --- a/tools/node_modules/eslint/lib/util/source-code.js +++ /dev/null @@ -1,507 +0,0 @@ -/** - * @fileoverview Abstraction of JavaScript source code. - * @author Nicholas C. Zakas - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const TokenStore = require("../token-store"), - Traverser = require("./traverser"), - astUtils = require("../util/ast-utils"), - lodash = require("lodash"); - -//------------------------------------------------------------------------------ -// Private -//------------------------------------------------------------------------------ - -/** - * Validates that the given AST has the required information. - * @param {ASTNode} ast The Program node of the AST to check. - * @throws {Error} If the AST doesn't contain the correct information. - * @returns {void} - * @private - */ -function validate(ast) { - if (!ast.tokens) { - throw new Error("AST is missing the tokens array."); - } - - if (!ast.comments) { - throw new Error("AST is missing the comments array."); - } - - if (!ast.loc) { - throw new Error("AST is missing location information."); - } - - if (!ast.range) { - throw new Error("AST is missing range information"); - } -} - -/** - * Check to see if its a ES6 export declaration. - * @param {ASTNode} astNode An AST node. - * @returns {boolean} whether the given node represents an export declaration. - * @private - */ -function looksLikeExport(astNode) { - return astNode.type === "ExportDefaultDeclaration" || astNode.type === "ExportNamedDeclaration" || - astNode.type === "ExportAllDeclaration" || astNode.type === "ExportSpecifier"; -} - -/** - * Merges two sorted lists into a larger sorted list in O(n) time. - * @param {Token[]} tokens The list of tokens. - * @param {Token[]} comments The list of comments. - * @returns {Token[]} A sorted list of tokens and comments. - * @private - */ -function sortedMerge(tokens, comments) { - const result = []; - let tokenIndex = 0; - let commentIndex = 0; - - while (tokenIndex < tokens.length || commentIndex < comments.length) { - if (commentIndex >= comments.length || tokenIndex < tokens.length && tokens[tokenIndex].range[0] < comments[commentIndex].range[0]) { - result.push(tokens[tokenIndex++]); - } else { - result.push(comments[commentIndex++]); - } - } - - return result; -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -class SourceCode extends TokenStore { - - /** - * Represents parsed source code. - * @param {string|Object} textOrConfig - The source code text or config object. - * @param {string} textOrConfig.text - The source code text. - * @param {ASTNode} textOrConfig.ast - The Program node of the AST representing the code. This AST should be created from the text that BOM was stripped. - * @param {Object|null} textOrConfig.parserServices - The parser services. - * @param {ScopeManager|null} textOrConfig.scopeManager - The scope of this source code. - * @param {Object|null} textOrConfig.visitorKeys - The visitor keys to traverse AST. - * @param {ASTNode} [astIfNoConfig] - The Program node of the AST representing the code. This AST should be created from the text that BOM was stripped. - * @constructor - */ - constructor(textOrConfig, astIfNoConfig) { - let text, ast, parserServices, scopeManager, visitorKeys; - - // Process overloading. - if (typeof textOrConfig === "string") { - text = textOrConfig; - ast = astIfNoConfig; - } else if (typeof textOrConfig === "object" && textOrConfig !== null) { - text = textOrConfig.text; - ast = textOrConfig.ast; - parserServices = textOrConfig.parserServices; - scopeManager = textOrConfig.scopeManager; - visitorKeys = textOrConfig.visitorKeys; - } - - validate(ast); - super(ast.tokens, ast.comments); - - /** - * The flag to indicate that the source code has Unicode BOM. - * @type boolean - */ - this.hasBOM = (text.charCodeAt(0) === 0xFEFF); - - /** - * The original text source code. - * BOM was stripped from this text. - * @type string - */ - this.text = (this.hasBOM ? text.slice(1) : text); - - /** - * The parsed AST for the source code. - * @type ASTNode - */ - this.ast = ast; - - /** - * The parser services of this source code. - * @type {Object} - */ - this.parserServices = parserServices || {}; - - /** - * The scope of this source code. - * @type {ScopeManager|null} - */ - this.scopeManager = scopeManager || null; - - /** - * The visitor keys to traverse AST. - * @type {Object} - */ - this.visitorKeys = visitorKeys || Traverser.DEFAULT_VISITOR_KEYS; - - // Check the source text for the presence of a shebang since it is parsed as a standard line comment. - const shebangMatched = this.text.match(astUtils.SHEBANG_MATCHER); - const hasShebang = shebangMatched && ast.comments.length && ast.comments[0].value === shebangMatched[1]; - - if (hasShebang) { - ast.comments[0].type = "Shebang"; - } - - this.tokensAndComments = sortedMerge(ast.tokens, ast.comments); - - /** - * The source code split into lines according to ECMA-262 specification. - * This is done to avoid each rule needing to do so separately. - * @type string[] - */ - this.lines = []; - this.lineStartIndices = [0]; - - const lineEndingPattern = astUtils.createGlobalLinebreakMatcher(); - let match; - - /* - * Previously, this was implemented using a regex that - * matched a sequence of non-linebreak characters followed by a - * linebreak, then adding the lengths of the matches. However, - * this caused a catastrophic backtracking issue when the end - * of a file contained a large number of non-newline characters. - * To avoid this, the current implementation just matches newlines - * and uses match.index to get the correct line start indices. - */ - while ((match = lineEndingPattern.exec(this.text))) { - this.lines.push(this.text.slice(this.lineStartIndices[this.lineStartIndices.length - 1], match.index)); - this.lineStartIndices.push(match.index + match[0].length); - } - this.lines.push(this.text.slice(this.lineStartIndices[this.lineStartIndices.length - 1])); - - // Cache for comments found using getComments(). - this._commentCache = new WeakMap(); - - // don't allow modification of this object - Object.freeze(this); - Object.freeze(this.lines); - } - - /** - * Split the source code into multiple lines based on the line delimiters. - * @param {string} text Source code as a string. - * @returns {string[]} Array of source code lines. - * @public - */ - static splitLines(text) { - return text.split(astUtils.createGlobalLinebreakMatcher()); - } - - /** - * Gets the source code for the given node. - * @param {ASTNode=} node The AST node to get the text for. - * @param {int=} beforeCount The number of characters before the node to retrieve. - * @param {int=} afterCount The number of characters after the node to retrieve. - * @returns {string} The text representing the AST node. - * @public - */ - getText(node, beforeCount, afterCount) { - if (node) { - return this.text.slice(Math.max(node.range[0] - (beforeCount || 0), 0), - node.range[1] + (afterCount || 0)); - } - return this.text; - } - - /** - * Gets the entire source text split into an array of lines. - * @returns {Array} The source text as an array of lines. - * @public - */ - getLines() { - return this.lines; - } - - /** - * Retrieves an array containing all comments in the source code. - * @returns {ASTNode[]} An array of comment nodes. - * @public - */ - getAllComments() { - return this.ast.comments; - } - - /** - * Gets all comments for the given node. - * @param {ASTNode} node The AST node to get the comments for. - * @returns {Object} An object containing a leading and trailing array - * of comments indexed by their position. - * @public - */ - getComments(node) { - if (this._commentCache.has(node)) { - return this._commentCache.get(node); - } - - const comments = { - leading: [], - trailing: [] - }; - - /* - * Return all comments as leading comments of the Program node when - * there is no executable code. - */ - if (node.type === "Program") { - if (node.body.length === 0) { - comments.leading = node.comments; - } - } else { - - /* - * Return comments as trailing comments of nodes that only contain - * comments (to mimic the comment attachment behavior present in Espree). - */ - if ((node.type === "BlockStatement" || node.type === "ClassBody") && node.body.length === 0 || - node.type === "ObjectExpression" && node.properties.length === 0 || - node.type === "ArrayExpression" && node.elements.length === 0 || - node.type === "SwitchStatement" && node.cases.length === 0 - ) { - comments.trailing = this.getTokens(node, { - includeComments: true, - filter: astUtils.isCommentToken - }); - } - - /* - * Iterate over tokens before and after node and collect comment tokens. - * Do not include comments that exist outside of the parent node - * to avoid duplication. - */ - let currentToken = this.getTokenBefore(node, { includeComments: true }); - - while (currentToken && astUtils.isCommentToken(currentToken)) { - if (node.parent && (currentToken.start < node.parent.start)) { - break; - } - comments.leading.push(currentToken); - currentToken = this.getTokenBefore(currentToken, { includeComments: true }); - } - - comments.leading.reverse(); - - currentToken = this.getTokenAfter(node, { includeComments: true }); - - while (currentToken && astUtils.isCommentToken(currentToken)) { - if (node.parent && (currentToken.end > node.parent.end)) { - break; - } - comments.trailing.push(currentToken); - currentToken = this.getTokenAfter(currentToken, { includeComments: true }); - } - } - - this._commentCache.set(node, comments); - return comments; - } - - /** - * Retrieves the JSDoc comment for a given node. - * @param {ASTNode} node The AST node to get the comment for. - * @returns {Token|null} The Block comment token containing the JSDoc comment - * for the given node or null if not found. - * @public - * @deprecated - */ - getJSDocComment(node) { - - /** - * Checks for the presence of a JSDoc comment for the given node and returns it. - * @param {ASTNode} astNode The AST node to get the comment for. - * @returns {Token|null} The Block comment token containing the JSDoc comment - * for the given node or null if not found. - * @private - */ - const findJSDocComment = astNode => { - const tokenBefore = this.getTokenBefore(astNode, { includeComments: true }); - - if ( - tokenBefore && - astUtils.isCommentToken(tokenBefore) && - tokenBefore.type === "Block" && - tokenBefore.value.charAt(0) === "*" && - astNode.loc.start.line - tokenBefore.loc.end.line <= 1 - ) { - return tokenBefore; - } - - return null; - }; - let parent = node.parent; - - switch (node.type) { - case "ClassDeclaration": - case "FunctionDeclaration": - return findJSDocComment(looksLikeExport(parent) ? parent : node); - - case "ClassExpression": - return findJSDocComment(parent.parent); - - case "ArrowFunctionExpression": - case "FunctionExpression": - if (parent.type !== "CallExpression" && parent.type !== "NewExpression") { - while ( - !this.getCommentsBefore(parent).length && - !/Function/.test(parent.type) && - parent.type !== "MethodDefinition" && - parent.type !== "Property" - ) { - parent = parent.parent; - - if (!parent) { - break; - } - } - - if (parent && parent.type !== "FunctionDeclaration" && parent.type !== "Program") { - return findJSDocComment(parent); - } - } - - return findJSDocComment(node); - - // falls through - default: - return null; - } - } - - /** - * Gets the deepest node containing a range index. - * @param {int} index Range index of the desired node. - * @returns {ASTNode} The node if found or null if not found. - * @public - */ - getNodeByRangeIndex(index) { - let result = null; - - Traverser.traverse(this.ast, { - visitorKeys: this.visitorKeys, - enter(node) { - if (node.range[0] <= index && index < node.range[1]) { - result = node; - } else { - this.skip(); - } - }, - leave(node) { - if (node === result) { - this.break(); - } - } - }); - - return result; - } - - /** - * Determines if two tokens have at least one whitespace character - * between them. This completely disregards comments in making the - * determination, so comments count as zero-length substrings. - * @param {Token} first The token to check after. - * @param {Token} second The token to check before. - * @returns {boolean} True if there is only space between tokens, false - * if there is anything other than whitespace between tokens. - * @public - */ - isSpaceBetweenTokens(first, second) { - const text = this.text.slice(first.range[1], second.range[0]); - - return /\s/.test(text.replace(/\/\*.*?\*\//g, "")); - } - - /** - * Converts a source text index into a (line, column) pair. - * @param {number} index The index of a character in a file - * @returns {Object} A {line, column} location object with a 0-indexed column - * @public - */ - getLocFromIndex(index) { - if (typeof index !== "number") { - throw new TypeError("Expected `index` to be a number."); - } - - if (index < 0 || index > this.text.length) { - throw new RangeError(`Index out of range (requested index ${index}, but source text has length ${this.text.length}).`); - } - - /* - * For an argument of this.text.length, return the location one "spot" past the last character - * of the file. If the last character is a linebreak, the location will be column 0 of the next - * line; otherwise, the location will be in the next column on the same line. - * - * See getIndexFromLoc for the motivation for this special case. - */ - if (index === this.text.length) { - return { line: this.lines.length, column: this.lines[this.lines.length - 1].length }; - } - - /* - * 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(this.lineStartIndices, index); - - return { line: lineNumber, column: index - this.lineStartIndices[lineNumber - 1] }; - } - - /** - * Converts a (line, column) pair into a range index. - * @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. - * @public - */ - getIndexFromLoc(loc) { - if (typeof loc !== "object" || typeof loc.line !== "number" || typeof loc.column !== "number") { - throw new TypeError("Expected `loc` to be an object with numeric `line` and `column` properties."); - } - - if (loc.line <= 0) { - throw new RangeError(`Line number out of range (line ${loc.line} requested). Line numbers should be 1-based.`); - } - - if (loc.line > this.lineStartIndices.length) { - throw new RangeError(`Line number out of range (line ${loc.line} requested, but only ${this.lineStartIndices.length} lines present).`); - } - - const lineStartIndex = this.lineStartIndices[loc.line - 1]; - const lineEndIndex = loc.line === this.lineStartIndices.length ? this.text.length : this.lineStartIndices[loc.line]; - const positionIndex = lineStartIndex + loc.column; - - /* - * By design, getIndexFromLoc({ line: lineNum, column: 0 }) should return the start index of - * the given line, provided that the line number is valid element of this.lines. Since the - * last element of this.lines is an empty string for files with trailing newlines, add a - * special case where getting the index for the first location after the end of the file - * will return the length of the file, rather than throwing an error. This allows rules to - * use getIndexFromLoc consistently without worrying about edge cases at the end of a file. - */ - if ( - loc.line === this.lineStartIndices.length && positionIndex > lineEndIndex || - loc.line < this.lineStartIndices.length && positionIndex >= lineEndIndex - ) { - throw new RangeError(`Column number out of range (column ${loc.column} requested, but the length of line ${loc.line} is ${lineEndIndex - lineStartIndex}).`); - } - - return positionIndex; - } -} - -module.exports = SourceCode; diff --git a/tools/node_modules/eslint/lib/util/timing.js b/tools/node_modules/eslint/lib/util/timing.js deleted file mode 100644 index 102a5233dc2ec1..00000000000000 --- a/tools/node_modules/eslint/lib/util/timing.js +++ /dev/null @@ -1,139 +0,0 @@ -/** - * @fileoverview Tracks performance of individual rules. - * @author Brandon Mills - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/* istanbul ignore next */ -/** - * Align the string to left - * @param {string} str string to evaluate - * @param {int} len length of the string - * @param {string} ch delimiter character - * @returns {string} modified string - * @private - */ -function alignLeft(str, len, ch) { - return str + new Array(len - str.length + 1).join(ch || " "); -} - -/* istanbul ignore next */ -/** - * Align the string to right - * @param {string} str string to evaluate - * @param {int} len length of the string - * @param {string} ch delimiter character - * @returns {string} modified string - * @private - */ -function alignRight(str, len, ch) { - return new Array(len - str.length + 1).join(ch || " ") + str; -} - -//------------------------------------------------------------------------------ -// Module definition -//------------------------------------------------------------------------------ - -const enabled = !!process.env.TIMING; - -const HEADERS = ["Rule", "Time (ms)", "Relative"]; -const ALIGN = [alignLeft, alignRight, alignRight]; - -/* istanbul ignore next */ -/** - * display the data - * @param {Object} data Data object to be displayed - * @returns {string} modified string - * @private - */ -function display(data) { - let total = 0; - const rows = Object.keys(data) - .map(key => { - const time = data[key]; - - total += time; - return [key, time]; - }) - .sort((a, b) => b[1] - a[1]) - .slice(0, 10); - - rows.forEach(row => { - row.push(`${(row[1] * 100 / total).toFixed(1)}%`); - row[1] = row[1].toFixed(3); - }); - - rows.unshift(HEADERS); - - const widths = []; - - rows.forEach(row => { - const len = row.length; - - for (let i = 0; i < len; i++) { - const n = row[i].length; - - if (!widths[i] || n > widths[i]) { - widths[i] = n; - } - } - }); - - const table = rows.map(row => ( - row - .map((cell, index) => ALIGN[index](cell, widths[index])) - .join(" | ") - )); - - table.splice(1, 0, widths.map((width, index) => { - const extraAlignment = index !== 0 && index !== widths.length - 1 ? 2 : 1; - - return ALIGN[index](":", width + extraAlignment, "-"); - }).join("|")); - - console.log(table.join("\n")); // eslint-disable-line no-console -} - -/* istanbul ignore next */ -module.exports = (function() { - - const data = Object.create(null); - - /** - * Time the run - * @param {*} key key from the data object - * @param {Function} fn function to be called - * @returns {Function} function to be executed - * @private - */ - function time(key, fn) { - if (typeof data[key] === "undefined") { - data[key] = 0; - } - - return function(...args) { - let t = process.hrtime(); - - fn(...args); - t = process.hrtime(t); - data[key] += t[0] * 1e3 + t[1] / 1e6; - }; - } - - if (enabled) { - process.on("exit", () => { - display(data); - }); - } - - return { - time, - enabled - }; - -}()); diff --git a/tools/node_modules/eslint/lib/util/traverser.js b/tools/node_modules/eslint/lib/util/traverser.js deleted file mode 100644 index 79fb32faf95cff..00000000000000 --- a/tools/node_modules/eslint/lib/util/traverser.js +++ /dev/null @@ -1,193 +0,0 @@ -/** - * @fileoverview Traverser to traverse AST trees. - * @author Nicholas C. Zakas - * @author Toru Nagashima - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const vk = require("eslint-visitor-keys"); -const debug = require("debug")("eslint:traverser"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Do nothing. - * @returns {void} - */ -function noop() { - - // do nothing. -} - -/** - * Check whether the given value is an ASTNode or not. - * @param {any} x The value to check. - * @returns {boolean} `true` if the value is an ASTNode. - */ -function isNode(x) { - return x !== null && typeof x === "object" && typeof x.type === "string"; -} - -/** - * Get the visitor keys of a given node. - * @param {Object} visitorKeys The map of visitor keys. - * @param {ASTNode} node The node to get their visitor keys. - * @returns {string[]} The visitor keys of the node. - */ -function getVisitorKeys(visitorKeys, node) { - let keys = visitorKeys[node.type]; - - if (!keys) { - keys = vk.getKeys(node); - debug("Unknown node type \"%s\": Estimated visitor keys %j", node.type, keys); - } - - return keys; -} - -/** - * The traverser class to traverse AST trees. - */ -class Traverser { - constructor() { - this._current = null; - this._parents = []; - this._skipped = false; - this._broken = false; - this._visitorKeys = null; - this._enter = null; - this._leave = null; - } - - /** - * @returns {ASTNode} The current node. - */ - current() { - return this._current; - } - - /** - * @returns {ASTNode[]} The ancestor nodes. - */ - parents() { - return this._parents.slice(0); - } - - /** - * Break the current traversal. - * @returns {void} - */ - break() { - this._broken = true; - } - - /** - * Skip child nodes for the current traversal. - * @returns {void} - */ - skip() { - this._skipped = true; - } - - /** - * Traverse the given AST tree. - * @param {ASTNode} node The root node to traverse. - * @param {Object} options The option object. - * @param {Object} [options.visitorKeys=DEFAULT_VISITOR_KEYS] The keys of each node types to traverse child nodes. Default is `./default-visitor-keys.json`. - * @param {Function} [options.enter=noop] The callback function which is called on entering each node. - * @param {Function} [options.leave=noop] The callback function which is called on leaving each node. - * @returns {void} - */ - traverse(node, options) { - this._current = null; - this._parents = []; - this._skipped = false; - this._broken = false; - this._visitorKeys = options.visitorKeys || vk.KEYS; - this._enter = options.enter || noop; - this._leave = options.leave || noop; - this._traverse(node, null); - } - - /** - * Traverse the given AST tree recursively. - * @param {ASTNode} node The current node. - * @param {ASTNode|null} parent The parent node. - * @returns {void} - * @private - */ - _traverse(node, parent) { - if (!isNode(node)) { - return; - } - - this._current = node; - this._skipped = false; - this._enter(node, parent); - - if (!this._skipped && !this._broken) { - const keys = getVisitorKeys(this._visitorKeys, node); - - if (keys.length >= 1) { - this._parents.push(node); - for (let i = 0; i < keys.length && !this._broken; ++i) { - const child = node[keys[i]]; - - if (Array.isArray(child)) { - for (let j = 0; j < child.length && !this._broken; ++j) { - this._traverse(child[j], node); - } - } else { - this._traverse(child, node); - } - } - this._parents.pop(); - } - } - - if (!this._broken) { - this._leave(node, parent); - } - - this._current = parent; - } - - /** - * Calculates the keys to use for traversal. - * @param {ASTNode} node The node to read keys from. - * @returns {string[]} An array of keys to visit on the node. - * @private - */ - static getKeys(node) { - return vk.getKeys(node); - } - - /** - * Traverse the given AST tree. - * @param {ASTNode} node The root node to traverse. - * @param {Object} options The option object. - * @param {Object} [options.visitorKeys=DEFAULT_VISITOR_KEYS] The keys of each node types to traverse child nodes. Default is `./default-visitor-keys.json`. - * @param {Function} [options.enter=noop] The callback function which is called on entering each node. - * @param {Function} [options.leave=noop] The callback function which is called on leaving each node. - * @returns {void} - */ - static traverse(node, options) { - new Traverser().traverse(node, options); - } - - /** - * The default visitor keys. - * @type {Object} - */ - static get DEFAULT_VISITOR_KEYS() { - return vk.KEYS; - } -} - -module.exports = Traverser; diff --git a/tools/node_modules/eslint/lib/util/unicode/index.js b/tools/node_modules/eslint/lib/util/unicode/index.js deleted file mode 100644 index 02eea502dfe669..00000000000000 --- a/tools/node_modules/eslint/lib/util/unicode/index.js +++ /dev/null @@ -1,11 +0,0 @@ -/** - * @author Toru Nagashima - */ -"use strict"; - -module.exports = { - isCombiningCharacter: require("./is-combining-character"), - isEmojiModifier: require("./is-emoji-modifier"), - isRegionalIndicatorSymbol: require("./is-regional-indicator-symbol"), - isSurrogatePair: require("./is-surrogate-pair") -}; diff --git a/tools/node_modules/eslint/lib/util/unicode/is-combining-character.js b/tools/node_modules/eslint/lib/util/unicode/is-combining-character.js deleted file mode 100644 index 0fa40ee4ae8630..00000000000000 --- a/tools/node_modules/eslint/lib/util/unicode/is-combining-character.js +++ /dev/null @@ -1,13 +0,0 @@ -// THIS FILE WAS GENERATED BY 'tools/update-unicode-utils.js' -"use strict"; - -const combiningChars = new Set([768,769,770,771,772,773,774,775,776,777,778,779,780,781,782,783,784,785,786,787,788,789,790,791,792,793,794,795,796,797,798,799,800,801,802,803,804,805,806,807,808,809,810,811,812,813,814,815,816,817,818,819,820,821,822,823,824,825,826,827,828,829,830,831,832,833,834,835,836,837,838,839,840,841,842,843,844,845,846,847,848,849,850,851,852,853,854,855,856,857,858,859,860,861,862,863,864,865,866,867,868,869,870,871,872,873,874,875,876,877,878,879,1155,1156,1157,1158,1159,1160,1161,1425,1426,1427,1428,1429,1430,1431,1432,1433,1434,1435,1436,1437,1438,1439,1440,1441,1442,1443,1444,1445,1446,1447,1448,1449,1450,1451,1452,1453,1454,1455,1456,1457,1458,1459,1460,1461,1462,1463,1464,1465,1466,1467,1468,1469,1471,1473,1474,1476,1477,1479,1552,1553,1554,1555,1556,1557,1558,1559,1560,1561,1562,1611,1612,1613,1614,1615,1616,1617,1618,1619,1620,1621,1622,1623,1624,1625,1626,1627,1628,1629,1630,1631,1648,1750,1751,1752,1753,1754,1755,1756,1759,1760,1761,1762,1763,1764,1767,1768,1770,1771,1772,1773,1809,1840,1841,1842,1843,1844,1845,1846,1847,1848,1849,1850,1851,1852,1853,1854,1855,1856,1857,1858,1859,1860,1861,1862,1863,1864,1865,1866,1958,1959,1960,1961,1962,1963,1964,1965,1966,1967,1968,2027,2028,2029,2030,2031,2032,2033,2034,2035,2070,2071,2072,2073,2075,2076,2077,2078,2079,2080,2081,2082,2083,2085,2086,2087,2089,2090,2091,2092,2093,2137,2138,2139,2260,2261,2262,2263,2264,2265,2266,2267,2268,2269,2270,2271,2272,2273,2275,2276,2277,2278,2279,2280,2281,2282,2283,2284,2285,2286,2287,2288,2289,2290,2291,2292,2293,2294,2295,2296,2297,2298,2299,2300,2301,2302,2303,2304,2305,2306,2307,2362,2363,2364,2366,2367,2368,2369,2370,2371,2372,2373,2374,2375,2376,2377,2378,2379,2380,2381,2382,2383,2385,2386,2387,2388,2389,2390,2391,2402,2403,2433,2434,2435,2492,2494,2495,2496,2497,2498,2499,2500,2503,2504,2507,2508,2509,2519,2530,2531,2561,2562,2563,2620,2622,2623,2624,2625,2626,2631,2632,2635,2636,2637,2641,2672,2673,2677,2689,2690,2691,2748,2750,2751,2752,2753,2754,2755,2756,2757,2759,2760,2761,2763,2764,2765,2786,2787,2810,2811,2812,2813,2814,2815,2817,2818,2819,2876,2878,2879,2880,2881,2882,2883,2884,2887,2888,2891,2892,2893,2902,2903,2914,2915,2946,3006,3007,3008,3009,3010,3014,3015,3016,3018,3019,3020,3021,3031,3072,3073,3074,3075,3134,3135,3136,3137,3138,3139,3140,3142,3143,3144,3146,3147,3148,3149,3157,3158,3170,3171,3201,3202,3203,3260,3262,3263,3264,3265,3266,3267,3268,3270,3271,3272,3274,3275,3276,3277,3285,3286,3298,3299,3328,3329,3330,3331,3387,3388,3390,3391,3392,3393,3394,3395,3396,3398,3399,3400,3402,3403,3404,3405,3415,3426,3427,3458,3459,3530,3535,3536,3537,3538,3539,3540,3542,3544,3545,3546,3547,3548,3549,3550,3551,3570,3571,3633,3636,3637,3638,3639,3640,3641,3642,3655,3656,3657,3658,3659,3660,3661,3662,3761,3764,3765,3766,3767,3768,3769,3771,3772,3784,3785,3786,3787,3788,3789,3864,3865,3893,3895,3897,3902,3903,3953,3954,3955,3956,3957,3958,3959,3960,3961,3962,3963,3964,3965,3966,3967,3968,3969,3970,3971,3972,3974,3975,3981,3982,3983,3984,3985,3986,3987,3988,3989,3990,3991,3993,3994,3995,3996,3997,3998,3999,4000,4001,4002,4003,4004,4005,4006,4007,4008,4009,4010,4011,4012,4013,4014,4015,4016,4017,4018,4019,4020,4021,4022,4023,4024,4025,4026,4027,4028,4038,4139,4140,4141,4142,4143,4144,4145,4146,4147,4148,4149,4150,4151,4152,4153,4154,4155,4156,4157,4158,4182,4183,4184,4185,4190,4191,4192,4194,4195,4196,4199,4200,4201,4202,4203,4204,4205,4209,4210,4211,4212,4226,4227,4228,4229,4230,4231,4232,4233,4234,4235,4236,4237,4239,4250,4251,4252,4253,4957,4958,4959,5906,5907,5908,5938,5939,5940,5970,5971,6002,6003,6068,6069,6070,6071,6072,6073,6074,6075,6076,6077,6078,6079,6080,6081,6082,6083,6084,6085,6086,6087,6088,6089,6090,6091,6092,6093,6094,6095,6096,6097,6098,6099,6109,6155,6156,6157,6277,6278,6313,6432,6433,6434,6435,6436,6437,6438,6439,6440,6441,6442,6443,6448,6449,6450,6451,6452,6453,6454,6455,6456,6457,6458,6459,6679,6680,6681,6682,6683,6741,6742,6743,6744,6745,6746,6747,6748,6749,6750,6752,6753,6754,6755,6756,6757,6758,6759,6760,6761,6762,6763,6764,6765,6766,6767,6768,6769,6770,6771,6772,6773,6774,6775,6776,6777,6778,6779,6780,6783,6832,6833,6834,6835,6836,6837,6838,6839,6840,6841,6842,6843,6844,6845,6846,6912,6913,6914,6915,6916,6964,6965,6966,6967,6968,6969,6970,6971,6972,6973,6974,6975,6976,6977,6978,6979,6980,7019,7020,7021,7022,7023,7024,7025,7026,7027,7040,7041,7042,7073,7074,7075,7076,7077,7078,7079,7080,7081,7082,7083,7084,7085,7142,7143,7144,7145,7146,7147,7148,7149,7150,7151,7152,7153,7154,7155,7204,7205,7206,7207,7208,7209,7210,7211,7212,7213,7214,7215,7216,7217,7218,7219,7220,7221,7222,7223,7376,7377,7378,7380,7381,7382,7383,7384,7385,7386,7387,7388,7389,7390,7391,7392,7393,7394,7395,7396,7397,7398,7399,7400,7405,7410,7411,7412,7415,7416,7417,7616,7617,7618,7619,7620,7621,7622,7623,7624,7625,7626,7627,7628,7629,7630,7631,7632,7633,7634,7635,7636,7637,7638,7639,7640,7641,7642,7643,7644,7645,7646,7647,7648,7649,7650,7651,7652,7653,7654,7655,7656,7657,7658,7659,7660,7661,7662,7663,7664,7665,7666,7667,7668,7669,7670,7671,7672,7673,7675,7676,7677,7678,7679,8400,8401,8402,8403,8404,8405,8406,8407,8408,8409,8410,8411,8412,8413,8414,8415,8416,8417,8418,8419,8420,8421,8422,8423,8424,8425,8426,8427,8428,8429,8430,8431,8432,11503,11504,11505,11647,11744,11745,11746,11747,11748,11749,11750,11751,11752,11753,11754,11755,11756,11757,11758,11759,11760,11761,11762,11763,11764,11765,11766,11767,11768,11769,11770,11771,11772,11773,11774,11775,12330,12331,12332,12333,12334,12335,12441,12442,42607,42608,42609,42610,42612,42613,42614,42615,42616,42617,42618,42619,42620,42621,42654,42655,42736,42737,43010,43014,43019,43043,43044,43045,43046,43047,43136,43137,43188,43189,43190,43191,43192,43193,43194,43195,43196,43197,43198,43199,43200,43201,43202,43203,43204,43205,43232,43233,43234,43235,43236,43237,43238,43239,43240,43241,43242,43243,43244,43245,43246,43247,43248,43249,43302,43303,43304,43305,43306,43307,43308,43309,43335,43336,43337,43338,43339,43340,43341,43342,43343,43344,43345,43346,43347,43392,43393,43394,43395,43443,43444,43445,43446,43447,43448,43449,43450,43451,43452,43453,43454,43455,43456,43493,43561,43562,43563,43564,43565,43566,43567,43568,43569,43570,43571,43572,43573,43574,43587,43596,43597,43643,43644,43645,43696,43698,43699,43700,43703,43704,43710,43711,43713,43755,43756,43757,43758,43759,43765,43766,44003,44004,44005,44006,44007,44008,44009,44010,44012,44013,64286,65024,65025,65026,65027,65028,65029,65030,65031,65032,65033,65034,65035,65036,65037,65038,65039,65056,65057,65058,65059,65060,65061,65062,65063,65064,65065,65066,65067,65068,65069,65070,65071,66045,66272,66422,66423,66424,66425,66426,68097,68098,68099,68101,68102,68108,68109,68110,68111,68152,68153,68154,68159,68325,68326,69632,69633,69634,69688,69689,69690,69691,69692,69693,69694,69695,69696,69697,69698,69699,69700,69701,69702,69759,69760,69761,69762,69808,69809,69810,69811,69812,69813,69814,69815,69816,69817,69818,69888,69889,69890,69927,69928,69929,69930,69931,69932,69933,69934,69935,69936,69937,69938,69939,69940,70003,70016,70017,70018,70067,70068,70069,70070,70071,70072,70073,70074,70075,70076,70077,70078,70079,70080,70090,70091,70092,70188,70189,70190,70191,70192,70193,70194,70195,70196,70197,70198,70199,70206,70367,70368,70369,70370,70371,70372,70373,70374,70375,70376,70377,70378,70400,70401,70402,70403,70460,70462,70463,70464,70465,70466,70467,70468,70471,70472,70475,70476,70477,70487,70498,70499,70502,70503,70504,70505,70506,70507,70508,70512,70513,70514,70515,70516,70709,70710,70711,70712,70713,70714,70715,70716,70717,70718,70719,70720,70721,70722,70723,70724,70725,70726,70832,70833,70834,70835,70836,70837,70838,70839,70840,70841,70842,70843,70844,70845,70846,70847,70848,70849,70850,70851,71087,71088,71089,71090,71091,71092,71093,71096,71097,71098,71099,71100,71101,71102,71103,71104,71132,71133,71216,71217,71218,71219,71220,71221,71222,71223,71224,71225,71226,71227,71228,71229,71230,71231,71232,71339,71340,71341,71342,71343,71344,71345,71346,71347,71348,71349,71350,71351,71453,71454,71455,71456,71457,71458,71459,71460,71461,71462,71463,71464,71465,71466,71467,72193,72194,72195,72196,72197,72198,72199,72200,72201,72202,72243,72244,72245,72246,72247,72248,72249,72251,72252,72253,72254,72263,72273,72274,72275,72276,72277,72278,72279,72280,72281,72282,72283,72330,72331,72332,72333,72334,72335,72336,72337,72338,72339,72340,72341,72342,72343,72344,72345,72751,72752,72753,72754,72755,72756,72757,72758,72760,72761,72762,72763,72764,72765,72766,72767,72850,72851,72852,72853,72854,72855,72856,72857,72858,72859,72860,72861,72862,72863,72864,72865,72866,72867,72868,72869,72870,72871,72873,72874,72875,72876,72877,72878,72879,72880,72881,72882,72883,72884,72885,72886,73009,73010,73011,73012,73013,73014,73018,73020,73021,73023,73024,73025,73026,73027,73028,73029,73031,92912,92913,92914,92915,92916,92976,92977,92978,92979,92980,92981,92982,94033,94034,94035,94036,94037,94038,94039,94040,94041,94042,94043,94044,94045,94046,94047,94048,94049,94050,94051,94052,94053,94054,94055,94056,94057,94058,94059,94060,94061,94062,94063,94064,94065,94066,94067,94068,94069,94070,94071,94072,94073,94074,94075,94076,94077,94078,94095,94096,94097,94098,113821,113822,119141,119142,119143,119144,119145,119149,119150,119151,119152,119153,119154,119163,119164,119165,119166,119167,119168,119169,119170,119173,119174,119175,119176,119177,119178,119179,119210,119211,119212,119213,119362,119363,119364,121344,121345,121346,121347,121348,121349,121350,121351,121352,121353,121354,121355,121356,121357,121358,121359,121360,121361,121362,121363,121364,121365,121366,121367,121368,121369,121370,121371,121372,121373,121374,121375,121376,121377,121378,121379,121380,121381,121382,121383,121384,121385,121386,121387,121388,121389,121390,121391,121392,121393,121394,121395,121396,121397,121398,121403,121404,121405,121406,121407,121408,121409,121410,121411,121412,121413,121414,121415,121416,121417,121418,121419,121420,121421,121422,121423,121424,121425,121426,121427,121428,121429,121430,121431,121432,121433,121434,121435,121436,121437,121438,121439,121440,121441,121442,121443,121444,121445,121446,121447,121448,121449,121450,121451,121452,121461,121476,121499,121500,121501,121502,121503,121505,121506,121507,121508,121509,121510,121511,121512,121513,121514,121515,121516,121517,121518,121519,122880,122881,122882,122883,122884,122885,122886,122888,122889,122890,122891,122892,122893,122894,122895,122896,122897,122898,122899,122900,122901,122902,122903,122904,122907,122908,122909,122910,122911,122912,122913,122915,122916,122918,122919,122920,122921,122922,125136,125137,125138,125139,125140,125141,125142,125252,125253,125254,125255,125256,125257,125258,917760,917761,917762,917763,917764,917765,917766,917767,917768,917769,917770,917771,917772,917773,917774,917775,917776,917777,917778,917779,917780,917781,917782,917783,917784,917785,917786,917787,917788,917789,917790,917791,917792,917793,917794,917795,917796,917797,917798,917799,917800,917801,917802,917803,917804,917805,917806,917807,917808,917809,917810,917811,917812,917813,917814,917815,917816,917817,917818,917819,917820,917821,917822,917823,917824,917825,917826,917827,917828,917829,917830,917831,917832,917833,917834,917835,917836,917837,917838,917839,917840,917841,917842,917843,917844,917845,917846,917847,917848,917849,917850,917851,917852,917853,917854,917855,917856,917857,917858,917859,917860,917861,917862,917863,917864,917865,917866,917867,917868,917869,917870,917871,917872,917873,917874,917875,917876,917877,917878,917879,917880,917881,917882,917883,917884,917885,917886,917887,917888,917889,917890,917891,917892,917893,917894,917895,917896,917897,917898,917899,917900,917901,917902,917903,917904,917905,917906,917907,917908,917909,917910,917911,917912,917913,917914,917915,917916,917917,917918,917919,917920,917921,917922,917923,917924,917925,917926,917927,917928,917929,917930,917931,917932,917933,917934,917935,917936,917937,917938,917939,917940,917941,917942,917943,917944,917945,917946,917947,917948,917949,917950,917951,917952,917953,917954,917955,917956,917957,917958,917959,917960,917961,917962,917963,917964,917965,917966,917967,917968,917969,917970,917971,917972,917973,917974,917975,917976,917977,917978,917979,917980,917981,917982,917983,917984,917985,917986,917987,917988,917989,917990,917991,917992,917993,917994,917995,917996,917997,917998,917999]) - -/** - * Check whether a given character is a combining mark or not. - * @param {number} c The character code to check. - * @returns {boolean} `true` if the character belongs to the category, one of `Mc`, `Me`, and `Mn`. - */ -module.exports = function isCombiningCharacter(c) { - return combiningChars.has(c); -}; diff --git a/tools/node_modules/eslint/lib/util/unicode/is-emoji-modifier.js b/tools/node_modules/eslint/lib/util/unicode/is-emoji-modifier.js deleted file mode 100644 index 1bd5f557dcc4ab..00000000000000 --- a/tools/node_modules/eslint/lib/util/unicode/is-emoji-modifier.js +++ /dev/null @@ -1,13 +0,0 @@ -/** - * @author Toru Nagashima - */ -"use strict"; - -/** - * Check whether a given character is an emoji modifier. - * @param {number} code The character code to check. - * @returns {boolean} `true` if the character is an emoji modifier. - */ -module.exports = function isEmojiModifier(code) { - return code >= 0x1F3FB && code <= 0x1F3FF; -}; diff --git a/tools/node_modules/eslint/lib/util/unicode/is-regional-indicator-symbol.js b/tools/node_modules/eslint/lib/util/unicode/is-regional-indicator-symbol.js deleted file mode 100644 index c48ed46ef8fded..00000000000000 --- a/tools/node_modules/eslint/lib/util/unicode/is-regional-indicator-symbol.js +++ /dev/null @@ -1,13 +0,0 @@ -/** - * @author Toru Nagashima - */ -"use strict"; - -/** - * Check whether a given character is a regional indicator symbol. - * @param {number} code The character code to check. - * @returns {boolean} `true` if the character is a regional indicator symbol. - */ -module.exports = function isRegionalIndicatorSymbol(code) { - return code >= 0x1F1E6 && code <= 0x1F1FF; -}; diff --git a/tools/node_modules/eslint/lib/util/unicode/is-surrogate-pair.js b/tools/node_modules/eslint/lib/util/unicode/is-surrogate-pair.js deleted file mode 100644 index b8e5c1cacdb6a9..00000000000000 --- a/tools/node_modules/eslint/lib/util/unicode/is-surrogate-pair.js +++ /dev/null @@ -1,14 +0,0 @@ -/** - * @author Toru Nagashima - */ -"use strict"; - -/** - * Check whether given two characters are a surrogate pair. - * @param {number} lead The code of the lead character. - * @param {number} tail The code of the tail character. - * @returns {boolean} `true` if the character pair is a surrogate pair. - */ -module.exports = function isSurrogatePair(lead, tail) { - return lead >= 0xD800 && lead < 0xDC00 && tail >= 0xDC00 && tail < 0xE000; -}; diff --git a/tools/node_modules/eslint/lib/util/xml-escape.js b/tools/node_modules/eslint/lib/util/xml-escape.js deleted file mode 100644 index 9f43c99c46a23c..00000000000000 --- a/tools/node_modules/eslint/lib/util/xml-escape.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * @fileoverview XML character escaper - * @author George Chung - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -/** - * Returns the escaped value for a character - * @param {string} s string to examine - * @returns {string} severity level - * @private - */ -module.exports = function(s) { - return (`${s}`).replace(/[<>&"'\x00-\x1F\x7F\u0080-\uFFFF]/g, c => { // eslint-disable-line no-control-regex - switch (c) { - case "<": - return "<"; - case ">": - return ">"; - case "&": - return "&"; - case "\"": - return """; - case "'": - return "'"; - default: - return `&#${c.charCodeAt(0)};`; - } - }); -}; diff --git a/tools/node_modules/eslint/messages/all-files-ignored.txt b/tools/node_modules/eslint/messages/all-files-ignored.txt deleted file mode 100644 index 3f4c8ced4c9ada..00000000000000 --- a/tools/node_modules/eslint/messages/all-files-ignored.txt +++ /dev/null @@ -1,8 +0,0 @@ -You are linting "<%= pattern %>", but all of the files matching the glob pattern "<%= pattern %>" are ignored. - -If you don't want to lint these files, remove the pattern "<%= pattern %>" from the list of arguments passed to ESLint. - -If you do want to lint these files, try the following solutions: - -* Check your .eslintignore file, or the eslintIgnore property in package.json, to ensure that the files are not configured to be ignored. -* Explicitly list the files from this glob that you'd like to lint on the command-line, rather than providing a glob as an argument. diff --git a/tools/node_modules/eslint/messages/extend-config-missing.txt b/tools/node_modules/eslint/messages/extend-config-missing.txt deleted file mode 100644 index 38e64581970b0e..00000000000000 --- a/tools/node_modules/eslint/messages/extend-config-missing.txt +++ /dev/null @@ -1,3 +0,0 @@ -ESLint couldn't find the config "<%- configName %>" to extend from. Please check that the name of the config is correct. - -If you still have problems, please stop by https://gitter.im/eslint/eslint to chat with the team. diff --git a/tools/node_modules/eslint/messages/failed-to-read-json.txt b/tools/node_modules/eslint/messages/failed-to-read-json.txt deleted file mode 100644 index b5e2b861cfcf23..00000000000000 --- a/tools/node_modules/eslint/messages/failed-to-read-json.txt +++ /dev/null @@ -1,3 +0,0 @@ -Failed to read JSON file at <%= path %>: - -<%= message %> diff --git a/tools/node_modules/eslint/messages/file-not-found.txt b/tools/node_modules/eslint/messages/file-not-found.txt deleted file mode 100644 index 97e2d37fa94e71..00000000000000 --- a/tools/node_modules/eslint/messages/file-not-found.txt +++ /dev/null @@ -1,2 +0,0 @@ -No files matching the pattern "<%= pattern %>" were found. -Please check for typing mistakes in the pattern. diff --git a/tools/node_modules/eslint/messages/no-config-found.txt b/tools/node_modules/eslint/messages/no-config-found.txt deleted file mode 100644 index 2f95c41b8c72f4..00000000000000 --- a/tools/node_modules/eslint/messages/no-config-found.txt +++ /dev/null @@ -1,7 +0,0 @@ -ESLint couldn't find a configuration file. To set up a configuration file for this project, please run: - - eslint --init - -ESLint looked for configuration files in <%= directory %> and its ancestors. If it found none, it then looked in your home directory. - -If you think you already have a configuration file or if you need more help, please stop by the ESLint chat room: https://gitter.im/eslint/eslint diff --git a/tools/node_modules/eslint/messages/plugin-missing.txt b/tools/node_modules/eslint/messages/plugin-missing.txt deleted file mode 100644 index 766020b2b8f647..00000000000000 --- a/tools/node_modules/eslint/messages/plugin-missing.txt +++ /dev/null @@ -1,11 +0,0 @@ -ESLint couldn't find the plugin "<%- pluginName %>". This can happen for a couple different reasons: - -1. If ESLint is installed globally, then make sure <%- pluginName %> is also installed globally. A globally-installed ESLint cannot find a locally-installed plugin. - -2. If ESLint is installed locally, then it's likely that the plugin isn't installed correctly. Try reinstalling by running the following: - - npm i <%- pluginName %>@latest --save-dev - -Path to ESLint package: <%- eslintPath %> - -If you still can't figure out the problem, please stop by https://gitter.im/eslint/eslint to chat with the team. diff --git a/tools/node_modules/eslint/messages/whitespace-found.txt b/tools/node_modules/eslint/messages/whitespace-found.txt deleted file mode 100644 index eea4efccedb1d1..00000000000000 --- a/tools/node_modules/eslint/messages/whitespace-found.txt +++ /dev/null @@ -1,3 +0,0 @@ -ESLint couldn't find the plugin "<%- pluginName %>". because there is whitespace in the name. Please check your configuration and remove all whitespace from the plugin name. - -If you still can't figure out the problem, please stop by https://gitter.im/eslint/eslint to chat with the team. diff --git a/tools/node_modules/eslint/node_modules/@babel/code-frame/LICENSE b/tools/node_modules/eslint/node_modules/@babel/code-frame/LICENSE deleted file mode 100644 index 620366eb90071c..00000000000000 --- a/tools/node_modules/eslint/node_modules/@babel/code-frame/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -MIT License - -Copyright (c) 2014-2018 Sebastian McKenzie - -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/node_modules/eslint/node_modules/@babel/code-frame/README.md b/tools/node_modules/eslint/node_modules/@babel/code-frame/README.md deleted file mode 100644 index 185f93d2471999..00000000000000 --- a/tools/node_modules/eslint/node_modules/@babel/code-frame/README.md +++ /dev/null @@ -1,19 +0,0 @@ -# @babel/code-frame - -> Generate errors that contain a code frame that point to source locations. - -See our website [@babel/code-frame](https://babeljs.io/docs/en/next/babel-code-frame.html) for more information. - -## Install - -Using npm: - -```sh -npm install --save-dev @babel/code-frame -``` - -or using yarn: - -```sh -yarn add @babel/code-frame --dev -``` diff --git a/tools/node_modules/eslint/node_modules/@babel/code-frame/lib/index.js b/tools/node_modules/eslint/node_modules/@babel/code-frame/lib/index.js deleted file mode 100644 index 1f64c6ce7b992d..00000000000000 --- a/tools/node_modules/eslint/node_modules/@babel/code-frame/lib/index.js +++ /dev/null @@ -1,173 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.codeFrameColumns = codeFrameColumns; -exports.default = _default; - -function _highlight() { - const data = _interopRequireWildcard(require("@babel/highlight")); - - _highlight = function () { - return data; - }; - - return data; -} - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } - -let deprecationWarningShown = false; - -function getDefs(chalk) { - return { - gutter: chalk.grey, - marker: chalk.red.bold, - message: chalk.red.bold - }; -} - -const NEWLINE = /\r\n|[\n\r\u2028\u2029]/; - -function getMarkerLines(loc, source, opts) { - const startLoc = Object.assign({ - column: 0, - line: -1 - }, loc.start); - const endLoc = Object.assign({}, startLoc, loc.end); - const { - linesAbove = 2, - linesBelow = 3 - } = opts || {}; - const startLine = startLoc.line; - const startColumn = startLoc.column; - const endLine = endLoc.line; - const endColumn = endLoc.column; - let start = Math.max(startLine - (linesAbove + 1), 0); - let end = Math.min(source.length, endLine + linesBelow); - - if (startLine === -1) { - start = 0; - } - - if (endLine === -1) { - end = source.length; - } - - const lineDiff = endLine - startLine; - const markerLines = {}; - - if (lineDiff) { - for (let i = 0; i <= lineDiff; i++) { - const lineNumber = i + startLine; - - if (!startColumn) { - markerLines[lineNumber] = true; - } else if (i === 0) { - const sourceLength = source[lineNumber - 1].length; - markerLines[lineNumber] = [startColumn, sourceLength - startColumn]; - } else if (i === lineDiff) { - markerLines[lineNumber] = [0, endColumn]; - } else { - const sourceLength = source[lineNumber - i].length; - markerLines[lineNumber] = [0, sourceLength]; - } - } - } else { - if (startColumn === endColumn) { - if (startColumn) { - markerLines[startLine] = [startColumn, 0]; - } else { - markerLines[startLine] = true; - } - } else { - markerLines[startLine] = [startColumn, endColumn - startColumn]; - } - } - - return { - start, - end, - markerLines - }; -} - -function codeFrameColumns(rawLines, loc, opts = {}) { - const highlighted = (opts.highlightCode || opts.forceColor) && (0, _highlight().shouldHighlight)(opts); - const chalk = (0, _highlight().getChalk)(opts); - const defs = getDefs(chalk); - - const maybeHighlight = (chalkFn, string) => { - return highlighted ? chalkFn(string) : string; - }; - - if (highlighted) rawLines = (0, _highlight().default)(rawLines, opts); - const lines = rawLines.split(NEWLINE); - const { - start, - end, - markerLines - } = getMarkerLines(loc, lines, opts); - const hasColumns = loc.start && typeof loc.start.column === "number"; - const numberMaxWidth = String(end).length; - let frame = lines.slice(start, end).map((line, index) => { - const number = start + 1 + index; - const paddedNumber = ` ${number}`.slice(-numberMaxWidth); - const gutter = ` ${paddedNumber} | `; - const hasMarker = markerLines[number]; - const lastMarkerLine = !markerLines[number + 1]; - - if (hasMarker) { - let markerLine = ""; - - if (Array.isArray(hasMarker)) { - const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " "); - const numberOfMarkers = hasMarker[1] || 1; - markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), markerSpacing, maybeHighlight(defs.marker, "^").repeat(numberOfMarkers)].join(""); - - if (lastMarkerLine && opts.message) { - markerLine += " " + maybeHighlight(defs.message, opts.message); - } - } - - return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line, markerLine].join(""); - } else { - return ` ${maybeHighlight(defs.gutter, gutter)}${line}`; - } - }).join("\n"); - - if (opts.message && !hasColumns) { - frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message}\n${frame}`; - } - - if (highlighted) { - return chalk.reset(frame); - } else { - return frame; - } -} - -function _default(rawLines, lineNumber, colNumber, opts = {}) { - if (!deprecationWarningShown) { - deprecationWarningShown = true; - const message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`."; - - if (process.emitWarning) { - process.emitWarning(message, "DeprecationWarning"); - } else { - const deprecationError = new Error(message); - deprecationError.name = "DeprecationWarning"; - console.warn(new Error(message)); - } - } - - colNumber = Math.max(colNumber, 0); - const location = { - start: { - column: colNumber, - line: lineNumber - } - }; - return codeFrameColumns(rawLines, location, opts); -} \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/@babel/code-frame/package.json b/tools/node_modules/eslint/node_modules/@babel/code-frame/package.json deleted file mode 100644 index f3b551dfa972de..00000000000000 --- a/tools/node_modules/eslint/node_modules/@babel/code-frame/package.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "author": { - "name": "Sebastian McKenzie", - "email": "sebmck@gmail.com" - }, - "bundleDependencies": false, - "dependencies": { - "@babel/highlight": "^7.0.0" - }, - "deprecated": false, - "description": "Generate errors that contain a code frame that point to source locations.", - "devDependencies": { - "chalk": "^2.0.0", - "strip-ansi": "^4.0.0" - }, - "homepage": "https://babeljs.io/", - "license": "MIT", - "main": "lib/index.js", - "name": "@babel/code-frame", - "repository": { - "type": "git", - "url": "https://github.com/babel/babel/tree/master/packages/babel-code-frame" - }, - "version": "7.0.0" -} \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/@babel/highlight/LICENSE b/tools/node_modules/eslint/node_modules/@babel/highlight/LICENSE deleted file mode 100644 index 620366eb90071c..00000000000000 --- a/tools/node_modules/eslint/node_modules/@babel/highlight/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -MIT License - -Copyright (c) 2014-2018 Sebastian McKenzie - -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/node_modules/eslint/node_modules/@babel/highlight/README.md b/tools/node_modules/eslint/node_modules/@babel/highlight/README.md deleted file mode 100644 index 72dae6094590f3..00000000000000 --- a/tools/node_modules/eslint/node_modules/@babel/highlight/README.md +++ /dev/null @@ -1,19 +0,0 @@ -# @babel/highlight - -> Syntax highlight JavaScript strings for output in terminals. - -See our website [@babel/highlight](https://babeljs.io/docs/en/next/babel-highlight.html) for more information. - -## Install - -Using npm: - -```sh -npm install --save-dev @babel/highlight -``` - -or using yarn: - -```sh -yarn add @babel/highlight --dev -``` diff --git a/tools/node_modules/eslint/node_modules/@babel/highlight/lib/index.js b/tools/node_modules/eslint/node_modules/@babel/highlight/lib/index.js deleted file mode 100644 index 6ac5b4a350b8e6..00000000000000 --- a/tools/node_modules/eslint/node_modules/@babel/highlight/lib/index.js +++ /dev/null @@ -1,129 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.shouldHighlight = shouldHighlight; -exports.getChalk = getChalk; -exports.default = highlight; - -function _jsTokens() { - const data = _interopRequireWildcard(require("js-tokens")); - - _jsTokens = function () { - return data; - }; - - return data; -} - -function _esutils() { - const data = _interopRequireDefault(require("esutils")); - - _esutils = function () { - return data; - }; - - return data; -} - -function _chalk() { - const data = _interopRequireDefault(require("chalk")); - - _chalk = function () { - return data; - }; - - return data; -} - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } - -function getDefs(chalk) { - return { - keyword: chalk.cyan, - capitalized: chalk.yellow, - jsx_tag: chalk.yellow, - punctuator: chalk.yellow, - number: chalk.magenta, - string: chalk.green, - regex: chalk.magenta, - comment: chalk.grey, - invalid: chalk.white.bgRed.bold - }; -} - -const NEWLINE = /\r\n|[\n\r\u2028\u2029]/; -const JSX_TAG = /^[a-z][\w-]*$/i; -const BRACKET = /^[()[\]{}]$/; - -function getTokenType(match) { - const [offset, text] = match.slice(-2); - const token = (0, _jsTokens().matchToToken)(match); - - if (token.type === "name") { - if (_esutils().default.keyword.isReservedWordES6(token.value)) { - return "keyword"; - } - - if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.substr(offset - 2, 2) == " colorize(str)).join("\n"); - } else { - return args[0]; - } - }); -} - -function shouldHighlight(options) { - return _chalk().default.supportsColor || options.forceColor; -} - -function getChalk(options) { - let chalk = _chalk().default; - - if (options.forceColor) { - chalk = new (_chalk().default.constructor)({ - enabled: true, - level: 1 - }); - } - - return chalk; -} - -function highlight(code, options = {}) { - if (shouldHighlight(options)) { - const chalk = getChalk(options); - const defs = getDefs(chalk); - return highlightTokens(defs, code); - } else { - return code; - } -} \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/@babel/highlight/package.json b/tools/node_modules/eslint/node_modules/@babel/highlight/package.json deleted file mode 100644 index ff84c66ec29732..00000000000000 --- a/tools/node_modules/eslint/node_modules/@babel/highlight/package.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "author": { - "name": "suchipi", - "email": "me@suchipi.com" - }, - "bundleDependencies": false, - "dependencies": { - "chalk": "^2.0.0", - "esutils": "^2.0.2", - "js-tokens": "^4.0.0" - }, - "deprecated": false, - "description": "Syntax highlight JavaScript strings for output in terminals.", - "devDependencies": { - "strip-ansi": "^4.0.0" - }, - "homepage": "https://babeljs.io/", - "license": "MIT", - "main": "lib/index.js", - "name": "@babel/highlight", - "repository": { - "type": "git", - "url": "https://github.com/babel/babel/tree/master/packages/babel-highlight" - }, - "version": "7.0.0" -} \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/acorn-jsx/LICENSE b/tools/node_modules/eslint/node_modules/acorn-jsx/LICENSE deleted file mode 100644 index 695d4b93082bee..00000000000000 --- a/tools/node_modules/eslint/node_modules/acorn-jsx/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (C) 2012-2017 by Ingvar Stepanyan - -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/node_modules/eslint/node_modules/acorn-jsx/README.md b/tools/node_modules/eslint/node_modules/acorn-jsx/README.md deleted file mode 100644 index 2bbb1d99fd8cfa..00000000000000 --- a/tools/node_modules/eslint/node_modules/acorn-jsx/README.md +++ /dev/null @@ -1,44 +0,0 @@ -# Acorn-JSX - -[![Build Status](https://travis-ci.org/RReverser/acorn-jsx.svg?branch=master)](https://travis-ci.org/RReverser/acorn-jsx) -[![NPM version](https://img.shields.io/npm/v/acorn-jsx.svg)](https://www.npmjs.org/package/acorn-jsx) - -This is plugin for [Acorn](http://marijnhaverbeke.nl/acorn/) - a tiny, fast JavaScript parser, written completely in JavaScript. - -It was created as an experimental alternative, faster [React.js JSX](http://facebook.github.io/react/docs/jsx-in-depth.html) parser. - -According to [benchmarks](https://github.com/RReverser/acorn-jsx/blob/master/test/bench.html), Acorn-JSX is 2x faster than official [Esprima-based parser](https://github.com/facebook/esprima) when location tracking is turned on in both (call it "source maps enabled mode"). At the same time, it consumes all the ES6+JSX syntax that can be consumed by Esprima-FB (this is proved by [official tests](https://github.com/RReverser/acorn-jsx/blob/master/test/tests-jsx.js)). - -**UPDATE [14-Apr-2015]**: Facebook implementation started [deprecation process](https://github.com/facebook/esprima/issues/111) in favor of Acorn + Acorn-JSX + Babel for parsing and transpiling JSX syntax. - -## Transpiler - -Please note that this tool only parses source code to JSX AST, which is useful for various language tools and services. If you want to transpile your code to regular ES5-compliant JavaScript with source map, check out the [babel transpiler](https://babeljs.io/) which uses `acorn-jsx` under the hood. - -## Usage - -Requiring this module provides you with an Acorn plugin that you can use like this: - -```javascript -var acorn = require("acorn"); -var jsx = require("acorn-jsx"); -acorn.Parser.extend(jsx()).parse("my(, 'code');"); -``` - -Note that official spec doesn't support mix of XML namespaces and object-style access in tag names (#27) like in ``, so it was deprecated in `acorn-jsx@3.0`. If you still want to opt-in to support of such constructions, you can pass the following option: - -```javascript -acorn.Parser.extend(jsx({ allowNamespacedObjects: true })) -``` - -Also, since most apps use pure React transformer, a new option was introduced that allows to prohibit namespaces completely: - -```javascript -acorn.Parser.extend(jsx({ allowNamespaces: false })) -``` - -Note that by default `allowNamespaces` is enabled for spec compliancy. - -## License - -This plugin is issued under the [MIT license](./LICENSE). diff --git a/tools/node_modules/eslint/node_modules/acorn-jsx/index.js b/tools/node_modules/eslint/node_modules/acorn-jsx/index.js deleted file mode 100644 index 460e7933992122..00000000000000 --- a/tools/node_modules/eslint/node_modules/acorn-jsx/index.js +++ /dev/null @@ -1,441 +0,0 @@ -'use strict'; - -const XHTMLEntities = require('./xhtml'); - -const hexNumber = /^[\da-fA-F]+$/; -const decimalNumber = /^\d+$/; - -const acorn = require("acorn"); -const tt = acorn.tokTypes; -const TokContext = acorn.TokContext; -const tokContexts = acorn.tokContexts; -const TokenType = acorn.TokenType; -const isNewLine = acorn.isNewLine; -const isIdentifierStart = acorn.isIdentifierStart; -const isIdentifierChar = acorn.isIdentifierChar; - -const tc_oTag = new TokContext('...', true, true); - -const tok = { - jsxName: new TokenType('jsxName'), - jsxText: new TokenType('jsxText', {beforeExpr: true}), - jsxTagStart: new TokenType('jsxTagStart'), - jsxTagEnd: new TokenType('jsxTagEnd') -} - -tok.jsxTagStart.updateContext = function() { - this.context.push(tc_expr); // treat as beginning of JSX expression - this.context.push(tc_oTag); // start opening tag context - this.exprAllowed = false; -}; -tok.jsxTagEnd.updateContext = function(prevType) { - let out = this.context.pop(); - if (out === tc_oTag && prevType === tt.slash || out === tc_cTag) { - this.context.pop(); - this.exprAllowed = this.curContext() === tc_expr; - } else { - this.exprAllowed = true; - } -}; - -// Transforms JSX element name to string. - -function getQualifiedJSXName(object) { - if (!object) - return object; - - if (object.type === 'JSXIdentifier') - return object.name; - - if (object.type === 'JSXNamespacedName') - return object.namespace.name + ':' + object.name.name; - - if (object.type === 'JSXMemberExpression') - return getQualifiedJSXName(object.object) + '.' + - getQualifiedJSXName(object.property); -} - -module.exports = function(options) { - options = options || {}; - return function(Parser) { - return plugin({ - allowNamespaces: options.allowNamespaces !== false, - allowNamespacedObjects: !!options.allowNamespacedObjects - }, Parser); - } -}; -module.exports.tokTypes = tok; - -function plugin(options, Parser) { - return class extends Parser { - // Reads inline JSX contents token. - jsx_readToken() { - let out = '', chunkStart = this.pos; - for (;;) { - if (this.pos >= this.input.length) - this.raise(this.start, 'Unterminated JSX contents'); - let ch = this.input.charCodeAt(this.pos); - - switch (ch) { - case 60: // '<' - case 123: // '{' - if (this.pos === this.start) { - if (ch === 60 && this.exprAllowed) { - ++this.pos; - return this.finishToken(tok.jsxTagStart); - } - return this.getTokenFromCode(ch); - } - out += this.input.slice(chunkStart, this.pos); - return this.finishToken(tok.jsxText, out); - - case 38: // '&' - out += this.input.slice(chunkStart, this.pos); - out += this.jsx_readEntity(); - chunkStart = this.pos; - break; - - default: - if (isNewLine(ch)) { - out += this.input.slice(chunkStart, this.pos); - out += this.jsx_readNewLine(true); - chunkStart = this.pos; - } else { - ++this.pos; - } - } - } - } - - jsx_readNewLine(normalizeCRLF) { - let ch = this.input.charCodeAt(this.pos); - let out; - ++this.pos; - if (ch === 13 && this.input.charCodeAt(this.pos) === 10) { - ++this.pos; - out = normalizeCRLF ? '\n' : '\r\n'; - } else { - out = String.fromCharCode(ch); - } - if (this.options.locations) { - ++this.curLine; - this.lineStart = this.pos; - } - - return out; - } - - jsx_readString(quote) { - let out = '', chunkStart = ++this.pos; - for (;;) { - if (this.pos >= this.input.length) - this.raise(this.start, 'Unterminated string constant'); - let ch = this.input.charCodeAt(this.pos); - if (ch === quote) break; - if (ch === 38) { // '&' - out += this.input.slice(chunkStart, this.pos); - out += this.jsx_readEntity(); - chunkStart = this.pos; - } else if (isNewLine(ch)) { - out += this.input.slice(chunkStart, this.pos); - out += this.jsx_readNewLine(false); - chunkStart = this.pos; - } else { - ++this.pos; - } - } - out += this.input.slice(chunkStart, this.pos++); - return this.finishToken(tt.string, out); - } - - jsx_readEntity() { - let str = '', count = 0, entity; - let ch = this.input[this.pos]; - if (ch !== '&') - this.raise(this.pos, 'Entity must start with an ampersand'); - let startPos = ++this.pos; - while (this.pos < this.input.length && count++ < 10) { - ch = this.input[this.pos++]; - if (ch === ';') { - if (str[0] === '#') { - if (str[1] === 'x') { - str = str.substr(2); - if (hexNumber.test(str)) - entity = String.fromCharCode(parseInt(str, 16)); - } else { - str = str.substr(1); - if (decimalNumber.test(str)) - entity = String.fromCharCode(parseInt(str, 10)); - } - } else { - entity = XHTMLEntities[str]; - } - break; - } - str += ch; - } - if (!entity) { - this.pos = startPos; - return '&'; - } - return entity; - } - - // Read a JSX identifier (valid tag or attribute name). - // - // Optimized version since JSX identifiers can't contain - // escape characters and so can be read as single slice. - // Also assumes that first character was already checked - // by isIdentifierStart in readToken. - - jsx_readWord() { - let ch, start = this.pos; - do { - ch = this.input.charCodeAt(++this.pos); - } while (isIdentifierChar(ch) || ch === 45); // '-' - return this.finishToken(tok.jsxName, this.input.slice(start, this.pos)); - } - - // Parse next token as JSX identifier - - jsx_parseIdentifier() { - let node = this.startNode(); - if (this.type === tok.jsxName) - node.name = this.value; - else if (this.type.keyword) - node.name = this.type.keyword; - else - this.unexpected(); - this.next(); - return this.finishNode(node, 'JSXIdentifier'); - } - - // Parse namespaced identifier. - - jsx_parseNamespacedName() { - let startPos = this.start, startLoc = this.startLoc; - let name = this.jsx_parseIdentifier(); - if (!options.allowNamespaces || !this.eat(tt.colon)) return name; - var node = this.startNodeAt(startPos, startLoc); - node.namespace = name; - node.name = this.jsx_parseIdentifier(); - return this.finishNode(node, 'JSXNamespacedName'); - } - - // Parses element name in any form - namespaced, member - // or single identifier. - - jsx_parseElementName() { - if (this.type === tok.jsxTagEnd) return ''; - let startPos = this.start, startLoc = this.startLoc; - let node = this.jsx_parseNamespacedName(); - if (this.type === tt.dot && node.type === 'JSXNamespacedName' && !options.allowNamespacedObjects) { - this.unexpected(); - } - while (this.eat(tt.dot)) { - let newNode = this.startNodeAt(startPos, startLoc); - newNode.object = node; - newNode.property = this.jsx_parseIdentifier(); - node = this.finishNode(newNode, 'JSXMemberExpression'); - } - return node; - } - - // Parses any type of JSX attribute value. - - jsx_parseAttributeValue() { - switch (this.type) { - case tt.braceL: - let node = this.jsx_parseExpressionContainer(); - if (node.expression.type === 'JSXEmptyExpression') - this.raise(node.start, 'JSX attributes must only be assigned a non-empty expression'); - return node; - - case tok.jsxTagStart: - case tt.string: - return this.parseExprAtom(); - - default: - this.raise(this.start, 'JSX value should be either an expression or a quoted JSX text'); - } - } - - // JSXEmptyExpression is unique type since it doesn't actually parse anything, - // and so it should start at the end of last read token (left brace) and finish - // at the beginning of the next one (right brace). - - jsx_parseEmptyExpression() { - let node = this.startNodeAt(this.lastTokEnd, this.lastTokEndLoc); - return this.finishNodeAt(node, 'JSXEmptyExpression', this.start, this.startLoc); - } - - // Parses JSX expression enclosed into curly brackets. - - jsx_parseExpressionContainer() { - let node = this.startNode(); - this.next(); - node.expression = this.type === tt.braceR - ? this.jsx_parseEmptyExpression() - : this.parseExpression(); - this.expect(tt.braceR); - return this.finishNode(node, 'JSXExpressionContainer'); - } - - // Parses following JSX attribute name-value pair. - - jsx_parseAttribute() { - let node = this.startNode(); - if (this.eat(tt.braceL)) { - this.expect(tt.ellipsis); - node.argument = this.parseMaybeAssign(); - this.expect(tt.braceR); - return this.finishNode(node, 'JSXSpreadAttribute'); - } - node.name = this.jsx_parseNamespacedName(); - node.value = this.eat(tt.eq) ? this.jsx_parseAttributeValue() : null; - return this.finishNode(node, 'JSXAttribute'); - } - - // Parses JSX opening tag starting after '<'. - - jsx_parseOpeningElementAt(startPos, startLoc) { - let node = this.startNodeAt(startPos, startLoc); - node.attributes = []; - let nodeName = this.jsx_parseElementName(); - if (nodeName) node.name = nodeName; - while (this.type !== tt.slash && this.type !== tok.jsxTagEnd) - node.attributes.push(this.jsx_parseAttribute()); - node.selfClosing = this.eat(tt.slash); - this.expect(tok.jsxTagEnd); - return this.finishNode(node, nodeName ? 'JSXOpeningElement' : 'JSXOpeningFragment'); - } - - // Parses JSX closing tag starting after ''); - } - } - let fragmentOrElement = openingElement.name ? 'Element' : 'Fragment'; - - node['opening' + fragmentOrElement] = openingElement; - node['closing' + fragmentOrElement] = closingElement; - node.children = children; - if (this.type === tt.relational && this.value === "<") { - this.raise(this.start, "Adjacent JSX elements must be wrapped in an enclosing tag"); - } - return this.finishNode(node, 'JSX' + fragmentOrElement); - } - - // Parse JSX text - - jsx_parseText(value) { - let node = this.parseLiteral(value); - node.type = "JSXText"; - return node; - } - - // Parses entire JSX element from current position. - - jsx_parseElement() { - let startPos = this.start, startLoc = this.startLoc; - this.next(); - return this.jsx_parseElementAt(startPos, startLoc); - } - - parseExprAtom(refShortHandDefaultPos) { - if (this.type === tok.jsxText) - return this.jsx_parseText(this.value); - else if (this.type === tok.jsxTagStart) - return this.jsx_parseElement(); - else - return super.parseExprAtom(refShortHandDefaultPos); - } - - readToken(code) { - let context = this.curContext(); - - if (context === tc_expr) return this.jsx_readToken(); - - if (context === tc_oTag || context === tc_cTag) { - if (isIdentifierStart(code)) return this.jsx_readWord(); - - if (code == 62) { - ++this.pos; - return this.finishToken(tok.jsxTagEnd); - } - - if ((code === 34 || code === 39) && context == tc_oTag) - return this.jsx_readString(code); - } - - if (code === 60 && this.exprAllowed && this.input.charCodeAt(this.pos + 1) !== 33) { - ++this.pos; - return this.finishToken(tok.jsxTagStart); - } - return super.readToken(code) - } - - updateContext(prevType) { - if (this.type == tt.braceL) { - var curContext = this.curContext(); - if (curContext == tc_oTag) this.context.push(tokContexts.b_expr); - else if (curContext == tc_expr) this.context.push(tokContexts.b_tmpl); - else super.updateContext(prevType) - this.exprAllowed = true; - } else if (this.type === tt.slash && prevType === tok.jsxTagStart) { - this.context.length -= 2; // do not consider JSX expr -> JSX open tag -> ... anymore - this.context.push(tc_cTag); // reconsider as closing tag context - this.exprAllowed = false; - } else { - return super.updateContext(prevType); - } - } - }; -} diff --git a/tools/node_modules/eslint/node_modules/acorn-jsx/package.json b/tools/node_modules/eslint/node_modules/acorn-jsx/package.json deleted file mode 100644 index 89d06d6900deaa..00000000000000 --- a/tools/node_modules/eslint/node_modules/acorn-jsx/package.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "bugs": { - "url": "https://github.com/RReverser/acorn-jsx/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Alternative, faster React.js JSX parser", - "devDependencies": { - "acorn": "^6.0.0" - }, - "homepage": "https://github.com/RReverser/acorn-jsx", - "license": "MIT", - "maintainers": [ - { - "name": "Ingvar Stepanyan", - "email": "me@rreverser.com", - "url": "http://rreverser.com/" - } - ], - "name": "acorn-jsx", - "peerDependencies": { - "acorn": "^6.0.0" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/RReverser/acorn-jsx.git" - }, - "scripts": { - "test": "node test/run.js" - }, - "version": "5.0.1" -} \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/acorn-jsx/xhtml.js b/tools/node_modules/eslint/node_modules/acorn-jsx/xhtml.js deleted file mode 100644 index c1520092f8e31e..00000000000000 --- a/tools/node_modules/eslint/node_modules/acorn-jsx/xhtml.js +++ /dev/null @@ -1,255 +0,0 @@ -module.exports = { - quot: '\u0022', - amp: '&', - apos: '\u0027', - lt: '<', - gt: '>', - nbsp: '\u00A0', - iexcl: '\u00A1', - cent: '\u00A2', - pound: '\u00A3', - curren: '\u00A4', - yen: '\u00A5', - brvbar: '\u00A6', - sect: '\u00A7', - uml: '\u00A8', - copy: '\u00A9', - ordf: '\u00AA', - laquo: '\u00AB', - not: '\u00AC', - shy: '\u00AD', - reg: '\u00AE', - macr: '\u00AF', - deg: '\u00B0', - plusmn: '\u00B1', - sup2: '\u00B2', - sup3: '\u00B3', - acute: '\u00B4', - micro: '\u00B5', - para: '\u00B6', - middot: '\u00B7', - cedil: '\u00B8', - sup1: '\u00B9', - ordm: '\u00BA', - raquo: '\u00BB', - frac14: '\u00BC', - frac12: '\u00BD', - frac34: '\u00BE', - iquest: '\u00BF', - Agrave: '\u00C0', - Aacute: '\u00C1', - Acirc: '\u00C2', - Atilde: '\u00C3', - Auml: '\u00C4', - Aring: '\u00C5', - AElig: '\u00C6', - Ccedil: '\u00C7', - Egrave: '\u00C8', - Eacute: '\u00C9', - Ecirc: '\u00CA', - Euml: '\u00CB', - Igrave: '\u00CC', - Iacute: '\u00CD', - Icirc: '\u00CE', - Iuml: '\u00CF', - ETH: '\u00D0', - Ntilde: '\u00D1', - Ograve: '\u00D2', - Oacute: '\u00D3', - Ocirc: '\u00D4', - Otilde: '\u00D5', - Ouml: '\u00D6', - times: '\u00D7', - Oslash: '\u00D8', - Ugrave: '\u00D9', - Uacute: '\u00DA', - Ucirc: '\u00DB', - Uuml: '\u00DC', - Yacute: '\u00DD', - THORN: '\u00DE', - szlig: '\u00DF', - agrave: '\u00E0', - aacute: '\u00E1', - acirc: '\u00E2', - atilde: '\u00E3', - auml: '\u00E4', - aring: '\u00E5', - aelig: '\u00E6', - ccedil: '\u00E7', - egrave: '\u00E8', - eacute: '\u00E9', - ecirc: '\u00EA', - euml: '\u00EB', - igrave: '\u00EC', - iacute: '\u00ED', - icirc: '\u00EE', - iuml: '\u00EF', - eth: '\u00F0', - ntilde: '\u00F1', - ograve: '\u00F2', - oacute: '\u00F3', - ocirc: '\u00F4', - otilde: '\u00F5', - ouml: '\u00F6', - divide: '\u00F7', - oslash: '\u00F8', - ugrave: '\u00F9', - uacute: '\u00FA', - ucirc: '\u00FB', - uuml: '\u00FC', - yacute: '\u00FD', - thorn: '\u00FE', - yuml: '\u00FF', - OElig: '\u0152', - oelig: '\u0153', - Scaron: '\u0160', - scaron: '\u0161', - Yuml: '\u0178', - fnof: '\u0192', - circ: '\u02C6', - tilde: '\u02DC', - Alpha: '\u0391', - Beta: '\u0392', - Gamma: '\u0393', - Delta: '\u0394', - Epsilon: '\u0395', - Zeta: '\u0396', - Eta: '\u0397', - Theta: '\u0398', - Iota: '\u0399', - Kappa: '\u039A', - Lambda: '\u039B', - Mu: '\u039C', - Nu: '\u039D', - Xi: '\u039E', - Omicron: '\u039F', - Pi: '\u03A0', - Rho: '\u03A1', - Sigma: '\u03A3', - Tau: '\u03A4', - Upsilon: '\u03A5', - Phi: '\u03A6', - Chi: '\u03A7', - Psi: '\u03A8', - Omega: '\u03A9', - alpha: '\u03B1', - beta: '\u03B2', - gamma: '\u03B3', - delta: '\u03B4', - epsilon: '\u03B5', - zeta: '\u03B6', - eta: '\u03B7', - theta: '\u03B8', - iota: '\u03B9', - kappa: '\u03BA', - lambda: '\u03BB', - mu: '\u03BC', - nu: '\u03BD', - xi: '\u03BE', - omicron: '\u03BF', - pi: '\u03C0', - rho: '\u03C1', - sigmaf: '\u03C2', - sigma: '\u03C3', - tau: '\u03C4', - upsilon: '\u03C5', - phi: '\u03C6', - chi: '\u03C7', - psi: '\u03C8', - omega: '\u03C9', - thetasym: '\u03D1', - upsih: '\u03D2', - piv: '\u03D6', - ensp: '\u2002', - emsp: '\u2003', - thinsp: '\u2009', - zwnj: '\u200C', - zwj: '\u200D', - lrm: '\u200E', - rlm: '\u200F', - ndash: '\u2013', - mdash: '\u2014', - lsquo: '\u2018', - rsquo: '\u2019', - sbquo: '\u201A', - ldquo: '\u201C', - rdquo: '\u201D', - bdquo: '\u201E', - dagger: '\u2020', - Dagger: '\u2021', - bull: '\u2022', - hellip: '\u2026', - permil: '\u2030', - prime: '\u2032', - Prime: '\u2033', - lsaquo: '\u2039', - rsaquo: '\u203A', - oline: '\u203E', - frasl: '\u2044', - euro: '\u20AC', - image: '\u2111', - weierp: '\u2118', - real: '\u211C', - trade: '\u2122', - alefsym: '\u2135', - larr: '\u2190', - uarr: '\u2191', - rarr: '\u2192', - darr: '\u2193', - harr: '\u2194', - crarr: '\u21B5', - lArr: '\u21D0', - uArr: '\u21D1', - rArr: '\u21D2', - dArr: '\u21D3', - hArr: '\u21D4', - forall: '\u2200', - part: '\u2202', - exist: '\u2203', - empty: '\u2205', - nabla: '\u2207', - isin: '\u2208', - notin: '\u2209', - ni: '\u220B', - prod: '\u220F', - sum: '\u2211', - minus: '\u2212', - lowast: '\u2217', - radic: '\u221A', - prop: '\u221D', - infin: '\u221E', - ang: '\u2220', - and: '\u2227', - or: '\u2228', - cap: '\u2229', - cup: '\u222A', - 'int': '\u222B', - there4: '\u2234', - sim: '\u223C', - cong: '\u2245', - asymp: '\u2248', - ne: '\u2260', - equiv: '\u2261', - le: '\u2264', - ge: '\u2265', - sub: '\u2282', - sup: '\u2283', - nsub: '\u2284', - sube: '\u2286', - supe: '\u2287', - oplus: '\u2295', - otimes: '\u2297', - perp: '\u22A5', - sdot: '\u22C5', - lceil: '\u2308', - rceil: '\u2309', - lfloor: '\u230A', - rfloor: '\u230B', - lang: '\u2329', - rang: '\u232A', - loz: '\u25CA', - spades: '\u2660', - clubs: '\u2663', - hearts: '\u2665', - diams: '\u2666' -}; diff --git a/tools/node_modules/eslint/node_modules/acorn/LICENSE b/tools/node_modules/eslint/node_modules/acorn/LICENSE deleted file mode 100644 index 2c0632b6a7c63b..00000000000000 --- a/tools/node_modules/eslint/node_modules/acorn/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (C) 2012-2018 by various contributors (see AUTHORS) - -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/node_modules/eslint/node_modules/acorn/README.md b/tools/node_modules/eslint/node_modules/acorn/README.md deleted file mode 100644 index 3e5f58d95dea95..00000000000000 --- a/tools/node_modules/eslint/node_modules/acorn/README.md +++ /dev/null @@ -1,269 +0,0 @@ -# Acorn - -A tiny, fast JavaScript parser written in JavaScript. - -## Community - -Acorn is open source software released under an -[MIT license](https://github.com/acornjs/acorn/blob/master/acorn/LICENSE). - -You are welcome to -[report bugs](https://github.com/acornjs/acorn/issues) or create pull -requests on [github](https://github.com/acornjs/acorn). For questions -and discussion, please use the -[Tern discussion forum](https://discuss.ternjs.net). - -## Installation - -The easiest way to install acorn is from [`npm`](https://www.npmjs.com/): - -```sh -npm install acorn -``` - -Alternately, you can download the source and build acorn yourself: - -```sh -git clone https://github.com/acornjs/acorn.git -cd acorn -npm install -``` - -## Interface - -**parse**`(input, options)` is the main interface to the library. The -`input` parameter is a string, `options` can be undefined or an object -setting some of the options listed below. The return value will be an -abstract syntax tree object as specified by the [ESTree -spec](https://github.com/estree/estree). - -```javascript -let acorn = require("acorn"); -console.log(acorn.parse("1 + 1")); -``` - -When encountering a syntax error, the parser will raise a -`SyntaxError` object with a meaningful message. The error object will -have a `pos` property that indicates the string offset at which the -error occurred, and a `loc` object that contains a `{line, column}` -object referring to that same position. - -Options can be provided by passing a second argument, which should be -an object containing any of these fields: - -- **ecmaVersion**: Indicates the ECMAScript version to parse. Must be - either 3, 5, 6 (2015), 7 (2016), 8 (2017), 9 (2018) or 10 (2019, partial - support). This influences support for strict mode, the set of - reserved words, and support for new syntax features. Default is 7. - - **NOTE**: Only 'stage 4' (finalized) ECMAScript features are being - implemented by Acorn. Other proposed new features can be implemented - through plugins. - -- **sourceType**: Indicate 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. - -- **onInsertedSemicolon**: If given a callback, that callback will be - called whenever a missing semicolon is inserted by the parser. The - callback will be given the character offset of the point where the - semicolon is inserted as argument, and if `locations` is on, also a - `{line, column}` object representing this position. - -- **onTrailingComma**: Like `onInsertedSemicolon`, but for trailing - commas. - -- **allowReserved**: If `false`, using a reserved word will generate - an error. Defaults to `true` for `ecmaVersion` 3, `false` for higher - versions. When given the value `"never"`, reserved words and - keywords can also not be used as property names (as in Internet - Explorer's old parser). - -- **allowReturnOutsideFunction**: By default, a return statement at - the top level raises an error. Set this to `true` to accept such - code. - -- **allowImportExportEverywhere**: By default, `import` and `export` - declarations can only appear at a program's top level. Setting this - option to `true` allows them anywhere where a statement is allowed. - -- **allowAwaitOutsideFunction**: By default, `await` expressions can - only appear inside `async` functions. Setting this option to - `true` allows to have top-level `await` expressions. They are - still not allowed in non-`async` functions, though. - -- **allowHashBang**: When this is enabled (off by default), if the - code starts with the characters `#!` (as in a shellscript), the - first line will be treated as a comment. - -- **locations**: When `true`, each node has a `loc` object attached - with `start` and `end` subobjects, each of which contains the - one-based line and zero-based column numbers in `{line, column}` - form. Default is `false`. - -- **onToken**: If a function is passed for this option, each found - token will be passed in same format as tokens returned from - `tokenizer().getToken()`. - - If array is passed, each found token is pushed to it. - - Note that you are not allowed to call the parser from the - callback—that will corrupt its internal state. - -- **onComment**: If a function is passed for this option, whenever a - comment is encountered the function will be called with the - following parameters: - - - `block`: `true` if the comment is a block comment, false if it - is a line comment. - - `text`: The content of the comment. - - `start`: Character offset of the start of the comment. - - `end`: Character offset of the end of the comment. - - When the `locations` options is on, the `{line, column}` locations - of the comment’s start and end are passed as two additional - parameters. - - If array is passed for this option, each found comment is pushed - to it as object in Esprima format: - - ```javascript - { - "type": "Line" | "Block", - "value": "comment text", - "start": Number, - "end": Number, - // If `locations` option is on: - "loc": { - "start": {line: Number, column: Number} - "end": {line: Number, column: Number} - }, - // If `ranges` option is on: - "range": [Number, Number] - } - ``` - - Note that you are not allowed to call the parser from the - callback—that will corrupt its internal state. - -- **ranges**: 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](https://bugzilla.mozilla.org/show_bug.cgi?id=745678) - `range` property holding a `[start, end]` array with the same - numbers, set the `ranges` option to `true`. - -- **program**: It is possible to parse multiple files into a single - AST by passing the tree produced by parsing the first file as the - `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. - -- **sourceFile**: When the `locations` option is `true`, you can pass - this option to add a `source` attribute in every node’s `loc` - object. Note that the contents of this option are not examined or - processed in any way; you are free to use whatever format you - choose. - -- **directSourceFile**: Like `sourceFile`, but a `sourceFile` property - will be added (regardless of the `location` option) directly to the - nodes, rather than the `loc` object. - -- **preserveParens**: If this option is `true`, parenthesized expressions - are represented by (non-standard) `ParenthesizedExpression` nodes - that have a single `expression` property containing the expression - inside parentheses. - -**parseExpressionAt**`(input, offset, options)` will parse a single -expression in a string, and return its AST. It will not complain if -there is more of the string left after the expression. - -**tokenizer**`(input, options)` returns an object with a `getToken` -method that can be called repeatedly to get the next token, a `{start, -end, type, value}` object (with added `loc` property when the -`locations` option is enabled and `range` property when the `ranges` -option is enabled). When the token's type is `tokTypes.eof`, you -should stop calling the method, since it will keep returning that same -token forever. - -In ES6 environment, returned result can be used as any other -protocol-compliant iterable: - -```javascript -for (let token of acorn.tokenizer(str)) { - // iterate over the tokens -} - -// transform code to array of tokens: -var tokens = [...acorn.tokenizer(str)]; -``` - -**tokTypes** holds an object mapping names to the token type objects -that end up in the `type` properties of tokens. - -**getLineInfo**`(input, offset)` can be used to get a `{line, -column}` object for a given program string and offset. - -### The `Parser` class - -Instances of the **`Parser`** class contain all the state and logic -that drives a parse. It has static methods `parse`, -`parseExpressionAt`, and `tokenizer` that match the top-level -functions by the same name. - -When extending the parser with plugins, you need to call these methods -on the extended version of the class. To extend a parser with plugins, -you can use its static `extend` method. - -```javascript -var acorn = require("acorn"); -var jsx = require("acorn-jsx"); -var JSXParser = acorn.Parser.extend(jsx()); -JSXParser.parse("foo()"); -``` - -The `extend` method takes any number of plugin values, and returns a -new `Parser` class that includes the extra parser logic provided by -the plugins. - -## Command line interface - -The `bin/acorn` utility can be used to parse a file from the command -line. It accepts as arguments its input file and the following -options: - -- `--ecma3|--ecma5|--ecma6|--ecma7|--ecma8|--ecma9|--ecma10`: Sets the ECMAScript version - to parse. Default is version 9. - -- `--module`: Sets the parsing mode to `"module"`. Is set to `"script"` otherwise. - -- `--locations`: Attaches a "loc" object to each node with "start" and - "end" subobjects, each of which contains the one-based line and - zero-based column numbers in `{line, column}` form. - -- `--allow-hash-bang`: If the code starts with the characters #! (as - in a shellscript), the first line will be treated as a comment. - -- `--compact`: No whitespace is used in the AST output. - -- `--silent`: Do not output the AST, just return the exit status. - -- `--help`: Print the usage information and quit. - -The utility spits out the syntax tree as JSON data. - -## Existing plugins - - - [`acorn-jsx`](https://github.com/RReverser/acorn-jsx): Parse [Facebook JSX syntax extensions](https://github.com/facebook/jsx) - -Plugins for ECMAScript proposals: - - - [`acorn-stage3`](https://github.com/acornjs/acorn-stage3): Parse most stage 3 proposals, bundling: - - [`acorn-async-iteration`](https://github.com/acornjs/acorn-async-iteration): Parse [async iteration proposal](https://github.com/tc39/proposal-async-iteration) - - [`acorn-bigint`](https://github.com/acornjs/acorn-bigint): Parse [BigInt proposal](https://github.com/tc39/proposal-bigint) - - [`acorn-class-fields`](https://github.com/acornjs/acorn-class-fields): Parse [class fields proposal](https://github.com/tc39/proposal-class-fields) - - [`acorn-dynamic-import`](https://github.com/kesne/acorn-dynamic-import): Parse [import() proposal](https://github.com/tc39/proposal-dynamic-import) - - [`acorn-import-meta`](https://github.com/acornjs/acorn-import-meta): Parse [import.meta proposal](https://github.com/tc39/proposal-import-meta) - - [`acorn-numeric-separator`](https://github.com/acornjs/acorn-numeric-separator): Parse [numeric separator proposal](https://github.com/tc39/proposal-numeric-separator) - - [`acorn-private-methods`](https://github.com/acornjs/acorn-private-methods): parse [private methods, getters and setters proposal](https://github.com/tc39/proposal-private-methods)n diff --git a/tools/node_modules/eslint/node_modules/acorn/bin/acorn b/tools/node_modules/eslint/node_modules/acorn/bin/acorn deleted file mode 100755 index cf7df46890fdd4..00000000000000 --- a/tools/node_modules/eslint/node_modules/acorn/bin/acorn +++ /dev/null @@ -1,4 +0,0 @@ -#!/usr/bin/env node -'use strict'; - -require('../dist/bin.js'); diff --git a/tools/node_modules/eslint/node_modules/acorn/dist/acorn.d.ts b/tools/node_modules/eslint/node_modules/acorn/dist/acorn.d.ts deleted file mode 100644 index c6f9841b809a48..00000000000000 --- a/tools/node_modules/eslint/node_modules/acorn/dist/acorn.d.ts +++ /dev/null @@ -1,209 +0,0 @@ -export as namespace acorn -export = acorn - -declare namespace acorn { - function parse(input: string, options?: Options): Node - - function parseExpressionAt(input: string, pos?: number, options?: Options): Node - - function tokenizer(input: string, options?: Options): { - getToken(): Token - [Symbol.iterator](): Iterator - } - - interface Options { - ecmaVersion?: 3 | 5 | 6 | 7 | 8 | 9 | 10 | 2015 | 2016 | 2017 | 2018 | 2019 - sourceType?: 'script' | 'module' - onInsertedSemicolon?: (lastTokEnd: number, lastTokEndLoc?: Position) => void - onTrailingComma?: (lastTokEnd: number, lastTokEndLoc?: Position) => void - allowReserved?: boolean - allowReturnOutsideFunction?: boolean - allowImportExportEverywhere?: boolean - allowAwaitOutsideFunction?: boolean - allowHashBang?: boolean - locations?: boolean - onToken?: ((token: Token) => any) | Token[] - onComment?: (( - isBlock: boolean, text: string, start: number, end: number, startLoc?: Position, - endLoc?: Position - ) => void) | Comment[] - ranges?: boolean - program?: Node - sourceFile?: string - directSourceFile?: string - preserveParens?: boolean - } - - class Parser { - constructor(options: Options, input: string, startPos?: number) - parse(): Node - static parse(input: string, options?: Options): Node - static parseExpressionAt(input: string, pos: number, options?: Options): Node - static tokenizer(input: string, options?: Options): { - getToken(): Token - [Symbol.iterator](): Iterator - } - static extend(...plugins: ((BaseParser: typeof Parser) => typeof Parser)[]): typeof Parser - } - - interface Position { line: number; column: number; offset: number } - - const defaultOptions: Options - - function getLineInfo(input: string, offset: number): Position - - class SourceLocation { - start: Position - end: Position - source?: string | null - constructor(p: Parser, start: Position, end: Position) - } - - class Node { - type: string - start: number - end: number - loc?: SourceLocation - sourceFile?: string - range?: [number, number] - constructor(parser: Parser, pos: number, loc?: SourceLocation) - } - - class TokenType { - label: string - keyword: string - beforeExpr: boolean - startsExpr: boolean - isLoop: boolean - isAssign: boolean - prefix: boolean - postfix: boolean - binop: number - updateContext?: (prevType: TokenType) => void - constructor(label: string, conf?: any) - } - - const tokTypes: { - num: TokenType - regexp: TokenType - string: TokenType - name: TokenType - eof: TokenType - bracketL: TokenType - bracketR: TokenType - braceL: TokenType - braceR: TokenType - parenL: TokenType - parenR: TokenType - comma: TokenType - semi: TokenType - colon: TokenType - dot: TokenType - question: TokenType - arrow: TokenType - template: TokenType - ellipsis: TokenType - backQuote: TokenType - dollarBraceL: TokenType - eq: TokenType - assign: TokenType - incDec: TokenType - prefix: TokenType - logicalOR: TokenType - logicalAND: TokenType - bitwiseOR: TokenType - bitwiseXOR: TokenType - bitwiseAND: TokenType - equality: TokenType - relational: TokenType - bitShift: TokenType - plusMin: TokenType - modulo: TokenType - star: TokenType - slash: TokenType - starstar: TokenType - _break: TokenType - _case: TokenType - _catch: TokenType - _continue: TokenType - _debugger: TokenType - _default: TokenType - _do: TokenType - _else: TokenType - _finally: TokenType - _for: TokenType - _function: TokenType - _if: TokenType - _return: TokenType - _switch: TokenType - _throw: TokenType - _try: TokenType - _var: TokenType - _const: TokenType - _while: TokenType - _with: TokenType - _new: TokenType - _this: TokenType - _super: TokenType - _class: TokenType - _extends: TokenType - _export: TokenType - _import: TokenType - _null: TokenType - _true: TokenType - _false: TokenType - _in: TokenType - _instanceof: TokenType - _typeof: TokenType - _void: TokenType - _delete: TokenType - } - - class TokContext { - constructor(token: string, isExpr: boolean, preserveSpace: boolean, override?: (p: Parser) => void) - } - - const tokContexts: { - b_stat: TokContext - b_expr: TokContext - b_tmpl: TokContext - p_stat: TokContext - p_expr: TokContext - q_tmpl: TokContext - f_expr: TokContext - } - - function isIdentifierStart(code: number, astral?: boolean): boolean - - function isIdentifierChar(code: number, astral?: boolean): boolean - - interface AbstractToken { - } - - interface Comment extends AbstractToken { - type: string - value: string - start: number - end: number - loc?: SourceLocation - range?: [number, number] - } - - class Token { - type: TokenType - value: any - start: number - end: number - loc?: SourceLocation - range?: [number, number] - constructor(p: Parser) - } - - function isNewLine(code: number): boolean - - const lineBreak: RegExp - - const lineBreakG: RegExp - - const version: string -} diff --git a/tools/node_modules/eslint/node_modules/acorn/dist/acorn.js b/tools/node_modules/eslint/node_modules/acorn/dist/acorn.js deleted file mode 100644 index 44d95c5fae74db..00000000000000 --- a/tools/node_modules/eslint/node_modules/acorn/dist/acorn.js +++ /dev/null @@ -1,5018 +0,0 @@ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : - typeof define === 'function' && define.amd ? define(['exports'], factory) : - (factory((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"; - -var keywords = { - 5: ecma5AndLessKeywords, - 6: ecma5AndLessKeywords + " const class extends export import super" -}; - -var keywordRelationalOperator = /^in(stanceof)?$/; - -// ## 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\u0560-\u0588\u05d0-\u05ea\u05ef-\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\u0860-\u086a\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\u09fc\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-\u1878\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\u1c90-\u1cba\u1cbd-\u1cbf\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-\u312f\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fef\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7b9\ua7f7-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\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\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\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\u09fe\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\u0afa-\u0aff\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-\u0c04\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\u0d00-\u0d03\u0d3b\u0d3c\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\u1cf7-\u1cf9\u1dc0-\u1df9\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\ua8ff-\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 - -// eslint-disable-next-line comma-spacing -var astralIdentifierStartCodes = [0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,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,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,477,28,11,0,9,21,190,52,76,44,33,24,27,35,30,0,12,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,26,230,43,117,63,32,0,257,0,11,39,8,0,22,0,12,39,3,3,20,0,35,56,264,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,270,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,689,63,129,68,12,0,67,12,65,1,31,6129,15,754,9486,286,82,395,2309,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,15,7472,3104,541]; - -// eslint-disable-next-line comma-spacing -var astralIdentifierCodes = [509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,525,10,176,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,4,9,83,11,7,0,161,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,243,14,166,9,280,9,41,6,2,3,9,0,10,10,47,15,406,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,19306,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 keywords$1 = {}; - -// Succinct definitions of keyword token types -function kw(name, options) { - if ( options === void 0 ) options = {}; - - options.keyword = name; - return keywords$1[name] = new TokenType(name, options) -} - -var types = { - 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"), - invalidTemplate: new TokenType("invalidTemplate"), - 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("!/~", {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", startsExpr), - _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, ecma2019String) { - return code === 10 || code === 13 || (!ecma2019String && (code === 0x2028 || code === 0x2029)) -} - -var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/; - -var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; - -var ref = Object.prototype; -var hasOwnProperty = ref.hasOwnProperty; -var toString = ref.toString; - -// Checks if an object has a property. - -function has(obj, propName) { - return hasOwnProperty.call(obj, propName) -} - -var isArray = Array.isArray || (function (obj) { return ( - toString.call(obj) === "[object Array]" -); }); - -function wordsRegexp(words) { - return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$") -} - -// 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), 8 (2017), 9 (2018), or 10 - // (2019). This influences support for strict mode, the set of - // reserved words, and support for new syntax features. The default - // is 9. - ecmaVersion: 9, - // `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 - // the 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, await identifiers are allowed to appear at the top-level scope, - // but they are still not allowed in non-async functions. - allowAwaitOutsideFunction: 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 -}; - -// 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); - } -} - -// Each scope gets a bitset that may contain these flags -var SCOPE_TOP = 1; -var SCOPE_FUNCTION = 2; -var SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION; -var SCOPE_ASYNC = 4; -var SCOPE_GENERATOR = 8; -var SCOPE_ARROW = 16; -var SCOPE_SIMPLE_CATCH = 32; -var SCOPE_SUPER = 64; -var SCOPE_DIRECT_SUPER = 128; - -function functionFlags(async, generator) { - return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0) -} - -// Used in checkLVal and declareName to determine the type of a binding -var BIND_NONE = 0; -var BIND_VAR = 1; -var BIND_LEXICAL = 2; -var BIND_FUNCTION = 3; -var BIND_SIMPLE_CATCH = 4; -var BIND_OUTSIDE = 5; // Special case for function names as bound inside the function - -var Parser = function Parser(options, input, startPos) { - this.options = options = getOptions(options); - this.sourceFile = options.sourceFile; - this.keywords = wordsRegexp(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 = wordsRegexp(reserved); - var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict; - this.reservedWordsStrict = wordsRegexp(reservedStrict); - this.reservedWordsStrictBind = wordsRegexp(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; - - // 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 = types.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.inModule = options.sourceType === "module"; - this.strict = this.inModule || this.strictDirective(this.pos); - - // Used to signify the start of a potential arrow function - this.potentialArrowAt = -1; - - // Positions to delayed-check that yield/await does not exist in default parameters. - this.yieldPos = this.awaitPos = this.awaitIdentPos = 0; - // Labels in scope. - this.labels = []; - // Thus-far undefined exports. - this.undefinedExports = {}; - - // If enabled, skip leading hashbang line. - if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!") - { this.skipLineComment(2); } - - // Scope tracking for duplicate variable names (see scope.js) - this.scopeStack = []; - this.enterScope(SCOPE_TOP); - - // For RegExp validation - this.regexpState = null; -}; - -var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true } }; - -Parser.prototype.parse = function parse () { - var node = this.options.program || this.startNode(); - this.nextToken(); - return this.parseTopLevel(node) -}; - -prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 }; -prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 }; -prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 }; -prototypeAccessors.allowSuper.get = function () { return (this.currentThisScope().flags & SCOPE_SUPER) > 0 }; -prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 }; -prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) }; - -// Switch to a getter for 7.0.0. -Parser.prototype.inNonArrowFunction = function inNonArrowFunction () { return (this.currentThisScope().flags & SCOPE_FUNCTION) > 0 }; - -Parser.extend = function extend () { - var plugins = [], len = arguments.length; - while ( len-- ) plugins[ len ] = arguments[ len ]; - - var cls = this; - for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); } - return cls -}; - -Parser.parse = function parse (input, options) { - return new this(options, input).parse() -}; - -Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) { - var parser = new this(options, input, pos); - parser.nextToken(); - return parser.parseExpression() -}; - -Parser.tokenizer = function tokenizer (input, options) { - return new this(options, input) -}; - -Object.defineProperties( Parser.prototype, prototypeAccessors ); - -var pp = Parser.prototype; - -// ## Parser utilities - -var literal = /^(?:'((?:\\.|[^'])*?)'|"((?:\\.|[^"])*?)")/; -pp.strictDirective = function(start) { - var this$1 = this; - - for (;;) { - // Try to find string literal. - skipWhiteSpace.lastIndex = start; - start += skipWhiteSpace.exec(this$1.input)[0].length; - var match = literal.exec(this$1.input.slice(start)); - if (!match) { return false } - if ((match[1] || match[2]) === "use strict") { return true } - start += match[0].length; - - // Skip semicolon, if any. - skipWhiteSpace.lastIndex = start; - start += skipWhiteSpace.exec(this$1.input)[0].length; - if (this$1.input[start] === ";") - { start++; } - } -}; - -// 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) { - this.next(); - return true - } else { - return false - } -}; - -// Tests whether parsed token is a contextual keyword. - -pp.isContextual = function(name) { - return this.type === types.name && this.value === name && !this.containsEsc -}; - -// Consumes contextual keyword if possible. - -pp.eatContextual = function(name) { - if (!this.isContextual(name)) { return false } - this.next(); - return true -}; - -// Asserts that following token is given contextual keyword. - -pp.expectContextual = function(name) { - if (!this.eatContextual(name)) { this.unexpected(); } -}; - -// Test whether a semicolon can be inserted at the current position. - -pp.canInsertSemicolon = function() { - return this.type === types.eof || - this.type === types.braceR || - lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) -}; - -pp.insertSemicolon = function() { - if (this.canInsertSemicolon()) { - if (this.options.onInsertedSemicolon) - { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); } - return true - } -}; - -// 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(types.semi) && !this.insertSemicolon()) { this.unexpected(); } -}; - -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 - } -}; - -// 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(); -}; - -// Raise an unexpected token error. - -pp.unexpected = function(pos) { - this.raise(pos != null ? pos : this.start, "Unexpected token"); -}; - -function DestructuringErrors() { - this.shorthandAssign = - this.trailingComma = - this.parenthesizedAssign = - this.parenthesizedBind = - this.doubleProto = - -1; -} - -pp.checkPatternErrors = function(refDestructuringErrors, isAssign) { - if (!refDestructuringErrors) { return } - if (refDestructuringErrors.trailingComma > -1) - { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); } - var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind; - if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern"); } -}; - -pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) { - if (!refDestructuringErrors) { return false } - var shorthandAssign = refDestructuringErrors.shorthandAssign; - var doubleProto = refDestructuringErrors.doubleProto; - if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 } - if (shorthandAssign >= 0) - { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); } - if (doubleProto >= 0) - { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); } -}; - -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"); } -}; - -pp.isSimpleAssignTarget = function(expr) { - if (expr.type === "ParenthesizedExpression") - { return this.isSimpleAssignTarget(expr.expression) } - return expr.type === "Identifier" || expr.type === "MemberExpression" -}; - -var pp$1 = Parser.prototype; - -// ### Statement parsing - -// 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. - -pp$1.parseTopLevel = function(node) { - var this$1 = this; - - var exports = {}; - if (!node.body) { node.body = []; } - while (this.type !== types.eof) { - var stmt = this$1.parseStatement(null, true, exports); - node.body.push(stmt); - } - if (this.inModule) - { for (var i = 0, list = Object.keys(this$1.undefinedExports); i < list.length; i += 1) - { - var name = list[i]; - - this$1.raiseRecoverable(this$1.undefinedExports[name].start, ("Export '" + name + "' is not defined")); - } } - this.adaptDirectivePrologue(node.body); - 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(context) { - if (this.options.ecmaVersion < 6 || !this.isContextual("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); - // For ambiguous cases, determine if a LexicalDeclaration (or only a - // Statement) is allowed here. If context is not empty then only a Statement - // is allowed. However, `let [` is an explicit negative lookahead for - // ExpressionStatement, so special-case it first. - if (nextCh === 91) { return true } // '[' - if (context) { return false } - - if (nextCh === 123) { return true } // '{' - if (isIdentifierStart(nextCh, true)) { - var pos = next + 1; - while (isIdentifierChar(this.input.charCodeAt(pos), true)) { ++pos; } - var ident = this.input.slice(next, pos); - if (!keywordRelationalOperator.test(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.options.ecmaVersion < 8 || !this.isContextual("async")) - { return false } - - 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(context, topLevel, exports) { - var starttype = this.type, node = this.startNode(), kind; - - if (this.isLet(context)) { - starttype = types._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 types._break: case types._continue: return this.parseBreakContinueStatement(node, starttype.keyword) - case types._debugger: return this.parseDebuggerStatement(node) - case types._do: return this.parseDoStatement(node) - case types._for: return this.parseForStatement(node) - case types._function: - // Function as sole body of either an if statement or a labeled statement - // works, but not when it is part of a labeled statement that is the sole - // body of an if statement. - if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); } - return this.parseFunctionStatement(node, false, !context) - case types._class: - if (context) { this.unexpected(); } - return this.parseClass(node, true) - case types._if: return this.parseIfStatement(node) - case types._return: return this.parseReturnStatement(node) - case types._switch: return this.parseSwitchStatement(node) - case types._throw: return this.parseThrowStatement(node) - case types._try: return this.parseTryStatement(node) - case types._const: case types._var: - kind = kind || this.value; - if (context && kind !== "var") { this.unexpected(); } - return this.parseVarStatement(node, kind) - case types._while: return this.parseWhileStatement(node) - case types._with: return this.parseWithStatement(node) - case types.braceL: return this.parseBlock(true, node) - case types.semi: return this.parseEmptyStatement(node) - case types._export: - case types._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 === types._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()) { - if (context) { this.unexpected(); } - this.next(); - return this.parseFunctionStatement(node, true, !context) - } - - var maybeName = this.value, expr = this.parseExpression(); - if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon)) - { return this.parseLabeledStatement(node, maybeName, expr, context) } - else { return this.parseExpressionStatement(node, expr) } - } -}; - -pp$1.parseBreakContinueStatement = function(node, keyword) { - var this$1 = this; - - var isBreak = keyword === "break"; - this.next(); - if (this.eat(types.semi) || this.insertSemicolon()) { node.label = null; } - else if (this.type !== types.name) { this.unexpected(); } - else { - node.label = this.parseIdent(); - this.semicolon(); - } - - // Verify that there is an actual destination to break or - // continue to. - var i = 0; - for (; 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("do"); - this.labels.pop(); - this.expect(types._while); - node.test = this.parseParenExpression(); - if (this.options.ecmaVersion >= 6) - { this.eat(types.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(); - var awaitAt = (this.options.ecmaVersion >= 9 && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction)) && this.eatContextual("await")) ? this.lastTokStart : -1; - this.labels.push(loopLabel); - this.enterScope(0); - this.expect(types.parenL); - if (this.type === types.semi) { - if (awaitAt > -1) { this.unexpected(awaitAt); } - return this.parseFor(node, null) - } - var isLet = this.isLet(); - if (this.type === types._var || this.type === types._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 === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1 && - !(kind !== "var" && init$1.declarations[0].init)) { - if (this.options.ecmaVersion >= 9) { - if (this.type === types._in) { - if (awaitAt > -1) { this.unexpected(awaitAt); } - } else { node.await = awaitAt > -1; } - } - return this.parseForIn(node, init$1) - } - if (awaitAt > -1) { this.unexpected(awaitAt); } - return this.parseFor(node, init$1) - } - var refDestructuringErrors = new DestructuringErrors; - var init = this.parseExpression(true, refDestructuringErrors); - if (this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) { - if (this.options.ecmaVersion >= 9) { - if (this.type === types._in) { - if (awaitAt > -1) { this.unexpected(awaitAt); } - } else { node.await = awaitAt > -1; } - } - this.toAssignable(init, false, refDestructuringErrors); - this.checkLVal(init); - return this.parseForIn(node, init) - } else { - this.checkExpressionErrors(refDestructuringErrors, true); - } - if (awaitAt > -1) { this.unexpected(awaitAt); } - return this.parseFor(node, init) -}; - -pp$1.parseFunctionStatement = function(node, isAsync, declarationPosition) { - this.next(); - return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync) -}; - -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("if"); - node.alternate = this.eat(types._else) ? this.parseStatement("if") : 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(types.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(types.braceL); - this.labels.push(switchLabel); - this.enterScope(0); - - // Statements under must be grouped (by label) in SwitchCase - // nodes. `cur` is used to keep the node that we are currently - // adding statements to. - - var cur; - for (var sawDefault = false; this.type !== types.braceR;) { - if (this$1.type === types._case || this$1.type === types._default) { - var isCase = this$1.type === types._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(types.colon); - } else { - if (!cur) { this$1.unexpected(); } - cur.consequent.push(this$1.parseStatement(null)); - } - } - this.exitScope(); - 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 === types._catch) { - var clause = this.startNode(); - this.next(); - if (this.eat(types.parenL)) { - clause.param = this.parseBindingAtom(); - var simple = clause.param.type === "Identifier"; - this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0); - this.checkLVal(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL); - this.expect(types.parenR); - } else { - if (this.options.ecmaVersion < 10) { this.unexpected(); } - clause.param = null; - this.enterScope(0); - } - clause.body = this.parseBlock(false); - this.exitScope(); - node.handler = this.finishNode(clause, "CatchClause"); - } - node.finalizer = this.eat(types._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("while"); - 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("with"); - return this.finishNode(node, "WithStatement") -}; - -pp$1.parseEmptyStatement = function(node) { - this.next(); - return this.finishNode(node, "EmptyStatement") -}; - -pp$1.parseLabeledStatement = function(node, maybeName, expr, context) { - var this$1 = this; - - for (var i$1 = 0, list = this$1.labels; i$1 < list.length; i$1 += 1) - { - var label = list[i$1]; - - if (label.name === maybeName) - { this$1.raise(expr.start, "Label '" + maybeName + "' is already declared"); - } } - var kind = this.type.isLoop ? "loop" : this.type === types._switch ? "switch" : null; - for (var i = this.labels.length - 1; i >= 0; i--) { - var label$1 = this$1.labels[i]; - if (label$1.statementStart === node.start) { - // Update information about previous labels on this node - label$1.statementStart = this$1.start; - label$1.kind = kind; - } else { break } - } - this.labels.push({name: maybeName, kind: kind, statementStart: this.start}); - node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label"); - 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(createNewLexicalScope, node) { - var this$1 = this; - if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true; - if ( node === void 0 ) node = this.startNode(); - - node.body = []; - this.expect(types.braceL); - if (createNewLexicalScope) { this.enterScope(0); } - while (!this.eat(types.braceR)) { - var stmt = this$1.parseStatement(null); - node.body.push(stmt); - } - if (createNewLexicalScope) { this.exitScope(); } - 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(types.semi); - node.test = this.type === types.semi ? null : this.parseExpression(); - this.expect(types.semi); - node.update = this.type === types.parenR ? null : this.parseExpression(); - this.expect(types.parenR); - node.body = this.parseStatement("for"); - this.exitScope(); - 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 === types._in ? "ForInStatement" : "ForOfStatement"; - this.next(); - if (type === "ForInStatement") { - if (init.type === "AssignmentPattern" || - (init.type === "VariableDeclaration" && init.declarations[0].init != null && - (this.strict || init.declarations[0].id.type !== "Identifier"))) - { this.raise(init.start, "Invalid assignment in for-in loop head"); } - } - node.left = init; - node.right = type === "ForInStatement" ? this.parseExpression() : this.parseMaybeAssign(); - this.expect(types.parenR); - node.body = this.parseStatement("for"); - this.exitScope(); - 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, kind); - if (this$1.eat(types.eq)) { - decl.init = this$1.parseMaybeAssign(isFor); - } else if (kind === "const" && !(this$1.type === types._in || (this$1.options.ecmaVersion >= 6 && this$1.isContextual("of")))) { - this$1.unexpected(); - } else if (decl.id.type !== "Identifier" && !(isFor && (this$1.type === types._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(types.comma)) { break } - } - return node -}; - -pp$1.parseVarId = function(decl, kind) { - if ((kind === "const" || kind === "let") && this.isContextual("let")) { - this.raiseRecoverable(this.start, "let is disallowed as a lexically bound name"); - } - decl.id = this.parseBindingAtom(); - this.checkLVal(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false); -}; - -var FUNC_STATEMENT = 1; -var FUNC_HANGING_STATEMENT = 2; -var FUNC_NULLABLE_ID = 4; - -// Parse a function declaration or literal (depending on the -// `statement & FUNC_STATEMENT`). - -// Remove `allowExpressionBody` for 7.0.0, as it is only called with false -pp$1.parseFunction = function(node, statement, allowExpressionBody, isAsync) { - this.initFunction(node); - if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) { - if (this.type === types.star && (statement & FUNC_HANGING_STATEMENT)) - { this.unexpected(); } - node.generator = this.eat(types.star); - } - if (this.options.ecmaVersion >= 8) - { node.async = !!isAsync; } - - if (statement & FUNC_STATEMENT) { - node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types.name ? null : this.parseIdent(); - if (node.id && !(statement & FUNC_HANGING_STATEMENT)) - // If it is a regular function declaration in sloppy mode, then it is - // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding - // mode depends on properties of the current scope (see - // treatFunctionsAsVar). - { this.checkLVal(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); } - } - - var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; - this.yieldPos = 0; - this.awaitPos = 0; - this.awaitIdentPos = 0; - this.enterScope(functionFlags(node.async, node.generator)); - - if (!(statement & FUNC_STATEMENT)) - { node.id = this.type === types.name ? this.parseIdent() : null; } - - this.parseFunctionParams(node); - this.parseFunctionBody(node, allowExpressionBody, false); - - this.yieldPos = oldYieldPos; - this.awaitPos = oldAwaitPos; - this.awaitIdentPos = oldAwaitIdentPos; - return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression") -}; - -pp$1.parseFunctionParams = function(node) { - this.expect(types.parenL); - node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8); - 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(); - - // ecma-262 14.6 Class Definitions - // A class definition is always strict mode code. - var oldStrict = this.strict; - this.strict = true; - - this.parseClassId(node, isStatement); - this.parseClassSuper(node); - var classBody = this.startNode(); - var hadConstructor = false; - classBody.body = []; - this.expect(types.braceL); - while (!this.eat(types.braceR)) { - var element = this$1.parseClassElement(node.superClass !== null); - if (element) { - classBody.body.push(element); - if (element.type === "MethodDefinition" && element.kind === "constructor") { - if (hadConstructor) { this$1.raise(element.start, "Duplicate constructor in the same class"); } - hadConstructor = true; - } - } - } - node.body = this.finishNode(classBody, "ClassBody"); - this.strict = oldStrict; - return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression") -}; - -pp$1.parseClassElement = function(constructorAllowsSuper) { - var this$1 = this; - - if (this.eat(types.semi)) { return null } - - var method = this.startNode(); - var tryContextual = function (k, noLineBreak) { - if ( noLineBreak === void 0 ) noLineBreak = false; - - var start = this$1.start, startLoc = this$1.startLoc; - if (!this$1.eatContextual(k)) { return false } - if (this$1.type !== types.parenL && (!noLineBreak || !this$1.canInsertSemicolon())) { return true } - if (method.key) { this$1.unexpected(); } - method.computed = false; - method.key = this$1.startNodeAt(start, startLoc); - method.key.name = k; - this$1.finishNode(method.key, "Identifier"); - return false - }; - - method.kind = "method"; - method.static = tryContextual("static"); - var isGenerator = this.eat(types.star); - var isAsync = false; - if (!isGenerator) { - if (this.options.ecmaVersion >= 8 && tryContextual("async", true)) { - isAsync = true; - isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star); - } else if (tryContextual("get")) { - method.kind = "get"; - } else if (tryContextual("set")) { - method.kind = "set"; - } - } - if (!method.key) { this.parsePropertyName(method); } - var key = method.key; - var allowsDirectSuper = false; - if (!method.computed && !method.static && (key.type === "Identifier" && key.name === "constructor" || - key.type === "Literal" && key.value === "constructor")) { - if (method.kind !== "method") { this.raise(key.start, "Constructor can't have get/set modifier"); } - if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); } - if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); } - method.kind = "constructor"; - allowsDirectSuper = constructorAllowsSuper; - } else if (method.static && key.type === "Identifier" && key.name === "prototype") { - this.raise(key.start, "Classes may not have a static property named prototype"); - } - this.parseClassMethod(method, isGenerator, isAsync, allowsDirectSuper); - if (method.kind === "get" && method.value.params.length !== 0) - { this.raiseRecoverable(method.value.start, "getter should have no params"); } - if (method.kind === "set" && method.value.params.length !== 1) - { this.raiseRecoverable(method.value.start, "setter should have exactly one param"); } - if (method.kind === "set" && method.value.params[0].type === "RestElement") - { this.raiseRecoverable(method.value.params[0].start, "Setter cannot use rest params"); } - return method -}; - -pp$1.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) { - method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper); - return this.finishNode(method, "MethodDefinition") -}; - -pp$1.parseClassId = function(node, isStatement) { - if (this.type === types.name) { - node.id = this.parseIdent(); - if (isStatement === true) - { this.checkLVal(node.id, BIND_LEXICAL, false); } - } else { - if (isStatement === true) - { this.unexpected(); } - node.id = null; - } -}; - -pp$1.parseClassSuper = function(node) { - node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null; -}; - -// Parses module export declaration. - -pp$1.parseExport = function(node, exports) { - var this$1 = this; - - this.next(); - // export * from '...' - if (this.eat(types.star)) { - this.expectContextual("from"); - if (this.type !== types.string) { this.unexpected(); } - node.source = this.parseExprAtom(); - this.semicolon(); - return this.finishNode(node, "ExportAllDeclaration") - } - if (this.eat(types._default)) { // export default ... - this.checkExport(exports, "default", this.lastTokStart); - var isAsync; - if (this.type === types._function || (isAsync = this.isAsyncFunction())) { - var fNode = this.startNode(); - this.next(); - if (isAsync) { this.next(); } - node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync); - } else if (this.type === types._class) { - var cNode = this.startNode(); - node.declaration = this.parseClass(cNode, "nullableID"); - } else { - node.declaration = this.parseMaybeAssign(); - this.semicolon(); - } - return this.finishNode(node, "ExportDefaultDeclaration") - } - // export var|const|let|function|class ... - if (this.shouldParseExportStatement()) { - node.declaration = this.parseStatement(null); - 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")) { - if (this.type !== types.string) { this.unexpected(); } - node.source = this.parseExprAtom(); - } else { - for (var i = 0, list = node.specifiers; i < list.length; i += 1) { - // check for keywords used as local names - var spec = list[i]; - - this$1.checkUnreserved(spec.local); - // check if export is defined - this$1.checkLocalExport(spec.local); - } - - node.source = null; - } - this.semicolon(); - } - return this.finishNode(node, "ExportNamedDeclaration") -}; - -pp$1.checkExport = function(exports, name, pos) { - if (!exports) { return } - if (has(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, list = pat.properties; i < list.length; i += 1) - { - var prop = list[i]; - - this$1.checkPatternExport(exports, prop); - } } - else if (type === "ArrayPattern") - { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) { - var elt = list$1[i$1]; - - if (elt) { this$1.checkPatternExport(exports, elt); } - } } - else if (type === "Property") - { this.checkPatternExport(exports, pat.value); } - else if (type === "AssignmentPattern") - { this.checkPatternExport(exports, pat.left); } - else if (type === "RestElement") - { this.checkPatternExport(exports, pat.argument); } - 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, list = decls; i < list.length; i += 1) - { - var decl = list[i]; - - this$1.checkPatternExport(exports, decl.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(types.braceL); - while (!this.eat(types.braceR)) { - if (!first) { - this$1.expect(types.comma); - if (this$1.afterTrailingComma(types.braceR)) { break } - } else { first = false; } - - var node = this$1.startNode(); - node.local = this$1.parseIdent(true); - 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 === types.string) { - node.specifiers = empty; - node.source = this.parseExprAtom(); - } else { - node.specifiers = this.parseImportSpecifiers(); - this.expectContextual("from"); - node.source = this.type === types.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 === types.name) { - // import defaultObj, { x, y as z } from '...' - var node = this.startNode(); - node.local = this.parseIdent(); - this.checkLVal(node.local, BIND_LEXICAL); - nodes.push(this.finishNode(node, "ImportDefaultSpecifier")); - if (!this.eat(types.comma)) { return nodes } - } - if (this.type === types.star) { - var node$1 = this.startNode(); - this.next(); - this.expectContextual("as"); - node$1.local = this.parseIdent(); - this.checkLVal(node$1.local, BIND_LEXICAL); - nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier")); - return nodes - } - this.expect(types.braceL); - while (!this.eat(types.braceR)) { - if (!first) { - this$1.expect(types.comma); - if (this$1.afterTrailingComma(types.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 { - this$1.checkUnreserved(node$2.imported); - node$2.local = node$2.imported; - } - this$1.checkLVal(node$2.local, BIND_LEXICAL); - nodes.push(this$1.finishNode(node$2, "ImportSpecifier")); - } - return nodes -}; - -// Set `ExpressionStatement#directive` property for directive prologues. -pp$1.adaptDirectivePrologue = function(statements) { - for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) { - statements[i].directive = statements[i].expression.raw.slice(1, -1); - } -}; -pp$1.isDirectiveCandidate = function(statement) { - return ( - statement.type === "ExpressionStatement" && - statement.expression.type === "Literal" && - typeof statement.expression.value === "string" && - // Reject parenthesized strings. - (this.input[statement.start] === "\"" || this.input[statement.start] === "'") - ) -}; - -var pp$2 = Parser.prototype; - -// Convert existing expression atom to assignable pattern -// if possible. - -pp$2.toAssignable = function(node, isBinding, refDestructuringErrors) { - 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, "Cannot use 'await' as identifier inside an async function"); } - break - - case "ObjectPattern": - case "ArrayPattern": - case "RestElement": - break - - case "ObjectExpression": - node.type = "ObjectPattern"; - if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } - for (var i = 0, list = node.properties; i < list.length; i += 1) { - var prop = list[i]; - - this$1.toAssignable(prop, isBinding); - // Early error: - // AssignmentRestProperty[Yield, Await] : - // `...` DestructuringAssignmentTarget[Yield, Await] - // - // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|. - if ( - prop.type === "RestElement" && - (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern") - ) { - this$1.raise(prop.argument.start, "Unexpected token"); - } - } - break - - case "Property": - // AssignmentProperty has type === "Property" - if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); } - this.toAssignable(node.value, isBinding); - break - - case "ArrayExpression": - node.type = "ArrayPattern"; - if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } - this.toAssignableList(node.elements, isBinding); - break - - case "SpreadElement": - node.type = "RestElement"; - this.toAssignable(node.argument, isBinding); - if (node.argument.type === "AssignmentPattern") - { this.raise(node.argument.start, "Rest elements cannot have a default value"); } - break - - case "AssignmentExpression": - if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); } - node.type = "AssignmentPattern"; - delete node.operator; - this.toAssignable(node.left, isBinding); - // falls through to AssignmentPattern - - case "AssignmentPattern": - break - - case "ParenthesizedExpression": - this.toAssignable(node.expression, isBinding, refDestructuringErrors); - break - - case "MemberExpression": - if (!isBinding) { break } - - default: - this.raise(node.start, "Assigning to rvalue"); - } - } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } - return node -}; - -// Convert list of expression atoms to binding list. - -pp$2.toAssignableList = function(exprList, isBinding) { - var this$1 = this; - - var end = exprList.length; - for (var i = 0; i < end; i++) { - var elt = exprList[i]; - if (elt) { this$1.toAssignable(elt, isBinding); } - } - if (end) { - var last = exprList[end - 1]; - if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier") - { this.unexpected(last.argument.start); } - } - 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.parseRestBinding = function() { - var node = this.startNode(); - this.next(); - - // RestElement inside of a function parameter must be an identifier - if (this.options.ecmaVersion === 6 && this.type !== types.name) - { this.unexpected(); } - - node.argument = this.parseBindingAtom(); - - return this.finishNode(node, "RestElement") -}; - -// Parses lvalue (assignable) atom. - -pp$2.parseBindingAtom = function() { - if (this.options.ecmaVersion >= 6) { - switch (this.type) { - case types.bracketL: - var node = this.startNode(); - this.next(); - node.elements = this.parseBindingList(types.bracketR, true, true); - return this.finishNode(node, "ArrayPattern") - - case types.braceL: - return this.parseObj(true) - } - } - return this.parseIdent() -}; - -pp$2.parseBindingList = function(close, allowEmpty, allowTrailingComma) { - var this$1 = this; - - var elts = [], first = true; - while (!this.eat(close)) { - if (first) { first = false; } - else { this$1.expect(types.comma); } - if (allowEmpty && this$1.type === types.comma) { - elts.push(null); - } else if (allowTrailingComma && this$1.afterTrailingComma(close)) { - break - } else if (this$1.type === types.ellipsis) { - var rest = this$1.parseRestBinding(); - this$1.parseBindingListItem(rest); - elts.push(rest); - if (this$1.type === types.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(types.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. -// bindingType can be either: -// 'var' indicating that the lval creates a 'var' binding -// 'let' indicating that the lval creates a lexical ('let' or 'const') binding -// 'none' indicating that the binding should be checked for illegal identifiers, but not for duplicate references - -pp$2.checkLVal = function(expr, bindingType, checkClashes) { - var this$1 = this; - if ( bindingType === void 0 ) bindingType = BIND_NONE; - - switch (expr.type) { - case "Identifier": - if (this.strict && this.reservedWordsStrictBind.test(expr.name)) - { this.raiseRecoverable(expr.start, (bindingType ? "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; - } - if (bindingType !== BIND_NONE && bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); } - break - - case "MemberExpression": - if (bindingType) { this.raiseRecoverable(expr.start, "Binding member expression"); } - break - - case "ObjectPattern": - for (var i = 0, list = expr.properties; i < list.length; i += 1) - { - var prop = list[i]; - - this$1.checkLVal(prop, bindingType, checkClashes); - } - break - - case "Property": - // AssignmentProperty has type === "Property" - this.checkLVal(expr.value, bindingType, checkClashes); - break - - case "ArrayPattern": - for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) { - var elem = list$1[i$1]; - - if (elem) { this$1.checkLVal(elem, bindingType, checkClashes); } - } - break - - case "AssignmentPattern": - this.checkLVal(expr.left, bindingType, checkClashes); - break - - case "RestElement": - this.checkLVal(expr.argument, bindingType, checkClashes); - break - - case "ParenthesizedExpression": - this.checkLVal(expr.expression, bindingType, checkClashes); - break - - default: - this.raise(expr.start, (bindingType ? "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, refDestructuringErrors) { - if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement") - { return } - 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) { - if (refDestructuringErrors && refDestructuringErrors.doubleProto < 0) { refDestructuringErrors.doubleProto = key.start; } - // Backwards-compat kludge. Can be removed in version 6.0 - else { this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); } - } - propHash.proto = true; - } - return - } - name = "$" + name; - var other = propHash[name]; - if (other) { - var redefinition; - if (kind === "init") { - redefinition = this.strict && other.init || other.get || other.set; - } else { - redefinition = other.init || other[kind]; - } - if (redefinition) - { 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 === types.comma) { - var node = this.startNodeAt(startPos, startLoc); - node.expressions = [expr]; - while (this.eat(types.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.isContextual("yield")) { - if (this.inGenerator) { return this.parseYield(noIn) } - // The tokenizer will assume an expression is allowed after - // `yield`, but this isn't that kind of yield - else { this.exprAllowed = false; } - } - - var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldShorthandAssign = -1; - if (refDestructuringErrors) { - oldParenAssign = refDestructuringErrors.parenthesizedAssign; - oldTrailingComma = refDestructuringErrors.trailingComma; - oldShorthandAssign = refDestructuringErrors.shorthandAssign; - refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.shorthandAssign = -1; - } else { - refDestructuringErrors = new DestructuringErrors; - ownDestructuringErrors = true; - } - - var startPos = this.start, startLoc = this.startLoc; - if (this.type === types.parenL || this.type === types.name) - { this.potentialArrowAt = this.start; } - var left = this.parseMaybeConditional(noIn, refDestructuringErrors); - if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); } - if (this.type.isAssign) { - var node = this.startNodeAt(startPos, startLoc); - node.operator = this.value; - node.left = this.type === types.eq ? this.toAssignable(left, false, refDestructuringErrors) : left; - if (!ownDestructuringErrors) { DestructuringErrors.call(refDestructuringErrors); } - refDestructuringErrors.shorthandAssign = -1; // 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); } - } - if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; } - if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; } - if (oldShorthandAssign > -1) { refDestructuringErrors.shorthandAssign = oldShorthandAssign; } - 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(types.question)) { - var node = this.startNodeAt(startPos, startLoc); - node.test = expr; - node.consequent = this.parseMaybeAssign(); - this.expect(types.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 expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : 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 !== types._in)) { - if (prec > minPrec) { - var logical = this.type === types.logicalOR || this.type === types.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.isContextual("await") && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction))) { - expr = this.parseAwait(); - sawUnary = true; - } else if (this.type.prefix) { - var node = this.startNode(), update = this.type === types.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(types.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 } - var result = this.parseSubscripts(expr, startPos, startLoc); - if (refDestructuringErrors && result.type === "MemberExpression") { - if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; } - if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; } - } - return result -}; - -pp$3.parseSubscripts = function(base, startPos, startLoc, noCalls) { - var this$1 = this; - - var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" && - this.lastTokEnd === base.end && !this.canInsertSemicolon() && this.input.slice(base.start, base.end) === "async"; - while (true) { - var element = this$1.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow); - if (element === base || element.type === "ArrowFunctionExpression") { return element } - base = element; - } -}; - -pp$3.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow) { - var computed = this.eat(types.bracketL); - if (computed || this.eat(types.dot)) { - var node = this.startNodeAt(startPos, startLoc); - node.object = base; - node.property = computed ? this.parseExpression() : this.parseIdent(true); - node.computed = !!computed; - if (computed) { this.expect(types.bracketR); } - base = this.finishNode(node, "MemberExpression"); - } else if (!noCalls && this.eat(types.parenL)) { - var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; - this.yieldPos = 0; - this.awaitPos = 0; - this.awaitIdentPos = 0; - var exprList = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors); - if (maybeAsyncArrow && !this.canInsertSemicolon() && this.eat(types.arrow)) { - this.checkPatternErrors(refDestructuringErrors, false); - this.checkYieldAwaitInDefaultParams(); - if (this.awaitIdentPos > 0) - { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); } - this.yieldPos = oldYieldPos; - this.awaitPos = oldAwaitPos; - this.awaitIdentPos = oldAwaitIdentPos; - return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true) - } - this.checkExpressionErrors(refDestructuringErrors, true); - this.yieldPos = oldYieldPos || this.yieldPos; - this.awaitPos = oldAwaitPos || this.awaitPos; - this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos; - var node$1 = this.startNodeAt(startPos, startLoc); - node$1.callee = base; - node$1.arguments = exprList; - base = this.finishNode(node$1, "CallExpression"); - } else if (this.type === types.backQuote) { - var node$2 = this.startNodeAt(startPos, startLoc); - node$2.tag = base; - node$2.quasi = this.parseTemplate({isTagged: true}); - base = this.finishNode(node$2, "TaggedTemplateExpression"); - } - 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) { - // If a division operator appears in an expression position, the - // tokenizer got confused, and we force it to read a regexp instead. - if (this.type === types.slash) { this.readRegexp(); } - - var node, canBeArrow = this.potentialArrowAt === this.start; - switch (this.type) { - case types._super: - if (!this.allowSuper) - { this.raise(this.start, "'super' keyword outside a method"); } - node = this.startNode(); - this.next(); - if (this.type === types.parenL && !this.allowDirectSuper) - { this.raise(node.start, "super() call outside constructor of a subclass"); } - // The `super` keyword can appear at below: - // SuperProperty: - // super [ Expression ] - // super . IdentifierName - // SuperCall: - // super Arguments - if (this.type !== types.dot && this.type !== types.bracketL && this.type !== types.parenL) - { this.unexpected(); } - return this.finishNode(node, "Super") - - case types._this: - node = this.startNode(); - this.next(); - return this.finishNode(node, "ThisExpression") - - case types.name: - var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc; - var id = this.parseIdent(false); - if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types._function)) - { return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true) } - if (canBeArrow && !this.canInsertSemicolon()) { - if (this.eat(types.arrow)) - { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false) } - if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types.name && !containsEsc) { - id = this.parseIdent(false); - if (this.canInsertSemicolon() || !this.eat(types.arrow)) - { this.unexpected(); } - return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true) - } - } - return id - - case types.regexp: - var value = this.value; - node = this.parseLiteral(value.value); - node.regex = {pattern: value.pattern, flags: value.flags}; - return node - - case types.num: case types.string: - return this.parseLiteral(this.value) - - case types._null: case types._true: case types._false: - node = this.startNode(); - node.value = this.type === types._null ? null : this.type === types._true; - node.raw = this.type.keyword; - this.next(); - return this.finishNode(node, "Literal") - - case types.parenL: - var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow); - if (refDestructuringErrors) { - if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr)) - { refDestructuringErrors.parenthesizedAssign = start; } - if (refDestructuringErrors.parenthesizedBind < 0) - { refDestructuringErrors.parenthesizedBind = start; } - } - return expr - - case types.bracketL: - node = this.startNode(); - this.next(); - node.elements = this.parseExprList(types.bracketR, true, true, refDestructuringErrors); - return this.finishNode(node, "ArrayExpression") - - case types.braceL: - return this.parseObj(false, refDestructuringErrors) - - case types._function: - node = this.startNode(); - this.next(); - return this.parseFunction(node, 0) - - case types._class: - return this.parseClass(this.startNode(), false) - - case types._new: - return this.parseNew() - - case types.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(types.parenL); - var val = this.parseExpression(); - this.expect(types.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; - this.yieldPos = 0; - this.awaitPos = 0; - // Do not save awaitIdentPos to allow checking awaits nested in parameters - while (this.type !== types.parenR) { - first ? first = false : this$1.expect(types.comma); - if (allowTrailingComma && this$1.afterTrailingComma(types.parenR, true)) { - lastIsComma = true; - break - } else if (this$1.type === types.ellipsis) { - spreadStart = this$1.start; - exprList.push(this$1.parseParenItem(this$1.parseRestBinding())); - if (this$1.type === types.comma) { this$1.raise(this$1.start, "Comma is not permitted after the rest element"); } - break - } else { - exprList.push(this$1.parseMaybeAssign(false, refDestructuringErrors, this$1.parseParenItem)); - } - } - var innerEndPos = this.start, innerEndLoc = this.startLoc; - this.expect(types.parenR); - - if (canBeArrow && !this.canInsertSemicolon() && this.eat(types.arrow)) { - this.checkPatternErrors(refDestructuringErrors, false); - this.checkYieldAwaitInDefaultParams(); - 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(types.dot)) { - node.meta = meta; - var containsEsc = this.containsEsc; - node.property = this.parseIdent(true); - if (node.property.name !== "target" || containsEsc) - { this.raiseRecoverable(node.property.start, "The only valid meta property for new is new.target"); } - if (!this.inNonArrowFunction()) - { 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(types.parenL)) { node.arguments = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false); } - else { node.arguments = empty$1; } - return this.finishNode(node, "NewExpression") -}; - -// Parse template expression. - -pp$3.parseTemplateElement = function(ref) { - var isTagged = ref.isTagged; - - var elem = this.startNode(); - if (this.type === types.invalidTemplate) { - if (!isTagged) { - this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal"); - } - elem.value = { - raw: this.value, - cooked: null - }; - } else { - elem.value = { - raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"), - cooked: this.value - }; - } - this.next(); - elem.tail = this.type === types.backQuote; - return this.finishNode(elem, "TemplateElement") -}; - -pp$3.parseTemplate = function(ref) { - var this$1 = this; - if ( ref === void 0 ) ref = {}; - var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false; - - var node = this.startNode(); - this.next(); - node.expressions = []; - var curElt = this.parseTemplateElement({isTagged: isTagged}); - node.quasis = [curElt]; - while (!curElt.tail) { - if (this$1.type === types.eof) { this$1.raise(this$1.pos, "Unterminated template literal"); } - this$1.expect(types.dollarBraceL); - node.expressions.push(this$1.parseExpression()); - this$1.expect(types.braceR); - node.quasis.push(curElt = this$1.parseTemplateElement({isTagged: isTagged})); - } - this.next(); - return this.finishNode(node, "TemplateLiteral") -}; - -pp$3.isAsyncProp = function(prop) { - return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" && - (this.type === types.name || this.type === types.num || this.type === types.string || this.type === types.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types.star)) && - !lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) -}; - -// 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(types.braceR)) { - if (!first) { - this$1.expect(types.comma); - if (this$1.afterTrailingComma(types.braceR)) { break } - } else { first = false; } - - var prop = this$1.parseProperty(isPattern, refDestructuringErrors); - if (!isPattern) { this$1.checkPropClash(prop, propHash, refDestructuringErrors); } - node.properties.push(prop); - } - return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression") -}; - -pp$3.parseProperty = function(isPattern, refDestructuringErrors) { - var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc; - if (this.options.ecmaVersion >= 9 && this.eat(types.ellipsis)) { - if (isPattern) { - prop.argument = this.parseIdent(false); - if (this.type === types.comma) { - this.raise(this.start, "Comma is not permitted after the rest element"); - } - return this.finishNode(prop, "RestElement") - } - // To disallow parenthesized identifier via `this.toAssignable()`. - if (this.type === types.parenL && refDestructuringErrors) { - if (refDestructuringErrors.parenthesizedAssign < 0) { - refDestructuringErrors.parenthesizedAssign = this.start; - } - if (refDestructuringErrors.parenthesizedBind < 0) { - refDestructuringErrors.parenthesizedBind = this.start; - } - } - // Parse argument. - prop.argument = this.parseMaybeAssign(false, refDestructuringErrors); - // To disallow trailing comma via `this.toAssignable()`. - if (this.type === types.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) { - refDestructuringErrors.trailingComma = this.start; - } - // Finish - return this.finishNode(prop, "SpreadElement") - } - if (this.options.ecmaVersion >= 6) { - prop.method = false; - prop.shorthand = false; - if (isPattern || refDestructuringErrors) { - startPos = this.start; - startLoc = this.startLoc; - } - if (!isPattern) - { isGenerator = this.eat(types.star); } - } - var containsEsc = this.containsEsc; - this.parsePropertyName(prop); - if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) { - isAsync = true; - isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star); - this.parsePropertyName(prop, refDestructuringErrors); - } else { - isAsync = false; - } - this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc); - return this.finishNode(prop, "Property") -}; - -pp$3.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) { - if ((isGenerator || isAsync) && this.type === types.colon) - { this.unexpected(); } - - if (this.eat(types.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 === types.parenL) { - if (isPattern) { this.unexpected(); } - prop.kind = "init"; - prop.method = true; - prop.value = this.parseMethod(isGenerator, isAsync); - } else if (!isPattern && !containsEsc && - this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && - (prop.key.name === "get" || prop.key.name === "set") && - (this.type !== types.comma && this.type !== types.braceR)) { - if (isGenerator || isAsync) { 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 (isGenerator || isAsync) { this.unexpected(); } - this.checkUnreserved(prop.key); - if (prop.key.name === "await" && !this.awaitIdentPos) - { this.awaitIdentPos = startPos; } - prop.kind = "init"; - if (isPattern) { - prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key); - } else if (this.type === types.eq && refDestructuringErrors) { - if (refDestructuringErrors.shorthandAssign < 0) - { 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(types.bracketL)) { - prop.computed = true; - prop.key = this.parseMaybeAssign(); - this.expect(types.bracketR); - return prop.key - } else { - prop.computed = false; - } - } - return prop.key = this.type === types.num || this.type === types.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 = node.expression = false; } - if (this.options.ecmaVersion >= 8) { node.async = false; } -}; - -// Parse object or class method. - -pp$3.parseMethod = function(isGenerator, isAsync, allowDirectSuper) { - var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; - - this.initFunction(node); - if (this.options.ecmaVersion >= 6) - { node.generator = isGenerator; } - if (this.options.ecmaVersion >= 8) - { node.async = !!isAsync; } - - this.yieldPos = 0; - this.awaitPos = 0; - this.awaitIdentPos = 0; - this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0)); - - this.expect(types.parenL); - node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8); - this.checkYieldAwaitInDefaultParams(); - this.parseFunctionBody(node, false, true); - - this.yieldPos = oldYieldPos; - this.awaitPos = oldAwaitPos; - this.awaitIdentPos = oldAwaitIdentPos; - return this.finishNode(node, "FunctionExpression") -}; - -// Parse arrow function expression with given parameters. - -pp$3.parseArrowExpression = function(node, params, isAsync) { - var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; - - this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW); - this.initFunction(node); - if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; } - - this.yieldPos = 0; - this.awaitPos = 0; - this.awaitIdentPos = 0; - - node.params = this.toAssignableList(params, true); - this.parseFunctionBody(node, true, false); - - this.yieldPos = oldYieldPos; - this.awaitPos = oldAwaitPos; - this.awaitIdentPos = oldAwaitIdentPos; - return this.finishNode(node, "ArrowFunctionExpression") -}; - -// Parse function body and check parameters. - -pp$3.parseFunctionBody = function(node, isArrowFunction, isMethod) { - var isExpression = isArrowFunction && this.type !== types.braceL; - var oldStrict = this.strict, useStrict = false; - - if (isExpression) { - node.body = this.parseMaybeAssign(); - node.expression = true; - this.checkParams(node, false); - } else { - var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params); - if (!oldStrict || nonSimple) { - useStrict = this.strictDirective(this.end); - // 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`. - if (useStrict && nonSimple) - { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); } - } - // Start a new scope with regard to labels and the `inFunction` - // flag (restore them to their old value afterwards). - var oldLabels = this.labels; - this.labels = []; - if (useStrict) { this.strict = true; } - - // Add the params to varDeclaredNames to ensure that an error is thrown - // if a let/const declaration in the function clashes with one of the params. - this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params)); - node.body = this.parseBlock(false); - node.expression = false; - this.adaptDirectivePrologue(node.body.body); - this.labels = oldLabels; - } - this.exitScope(); - - // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval' - if (this.strict && node.id) { this.checkLVal(node.id, BIND_OUTSIDE); } - this.strict = oldStrict; -}; - -pp$3.isSimpleParamList = function(params) { - for (var i = 0, list = params; i < list.length; i += 1) - { - var param = list[i]; - - if (param.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, allowDuplicates) { - var this$1 = this; - - var nameHash = {}; - for (var i = 0, list = node.params; i < list.length; i += 1) - { - var param = list[i]; - - this$1.checkLVal(param, BIND_VAR, allowDuplicates ? null : 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(types.comma); - if (allowTrailingComma && this$1.afterTrailingComma(close)) { break } - } else { first = false; } - - var elt = (void 0); - if (allowEmpty && this$1.type === types.comma) - { elt = null; } - else if (this$1.type === types.ellipsis) { - elt = this$1.parseSpread(refDestructuringErrors); - if (refDestructuringErrors && this$1.type === types.comma && refDestructuringErrors.trailingComma < 0) - { refDestructuringErrors.trailingComma = this$1.start; } - } else { - elt = this$1.parseMaybeAssign(false, refDestructuringErrors); - } - elts.push(elt); - } - return elts -}; - -pp$3.checkUnreserved = function(ref) { - var start = ref.start; - var end = ref.end; - var name = ref.name; - - if (this.inGenerator && name === "yield") - { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); } - if (this.inAsync && name === "await") - { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); } - if (this.keywords.test(name)) - { this.raise(start, ("Unexpected keyword '" + name + "'")); } - if (this.options.ecmaVersion < 6 && - this.input.slice(start, end).indexOf("\\") !== -1) { return } - var re = this.strict ? this.reservedWordsStrict : this.reservedWords; - if (re.test(name)) { - if (!this.inAsync && name === "await") - { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); } - this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved")); - } -}; - -// 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, isBinding) { - var node = this.startNode(); - if (liberal && this.options.allowReserved === "never") { liberal = false; } - if (this.type === types.name) { - node.name = this.value; - } else if (this.type.keyword) { - node.name = this.type.keyword; - - // To fix https://github.com/acornjs/acorn/issues/575 - // `class` and `function` keywords push new context into this.context. - // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name. - // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword - if ((node.name === "class" || node.name === "function") && - (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) { - this.context.pop(); - } - } else { - this.unexpected(); - } - this.next(); - this.finishNode(node, "Identifier"); - if (!liberal) { - this.checkUnreserved(node); - if (node.name === "await" && !this.awaitIdentPos) - { this.awaitIdentPos = node.start; } - } - return node -}; - -// Parses yield expression inside generator. - -pp$3.parseYield = function(noIn) { - if (!this.yieldPos) { this.yieldPos = this.start; } - - var node = this.startNode(); - this.next(); - if (this.type === types.semi || this.canInsertSemicolon() || (this.type !== types.star && !this.type.startsExpr)) { - node.delegate = false; - node.argument = null; - } else { - node.delegate = this.eat(types.star); - node.argument = this.parseMaybeAssign(noIn); - } - 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 pp$5 = Parser.prototype; - -var Scope = function Scope(flags) { - this.flags = flags; - // A list of var-declared names in the current lexical scope - this.var = []; - // A list of lexically-declared names in the current lexical scope - this.lexical = []; - // A list of lexically-declared FunctionDeclaration names in the current lexical scope - this.functions = []; -}; - -// The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names. - -pp$5.enterScope = function(flags) { - this.scopeStack.push(new Scope(flags)); -}; - -pp$5.exitScope = function() { - this.scopeStack.pop(); -}; - -// The spec says: -// > At the top level of a function, or script, function declarations are -// > treated like var declarations rather than like lexical declarations. -pp$5.treatFunctionsAsVarInScope = function(scope) { - return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP) -}; - -pp$5.declareName = function(name, bindingType, pos) { - var this$1 = this; - - var redeclared = false; - if (bindingType === BIND_LEXICAL) { - var scope = this.currentScope(); - redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1; - scope.lexical.push(name); - if (this.inModule && (scope.flags & SCOPE_TOP)) - { delete this.undefinedExports[name]; } - } else if (bindingType === BIND_SIMPLE_CATCH) { - var scope$1 = this.currentScope(); - scope$1.lexical.push(name); - } else if (bindingType === BIND_FUNCTION) { - var scope$2 = this.currentScope(); - if (this.treatFunctionsAsVar) - { redeclared = scope$2.lexical.indexOf(name) > -1; } - else - { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; } - scope$2.functions.push(name); - } else { - for (var i = this.scopeStack.length - 1; i >= 0; --i) { - var scope$3 = this$1.scopeStack[i]; - if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) || - !this$1.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) { - redeclared = true; - break - } - scope$3.var.push(name); - if (this$1.inModule && (scope$3.flags & SCOPE_TOP)) - { delete this$1.undefinedExports[name]; } - if (scope$3.flags & SCOPE_VAR) { break } - } - } - if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); } -}; - -pp$5.checkLocalExport = function(id) { - // scope.functions must be empty as Module code is always strict. - if (this.scopeStack[0].lexical.indexOf(id.name) === -1 && - this.scopeStack[0].var.indexOf(id.name) === -1) { - this.undefinedExports[id.name] = id; - } -}; - -pp$5.currentScope = function() { - return this.scopeStack[this.scopeStack.length - 1] -}; - -pp$5.currentVarScope = function() { - var this$1 = this; - - for (var i = this.scopeStack.length - 1;; i--) { - var scope = this$1.scopeStack[i]; - if (scope.flags & SCOPE_VAR) { return scope } - } -}; - -// Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`. -pp$5.currentThisScope = function() { - var this$1 = this; - - for (var i = this.scopeStack.length - 1;; i--) { - var scope = this$1.scopeStack[i]; - if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope } - } -}; - -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$6 = Parser.prototype; - -pp$6.startNode = function() { - return new Node(this, this.start, this.startLoc) -}; - -pp$6.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$6.finishNode = function(node, type) { - return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc) -}; - -// Finish node at given position - -pp$6.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, generator) { - this.token = token; - this.isExpr = !!isExpr; - this.preserveSpace = !!preserveSpace; - this.override = override; - this.generator = !!generator; -}; - -var types$1 = { - b_stat: new TokContext("{", false), - b_expr: new TokContext("{", true), - b_tmpl: new TokContext("${", false), - p_stat: new TokContext("(", false), - p_expr: new TokContext("(", true), - q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }), - f_stat: new TokContext("function", false), - f_expr: new TokContext("function", true), - f_expr_gen: new TokContext("function", true, false, null, true), - f_gen: new TokContext("function", false, false, null, true) -}; - -var pp$7 = Parser.prototype; - -pp$7.initialContext = function() { - return [types$1.b_stat] -}; - -pp$7.braceIsBlock = function(prevType) { - var parent = this.curContext(); - if (parent === types$1.f_expr || parent === types$1.f_stat) - { return true } - if (prevType === types.colon && (parent === types$1.b_stat || parent === types$1.b_expr)) - { return !parent.isExpr } - - // The check for `tt.name && exprAllowed` detects whether we are - // after a `yield` or `of` construct. See the `updateContext` for - // `tt.name`. - if (prevType === types._return || prevType === types.name && this.exprAllowed) - { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) } - if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType === types.arrow) - { return true } - if (prevType === types.braceL) - { return parent === types$1.b_stat } - if (prevType === types._var || prevType === types._const || prevType === types.name) - { return false } - return !this.exprAllowed -}; - -pp$7.inGeneratorContext = function() { - var this$1 = this; - - for (var i = this.context.length - 1; i >= 1; i--) { - var context = this$1.context[i]; - if (context.token === "function") - { return context.generator } - } - return false -}; - -pp$7.updateContext = function(prevType) { - var update, type = this.type; - if (type.keyword && prevType === types.dot) - { this.exprAllowed = false; } - else if (update = type.updateContext) - { update.call(this, prevType); } - else - { this.exprAllowed = type.beforeExpr; } -}; - -// Token-specific context update code - -types.parenR.updateContext = types.braceR.updateContext = function() { - if (this.context.length === 1) { - this.exprAllowed = true; - return - } - var out = this.context.pop(); - if (out === types$1.b_stat && this.curContext().token === "function") { - out = this.context.pop(); - } - this.exprAllowed = !out.isExpr; -}; - -types.braceL.updateContext = function(prevType) { - this.context.push(this.braceIsBlock(prevType) ? types$1.b_stat : types$1.b_expr); - this.exprAllowed = true; -}; - -types.dollarBraceL.updateContext = function() { - this.context.push(types$1.b_tmpl); - this.exprAllowed = true; -}; - -types.parenL.updateContext = function(prevType) { - var statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while; - this.context.push(statementParens ? types$1.p_stat : types$1.p_expr); - this.exprAllowed = true; -}; - -types.incDec.updateContext = function() { - // tokExprAllowed stays unchanged -}; - -types._function.updateContext = types._class.updateContext = function(prevType) { - if (prevType.beforeExpr && prevType !== types.semi && prevType !== types._else && - !(prevType === types._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) && - !((prevType === types.colon || prevType === types.braceL) && this.curContext() === types$1.b_stat)) - { this.context.push(types$1.f_expr); } - else - { this.context.push(types$1.f_stat); } - this.exprAllowed = false; -}; - -types.backQuote.updateContext = function() { - if (this.curContext() === types$1.q_tmpl) - { this.context.pop(); } - else - { this.context.push(types$1.q_tmpl); } - this.exprAllowed = false; -}; - -types.star.updateContext = function(prevType) { - if (prevType === types._function) { - var index = this.context.length - 1; - if (this.context[index] === types$1.f_expr) - { this.context[index] = types$1.f_expr_gen; } - else - { this.context[index] = types$1.f_gen; } - } - this.exprAllowed = true; -}; - -types.name.updateContext = function(prevType) { - var allowed = false; - if (this.options.ecmaVersion >= 6 && prevType !== types.dot) { - if (this.value === "of" && !this.exprAllowed || - this.value === "yield" && this.inGeneratorContext()) - { allowed = true; } - } - this.exprAllowed = allowed; -}; - -// This file contains Unicode properties extracted from the ECMAScript -// specification. The lists are extracted like so: -// $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText) - -// #table-binary-unicode-properties -var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS"; -var unicodeBinaryProperties = { - 9: ecma9BinaryProperties, - 10: ecma9BinaryProperties + " Extended_Pictographic" -}; - -// #table-unicode-general-category-values -var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu"; - -// #table-unicode-script-values -var ecma9ScriptValues = "Adlam Adlm Ahom Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb"; -var unicodeScriptValues = { - 9: ecma9ScriptValues, - 10: ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd" -}; - -var data = {}; -function buildUnicodeData(ecmaVersion) { - var d = data[ecmaVersion] = { - binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues), - nonBinary: { - General_Category: wordsRegexp(unicodeGeneralCategoryValues), - Script: wordsRegexp(unicodeScriptValues[ecmaVersion]) - } - }; - d.nonBinary.Script_Extensions = d.nonBinary.Script; - - d.nonBinary.gc = d.nonBinary.General_Category; - d.nonBinary.sc = d.nonBinary.Script; - d.nonBinary.scx = d.nonBinary.Script_Extensions; -} -buildUnicodeData(9); -buildUnicodeData(10); - -var pp$9 = Parser.prototype; - -var RegExpValidationState = function RegExpValidationState(parser) { - this.parser = parser; - this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : ""); - this.unicodeProperties = data[parser.options.ecmaVersion >= 10 ? 10 : parser.options.ecmaVersion]; - this.source = ""; - this.flags = ""; - this.start = 0; - this.switchU = false; - this.switchN = false; - this.pos = 0; - this.lastIntValue = 0; - this.lastStringValue = ""; - this.lastAssertionIsQuantifiable = false; - this.numCapturingParens = 0; - this.maxBackReference = 0; - this.groupNames = []; - this.backReferenceNames = []; -}; - -RegExpValidationState.prototype.reset = function reset (start, pattern, flags) { - var unicode = flags.indexOf("u") !== -1; - this.start = start | 0; - this.source = pattern + ""; - this.flags = flags; - this.switchU = unicode && this.parser.options.ecmaVersion >= 6; - this.switchN = unicode && this.parser.options.ecmaVersion >= 9; -}; - -RegExpValidationState.prototype.raise = function raise (message) { - this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message)); -}; - -// If u flag is given, this returns the code point at the index (it combines a surrogate pair). -// Otherwise, this returns the code unit of the index (can be a part of a surrogate pair). -RegExpValidationState.prototype.at = function at (i) { - var s = this.source; - var l = s.length; - if (i >= l) { - return -1 - } - var c = s.charCodeAt(i); - if (!this.switchU || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) { - return c - } - return (c << 10) + s.charCodeAt(i + 1) - 0x35FDC00 -}; - -RegExpValidationState.prototype.nextIndex = function nextIndex (i) { - var s = this.source; - var l = s.length; - if (i >= l) { - return l - } - var c = s.charCodeAt(i); - if (!this.switchU || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) { - return i + 1 - } - return i + 2 -}; - -RegExpValidationState.prototype.current = function current () { - return this.at(this.pos) -}; - -RegExpValidationState.prototype.lookahead = function lookahead () { - return this.at(this.nextIndex(this.pos)) -}; - -RegExpValidationState.prototype.advance = function advance () { - this.pos = this.nextIndex(this.pos); -}; - -RegExpValidationState.prototype.eat = function eat (ch) { - if (this.current() === ch) { - this.advance(); - return true - } - return false -}; - -function codePointToString$1(ch) { - if (ch <= 0xFFFF) { return String.fromCharCode(ch) } - ch -= 0x10000; - return String.fromCharCode((ch >> 10) + 0xD800, (ch & 0x03FF) + 0xDC00) -} - -/** - * Validate the flags part of a given RegExpLiteral. - * - * @param {RegExpValidationState} state The state to validate RegExp. - * @returns {void} - */ -pp$9.validateRegExpFlags = function(state) { - var this$1 = this; - - var validFlags = state.validFlags; - var flags = state.flags; - - for (var i = 0; i < flags.length; i++) { - var flag = flags.charAt(i); - if (validFlags.indexOf(flag) === -1) { - this$1.raise(state.start, "Invalid regular expression flag"); - } - if (flags.indexOf(flag, i + 1) > -1) { - this$1.raise(state.start, "Duplicate regular expression flag"); - } - } -}; - -/** - * Validate the pattern part of a given RegExpLiteral. - * - * @param {RegExpValidationState} state The state to validate RegExp. - * @returns {void} - */ -pp$9.validateRegExpPattern = function(state) { - this.regexp_pattern(state); - - // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of - // parsing contains a |GroupName|, reparse with the goal symbol - // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError* - // exception if _P_ did not conform to the grammar, if any elements of _P_ - // were not matched by the parse, or if any Early Error conditions exist. - if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) { - state.switchN = true; - this.regexp_pattern(state); - } -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern -pp$9.regexp_pattern = function(state) { - state.pos = 0; - state.lastIntValue = 0; - state.lastStringValue = ""; - state.lastAssertionIsQuantifiable = false; - state.numCapturingParens = 0; - state.maxBackReference = 0; - state.groupNames.length = 0; - state.backReferenceNames.length = 0; - - this.regexp_disjunction(state); - - if (state.pos !== state.source.length) { - // Make the same messages as V8. - if (state.eat(0x29 /* ) */)) { - state.raise("Unmatched ')'"); - } - if (state.eat(0x5D /* [ */) || state.eat(0x7D /* } */)) { - state.raise("Lone quantifier brackets"); - } - } - if (state.maxBackReference > state.numCapturingParens) { - state.raise("Invalid escape"); - } - for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) { - var name = list[i]; - - if (state.groupNames.indexOf(name) === -1) { - state.raise("Invalid named capture referenced"); - } - } -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction -pp$9.regexp_disjunction = function(state) { - var this$1 = this; - - this.regexp_alternative(state); - while (state.eat(0x7C /* | */)) { - this$1.regexp_alternative(state); - } - - // Make the same message as V8. - if (this.regexp_eatQuantifier(state, true)) { - state.raise("Nothing to repeat"); - } - if (state.eat(0x7B /* { */)) { - state.raise("Lone quantifier brackets"); - } -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative -pp$9.regexp_alternative = function(state) { - while (state.pos < state.source.length && this.regexp_eatTerm(state)) - { } -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term -pp$9.regexp_eatTerm = function(state) { - if (this.regexp_eatAssertion(state)) { - // Handle `QuantifiableAssertion Quantifier` alternative. - // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion - // is a QuantifiableAssertion. - if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) { - // Make the same message as V8. - if (state.switchU) { - state.raise("Invalid quantifier"); - } - } - return true - } - - if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) { - this.regexp_eatQuantifier(state); - return true - } - - return false -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion -pp$9.regexp_eatAssertion = function(state) { - var start = state.pos; - state.lastAssertionIsQuantifiable = false; - - // ^, $ - if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) { - return true - } - - // \b \B - if (state.eat(0x5C /* \ */)) { - if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) { - return true - } - state.pos = start; - } - - // Lookahead / Lookbehind - if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) { - var lookbehind = false; - if (this.options.ecmaVersion >= 9) { - lookbehind = state.eat(0x3C /* < */); - } - if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) { - this.regexp_disjunction(state); - if (!state.eat(0x29 /* ) */)) { - state.raise("Unterminated group"); - } - state.lastAssertionIsQuantifiable = !lookbehind; - return true - } - } - - state.pos = start; - return false -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier -pp$9.regexp_eatQuantifier = function(state, noError) { - if ( noError === void 0 ) noError = false; - - if (this.regexp_eatQuantifierPrefix(state, noError)) { - state.eat(0x3F /* ? */); - return true - } - return false -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix -pp$9.regexp_eatQuantifierPrefix = function(state, noError) { - return ( - state.eat(0x2A /* * */) || - state.eat(0x2B /* + */) || - state.eat(0x3F /* ? */) || - this.regexp_eatBracedQuantifier(state, noError) - ) -}; -pp$9.regexp_eatBracedQuantifier = function(state, noError) { - var start = state.pos; - if (state.eat(0x7B /* { */)) { - var min = 0, max = -1; - if (this.regexp_eatDecimalDigits(state)) { - min = state.lastIntValue; - if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) { - max = state.lastIntValue; - } - if (state.eat(0x7D /* } */)) { - // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term - if (max !== -1 && max < min && !noError) { - state.raise("numbers out of order in {} quantifier"); - } - return true - } - } - if (state.switchU && !noError) { - state.raise("Incomplete quantifier"); - } - state.pos = start; - } - return false -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-Atom -pp$9.regexp_eatAtom = function(state) { - return ( - this.regexp_eatPatternCharacters(state) || - state.eat(0x2E /* . */) || - this.regexp_eatReverseSolidusAtomEscape(state) || - this.regexp_eatCharacterClass(state) || - this.regexp_eatUncapturingGroup(state) || - this.regexp_eatCapturingGroup(state) - ) -}; -pp$9.regexp_eatReverseSolidusAtomEscape = function(state) { - var start = state.pos; - if (state.eat(0x5C /* \ */)) { - if (this.regexp_eatAtomEscape(state)) { - return true - } - state.pos = start; - } - return false -}; -pp$9.regexp_eatUncapturingGroup = function(state) { - var start = state.pos; - if (state.eat(0x28 /* ( */)) { - if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) { - this.regexp_disjunction(state); - if (state.eat(0x29 /* ) */)) { - return true - } - state.raise("Unterminated group"); - } - state.pos = start; - } - return false -}; -pp$9.regexp_eatCapturingGroup = function(state) { - if (state.eat(0x28 /* ( */)) { - if (this.options.ecmaVersion >= 9) { - this.regexp_groupSpecifier(state); - } else if (state.current() === 0x3F /* ? */) { - state.raise("Invalid group"); - } - this.regexp_disjunction(state); - if (state.eat(0x29 /* ) */)) { - state.numCapturingParens += 1; - return true - } - state.raise("Unterminated group"); - } - return false -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom -pp$9.regexp_eatExtendedAtom = function(state) { - return ( - state.eat(0x2E /* . */) || - this.regexp_eatReverseSolidusAtomEscape(state) || - this.regexp_eatCharacterClass(state) || - this.regexp_eatUncapturingGroup(state) || - this.regexp_eatCapturingGroup(state) || - this.regexp_eatInvalidBracedQuantifier(state) || - this.regexp_eatExtendedPatternCharacter(state) - ) -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier -pp$9.regexp_eatInvalidBracedQuantifier = function(state) { - if (this.regexp_eatBracedQuantifier(state, true)) { - state.raise("Nothing to repeat"); - } - return false -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter -pp$9.regexp_eatSyntaxCharacter = function(state) { - var ch = state.current(); - if (isSyntaxCharacter(ch)) { - state.lastIntValue = ch; - state.advance(); - return true - } - return false -}; -function isSyntaxCharacter(ch) { - return ( - ch === 0x24 /* $ */ || - ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ || - ch === 0x2E /* . */ || - ch === 0x3F /* ? */ || - ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ || - ch >= 0x7B /* { */ && ch <= 0x7D /* } */ - ) -} - -// https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter -// But eat eager. -pp$9.regexp_eatPatternCharacters = function(state) { - var start = state.pos; - var ch = 0; - while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) { - state.advance(); - } - return state.pos !== start -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter -pp$9.regexp_eatExtendedPatternCharacter = function(state) { - var ch = state.current(); - if ( - ch !== -1 && - ch !== 0x24 /* $ */ && - !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) && - ch !== 0x2E /* . */ && - ch !== 0x3F /* ? */ && - ch !== 0x5B /* [ */ && - ch !== 0x5E /* ^ */ && - ch !== 0x7C /* | */ - ) { - state.advance(); - return true - } - return false -}; - -// GroupSpecifier[U] :: -// [empty] -// `?` GroupName[?U] -pp$9.regexp_groupSpecifier = function(state) { - if (state.eat(0x3F /* ? */)) { - if (this.regexp_eatGroupName(state)) { - if (state.groupNames.indexOf(state.lastStringValue) !== -1) { - state.raise("Duplicate capture group name"); - } - state.groupNames.push(state.lastStringValue); - return - } - state.raise("Invalid group"); - } -}; - -// GroupName[U] :: -// `<` RegExpIdentifierName[?U] `>` -// Note: this updates `state.lastStringValue` property with the eaten name. -pp$9.regexp_eatGroupName = function(state) { - state.lastStringValue = ""; - if (state.eat(0x3C /* < */)) { - if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) { - return true - } - state.raise("Invalid capture group name"); - } - return false -}; - -// RegExpIdentifierName[U] :: -// RegExpIdentifierStart[?U] -// RegExpIdentifierName[?U] RegExpIdentifierPart[?U] -// Note: this updates `state.lastStringValue` property with the eaten name. -pp$9.regexp_eatRegExpIdentifierName = function(state) { - state.lastStringValue = ""; - if (this.regexp_eatRegExpIdentifierStart(state)) { - state.lastStringValue += codePointToString$1(state.lastIntValue); - while (this.regexp_eatRegExpIdentifierPart(state)) { - state.lastStringValue += codePointToString$1(state.lastIntValue); - } - return true - } - return false -}; - -// RegExpIdentifierStart[U] :: -// UnicodeIDStart -// `$` -// `_` -// `\` RegExpUnicodeEscapeSequence[?U] -pp$9.regexp_eatRegExpIdentifierStart = function(state) { - var start = state.pos; - var ch = state.current(); - state.advance(); - - if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state)) { - ch = state.lastIntValue; - } - if (isRegExpIdentifierStart(ch)) { - state.lastIntValue = ch; - return true - } - - state.pos = start; - return false -}; -function isRegExpIdentifierStart(ch) { - return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ -} - -// RegExpIdentifierPart[U] :: -// UnicodeIDContinue -// `$` -// `_` -// `\` RegExpUnicodeEscapeSequence[?U] -// -// -pp$9.regexp_eatRegExpIdentifierPart = function(state) { - var start = state.pos; - var ch = state.current(); - state.advance(); - - if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state)) { - ch = state.lastIntValue; - } - if (isRegExpIdentifierPart(ch)) { - state.lastIntValue = ch; - return true - } - - state.pos = start; - return false -}; -function isRegExpIdentifierPart(ch) { - return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* */ || ch === 0x200D /* */ -} - -// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape -pp$9.regexp_eatAtomEscape = function(state) { - if ( - this.regexp_eatBackReference(state) || - this.regexp_eatCharacterClassEscape(state) || - this.regexp_eatCharacterEscape(state) || - (state.switchN && this.regexp_eatKGroupName(state)) - ) { - return true - } - if (state.switchU) { - // Make the same message as V8. - if (state.current() === 0x63 /* c */) { - state.raise("Invalid unicode escape"); - } - state.raise("Invalid escape"); - } - return false -}; -pp$9.regexp_eatBackReference = function(state) { - var start = state.pos; - if (this.regexp_eatDecimalEscape(state)) { - var n = state.lastIntValue; - if (state.switchU) { - // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape - if (n > state.maxBackReference) { - state.maxBackReference = n; - } - return true - } - if (n <= state.numCapturingParens) { - return true - } - state.pos = start; - } - return false -}; -pp$9.regexp_eatKGroupName = function(state) { - if (state.eat(0x6B /* k */)) { - if (this.regexp_eatGroupName(state)) { - state.backReferenceNames.push(state.lastStringValue); - return true - } - state.raise("Invalid named reference"); - } - return false -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape -pp$9.regexp_eatCharacterEscape = function(state) { - return ( - this.regexp_eatControlEscape(state) || - this.regexp_eatCControlLetter(state) || - this.regexp_eatZero(state) || - this.regexp_eatHexEscapeSequence(state) || - this.regexp_eatRegExpUnicodeEscapeSequence(state) || - (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) || - this.regexp_eatIdentityEscape(state) - ) -}; -pp$9.regexp_eatCControlLetter = function(state) { - var start = state.pos; - if (state.eat(0x63 /* c */)) { - if (this.regexp_eatControlLetter(state)) { - return true - } - state.pos = start; - } - return false -}; -pp$9.regexp_eatZero = function(state) { - if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) { - state.lastIntValue = 0; - state.advance(); - return true - } - return false -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape -pp$9.regexp_eatControlEscape = function(state) { - var ch = state.current(); - if (ch === 0x74 /* t */) { - state.lastIntValue = 0x09; /* \t */ - state.advance(); - return true - } - if (ch === 0x6E /* n */) { - state.lastIntValue = 0x0A; /* \n */ - state.advance(); - return true - } - if (ch === 0x76 /* v */) { - state.lastIntValue = 0x0B; /* \v */ - state.advance(); - return true - } - if (ch === 0x66 /* f */) { - state.lastIntValue = 0x0C; /* \f */ - state.advance(); - return true - } - if (ch === 0x72 /* r */) { - state.lastIntValue = 0x0D; /* \r */ - state.advance(); - return true - } - return false -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter -pp$9.regexp_eatControlLetter = function(state) { - var ch = state.current(); - if (isControlLetter(ch)) { - state.lastIntValue = ch % 0x20; - state.advance(); - return true - } - return false -}; -function isControlLetter(ch) { - return ( - (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) || - (ch >= 0x61 /* a */ && ch <= 0x7A /* z */) - ) -} - -// https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence -pp$9.regexp_eatRegExpUnicodeEscapeSequence = function(state) { - var start = state.pos; - - if (state.eat(0x75 /* u */)) { - if (this.regexp_eatFixedHexDigits(state, 4)) { - var lead = state.lastIntValue; - if (state.switchU && lead >= 0xD800 && lead <= 0xDBFF) { - var leadSurrogateEnd = state.pos; - if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) { - var trail = state.lastIntValue; - if (trail >= 0xDC00 && trail <= 0xDFFF) { - state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; - return true - } - } - state.pos = leadSurrogateEnd; - state.lastIntValue = lead; - } - return true - } - if ( - state.switchU && - state.eat(0x7B /* { */) && - this.regexp_eatHexDigits(state) && - state.eat(0x7D /* } */) && - isValidUnicode(state.lastIntValue) - ) { - return true - } - if (state.switchU) { - state.raise("Invalid unicode escape"); - } - state.pos = start; - } - - return false -}; -function isValidUnicode(ch) { - return ch >= 0 && ch <= 0x10FFFF -} - -// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape -pp$9.regexp_eatIdentityEscape = function(state) { - if (state.switchU) { - if (this.regexp_eatSyntaxCharacter(state)) { - return true - } - if (state.eat(0x2F /* / */)) { - state.lastIntValue = 0x2F; /* / */ - return true - } - return false - } - - var ch = state.current(); - if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) { - state.lastIntValue = ch; - state.advance(); - return true - } - - return false -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape -pp$9.regexp_eatDecimalEscape = function(state) { - state.lastIntValue = 0; - var ch = state.current(); - if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) { - do { - state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); - state.advance(); - } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) - return true - } - return false -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape -pp$9.regexp_eatCharacterClassEscape = function(state) { - var ch = state.current(); - - if (isCharacterClassEscape(ch)) { - state.lastIntValue = -1; - state.advance(); - return true - } - - if ( - state.switchU && - this.options.ecmaVersion >= 9 && - (ch === 0x50 /* P */ || ch === 0x70 /* p */) - ) { - state.lastIntValue = -1; - state.advance(); - if ( - state.eat(0x7B /* { */) && - this.regexp_eatUnicodePropertyValueExpression(state) && - state.eat(0x7D /* } */) - ) { - return true - } - state.raise("Invalid property name"); - } - - return false -}; -function isCharacterClassEscape(ch) { - return ( - ch === 0x64 /* d */ || - ch === 0x44 /* D */ || - ch === 0x73 /* s */ || - ch === 0x53 /* S */ || - ch === 0x77 /* w */ || - ch === 0x57 /* W */ - ) -} - -// UnicodePropertyValueExpression :: -// UnicodePropertyName `=` UnicodePropertyValue -// LoneUnicodePropertyNameOrValue -pp$9.regexp_eatUnicodePropertyValueExpression = function(state) { - var start = state.pos; - - // UnicodePropertyName `=` UnicodePropertyValue - if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) { - var name = state.lastStringValue; - if (this.regexp_eatUnicodePropertyValue(state)) { - var value = state.lastStringValue; - this.regexp_validateUnicodePropertyNameAndValue(state, name, value); - return true - } - } - state.pos = start; - - // LoneUnicodePropertyNameOrValue - if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) { - var nameOrValue = state.lastStringValue; - this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue); - return true - } - return false -}; -pp$9.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) { - if (!has(state.unicodeProperties.nonBinary, name)) - { state.raise("Invalid property name"); } - if (!state.unicodeProperties.nonBinary[name].test(value)) - { state.raise("Invalid property value"); } -}; -pp$9.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) { - if (!state.unicodeProperties.binary.test(nameOrValue)) - { state.raise("Invalid property name"); } -}; - -// UnicodePropertyName :: -// UnicodePropertyNameCharacters -pp$9.regexp_eatUnicodePropertyName = function(state) { - var ch = 0; - state.lastStringValue = ""; - while (isUnicodePropertyNameCharacter(ch = state.current())) { - state.lastStringValue += codePointToString$1(ch); - state.advance(); - } - return state.lastStringValue !== "" -}; -function isUnicodePropertyNameCharacter(ch) { - return isControlLetter(ch) || ch === 0x5F /* _ */ -} - -// UnicodePropertyValue :: -// UnicodePropertyValueCharacters -pp$9.regexp_eatUnicodePropertyValue = function(state) { - var ch = 0; - state.lastStringValue = ""; - while (isUnicodePropertyValueCharacter(ch = state.current())) { - state.lastStringValue += codePointToString$1(ch); - state.advance(); - } - return state.lastStringValue !== "" -}; -function isUnicodePropertyValueCharacter(ch) { - return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch) -} - -// LoneUnicodePropertyNameOrValue :: -// UnicodePropertyValueCharacters -pp$9.regexp_eatLoneUnicodePropertyNameOrValue = function(state) { - return this.regexp_eatUnicodePropertyValue(state) -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass -pp$9.regexp_eatCharacterClass = function(state) { - if (state.eat(0x5B /* [ */)) { - state.eat(0x5E /* ^ */); - this.regexp_classRanges(state); - if (state.eat(0x5D /* [ */)) { - return true - } - // Unreachable since it threw "unterminated regular expression" error before. - state.raise("Unterminated character class"); - } - return false -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges -// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges -// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash -pp$9.regexp_classRanges = function(state) { - var this$1 = this; - - while (this.regexp_eatClassAtom(state)) { - var left = state.lastIntValue; - if (state.eat(0x2D /* - */) && this$1.regexp_eatClassAtom(state)) { - var right = state.lastIntValue; - if (state.switchU && (left === -1 || right === -1)) { - state.raise("Invalid character class"); - } - if (left !== -1 && right !== -1 && left > right) { - state.raise("Range out of order in character class"); - } - } - } -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom -// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash -pp$9.regexp_eatClassAtom = function(state) { - var start = state.pos; - - if (state.eat(0x5C /* \ */)) { - if (this.regexp_eatClassEscape(state)) { - return true - } - if (state.switchU) { - // Make the same message as V8. - var ch$1 = state.current(); - if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) { - state.raise("Invalid class escape"); - } - state.raise("Invalid escape"); - } - state.pos = start; - } - - var ch = state.current(); - if (ch !== 0x5D /* [ */) { - state.lastIntValue = ch; - state.advance(); - return true - } - - return false -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape -pp$9.regexp_eatClassEscape = function(state) { - var start = state.pos; - - if (state.eat(0x62 /* b */)) { - state.lastIntValue = 0x08; /* */ - return true - } - - if (state.switchU && state.eat(0x2D /* - */)) { - state.lastIntValue = 0x2D; /* - */ - return true - } - - if (!state.switchU && state.eat(0x63 /* c */)) { - if (this.regexp_eatClassControlLetter(state)) { - return true - } - state.pos = start; - } - - return ( - this.regexp_eatCharacterClassEscape(state) || - this.regexp_eatCharacterEscape(state) - ) -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter -pp$9.regexp_eatClassControlLetter = function(state) { - var ch = state.current(); - if (isDecimalDigit(ch) || ch === 0x5F /* _ */) { - state.lastIntValue = ch % 0x20; - state.advance(); - return true - } - return false -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence -pp$9.regexp_eatHexEscapeSequence = function(state) { - var start = state.pos; - if (state.eat(0x78 /* x */)) { - if (this.regexp_eatFixedHexDigits(state, 2)) { - return true - } - if (state.switchU) { - state.raise("Invalid escape"); - } - state.pos = start; - } - return false -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits -pp$9.regexp_eatDecimalDigits = function(state) { - var start = state.pos; - var ch = 0; - state.lastIntValue = 0; - while (isDecimalDigit(ch = state.current())) { - state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); - state.advance(); - } - return state.pos !== start -}; -function isDecimalDigit(ch) { - return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */ -} - -// https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits -pp$9.regexp_eatHexDigits = function(state) { - var start = state.pos; - var ch = 0; - state.lastIntValue = 0; - while (isHexDigit(ch = state.current())) { - state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); - state.advance(); - } - return state.pos !== start -}; -function isHexDigit(ch) { - return ( - (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) || - (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) || - (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) - ) -} -function hexToInt(ch) { - if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) { - return 10 + (ch - 0x41 /* A */) - } - if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) { - return 10 + (ch - 0x61 /* a */) - } - return ch - 0x30 /* 0 */ -} - -// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence -// Allows only 0-377(octal) i.e. 0-255(decimal). -pp$9.regexp_eatLegacyOctalEscapeSequence = function(state) { - if (this.regexp_eatOctalDigit(state)) { - var n1 = state.lastIntValue; - if (this.regexp_eatOctalDigit(state)) { - var n2 = state.lastIntValue; - if (n1 <= 3 && this.regexp_eatOctalDigit(state)) { - state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue; - } else { - state.lastIntValue = n1 * 8 + n2; - } - } else { - state.lastIntValue = n1; - } - return true - } - return false -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit -pp$9.regexp_eatOctalDigit = function(state) { - var ch = state.current(); - if (isOctalDigit(ch)) { - state.lastIntValue = ch - 0x30; /* 0 */ - state.advance(); - return true - } - state.lastIntValue = 0; - return false -}; -function isOctalDigit(ch) { - return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */ -} - -// https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits -// https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit -// And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence -pp$9.regexp_eatFixedHexDigits = function(state, length) { - var start = state.pos; - state.lastIntValue = 0; - for (var i = 0; i < length; ++i) { - var ch = state.current(); - if (!isHexDigit(ch)) { - state.pos = start; - return false - } - state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); - state.advance(); - } - return true -}; - -// 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$8 = Parser.prototype; - -// Move to the next token - -pp$8.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$8.getToken = function() { - this.next(); - return new Token(this) -}; - -// If we're in an ES6 environment, make parsers iterable -if (typeof Symbol !== "undefined") - { pp$8[Symbol.iterator] = function() { - var this$1 = this; - - return { - next: function () { - var token = this$1.getToken(); - return { - done: token.type === types.eof, - value: token - } - } - } - }; } - -// Toggle strict mode. Re-reads the next number or string to please -// pedantic tests (`"use strict"; 010;` should fail). - -pp$8.curContext = function() { - return this.context[this.context.length - 1] -}; - -// Read a single token, updating the parser object's token-related -// properties. - -pp$8.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(types.eof) } - - if (curContext.override) { return curContext.override(this) } - else { this.readToken(this.fullCharCodeAtPos()); } -}; - -pp$8.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$8.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$8.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$8.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 && !isNewLine(ch)) { - 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$8.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: - ++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 { - 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$8.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$8.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(types.ellipsis) - } else { - ++this.pos; - return this.finishToken(types.dot) - } -}; - -pp$8.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(types.assign, 2) } - return this.finishOp(types.slash, 1) -}; - -pp$8.readToken_mult_modulo_exp = function(code) { // '%*' - var next = this.input.charCodeAt(this.pos + 1); - var size = 1; - var tokentype = code === 42 ? types.star : types.modulo; - - // exponentiation operator ** and **= - if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) { - ++size; - tokentype = types.starstar; - next = this.input.charCodeAt(this.pos + 2); - } - - if (next === 61) { return this.finishOp(types.assign, size + 1) } - return this.finishOp(tokentype, size) -}; - -pp$8.readToken_pipe_amp = function(code) { // '|&' - var next = this.input.charCodeAt(this.pos + 1); - if (next === code) { return this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2) } - if (next === 61) { return this.finishOp(types.assign, 2) } - return this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1) -}; - -pp$8.readToken_caret = function() { // '^' - var next = this.input.charCodeAt(this.pos + 1); - if (next === 61) { return this.finishOp(types.assign, 2) } - return this.finishOp(types.bitwiseXOR, 1) -}; - -pp$8.readToken_plus_min = function(code) { // '+-' - var next = this.input.charCodeAt(this.pos + 1); - if (next === code) { - if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 && - (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) { - // A `-->` line comment - this.skipLineComment(3); - this.skipSpace(); - return this.nextToken() - } - return this.finishOp(types.incDec, 2) - } - if (next === 61) { return this.finishOp(types.assign, 2) } - return this.finishOp(types.plusMin, 1) -}; - -pp$8.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(types.assign, size + 1) } - return this.finishOp(types.bitShift, size) - } - if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && - this.input.charCodeAt(this.pos + 3) === 45) { - // `` line comment\n this.skipLineComment(3)\n this.skipSpace()\n return this.nextToken()\n }\n return this.finishOp(tt.incDec, 2)\n }\n if (next === 61) return this.finishOp(tt.assign, 2)\n return this.finishOp(tt.plusMin, 1)\n}\n\npp.readToken_lt_gt = function(code) { // '<>'\n let next = this.input.charCodeAt(this.pos + 1)\n let size = 1\n if (next === code) {\n size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2\n if (this.input.charCodeAt(this.pos + size) === 61) return this.finishOp(tt.assign, size + 1)\n return this.finishOp(tt.bitShift, size)\n }\n if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 &&\n this.input.charCodeAt(this.pos + 3) === 45) {\n // `` line comment - this.skipLineComment(3); - this.skipSpace(); - return this.nextToken() - } - return this.finishOp(types.incDec, 2) - } - if (next === 61) { return this.finishOp(types.assign, 2) } - return this.finishOp(types.plusMin, 1) -}; - -pp$8.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(types.assign, size + 1) } - return this.finishOp(types.bitShift, size) - } - if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && - this.input.charCodeAt(this.pos + 3) === 45) { - // `` line comment\n this.skipLineComment(3)\n this.skipSpace()\n return this.nextToken()\n }\n return this.finishOp(tt.incDec, 2)\n }\n if (next === 61) return this.finishOp(tt.assign, 2)\n return this.finishOp(tt.plusMin, 1)\n}\n\npp.readToken_lt_gt = function(code) { // '<>'\n let next = this.input.charCodeAt(this.pos + 1)\n let size = 1\n if (next === code) {\n size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2\n if (this.input.charCodeAt(this.pos + size) === 61) return this.finishOp(tt.assign, size + 1)\n return this.finishOp(tt.bitShift, size)\n }\n if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 &&\n this.input.charCodeAt(this.pos + 3) === 45) {\n // ` - -[travis-badge]: https://img.shields.io/travis/wooorm/bail.svg - -[travis]: https://travis-ci.org/wooorm/bail - -[codecov-badge]: https://img.shields.io/codecov/c/github/wooorm/bail.svg - -[codecov]: https://codecov.io/github/wooorm/bail - -[npm-install]: https://docs.npmjs.com/cli/install - -[license]: LICENSE - -[author]: http://wooorm.com - -[noop]: https://www.npmjs.com/package/noop - -[noop2]: https://www.npmjs.com/package/noop2 - -[noop3]: https://www.npmjs.com/package/noop3 diff --git a/tools/node_modules/eslint/node_modules/balanced-match/LICENSE.md b/tools/node_modules/eslint/node_modules/balanced-match/LICENSE.md deleted file mode 100644 index 2cdc8e4148cc0a..00000000000000 --- a/tools/node_modules/eslint/node_modules/balanced-match/LICENSE.md +++ /dev/null @@ -1,21 +0,0 @@ -(MIT) - -Copyright (c) 2013 Julian Gruber <julian@juliangruber.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/node_modules/eslint/node_modules/balanced-match/README.md b/tools/node_modules/eslint/node_modules/balanced-match/README.md deleted file mode 100644 index 08e918c0db9a62..00000000000000 --- a/tools/node_modules/eslint/node_modules/balanced-match/README.md +++ /dev/null @@ -1,91 +0,0 @@ -# balanced-match - -Match balanced string pairs, like `{` and `}` or `` and ``. Supports regular expressions as well! - -[![build status](https://secure.travis-ci.org/juliangruber/balanced-match.svg)](http://travis-ci.org/juliangruber/balanced-match) -[![downloads](https://img.shields.io/npm/dm/balanced-match.svg)](https://www.npmjs.org/package/balanced-match) - -[![testling badge](https://ci.testling.com/juliangruber/balanced-match.png)](https://ci.testling.com/juliangruber/balanced-match) - -## Example - -Get the first matching pair of braces: - -```js -var balanced = require('balanced-match'); - -console.log(balanced('{', '}', 'pre{in{nested}}post')); -console.log(balanced('{', '}', 'pre{first}between{second}post')); -console.log(balanced(/\s+\{\s+/, /\s+\}\s+/, 'pre { in{nest} } post')); -``` - -The matches are: - -```bash -$ node example.js -{ start: 3, end: 14, pre: 'pre', body: 'in{nested}', post: 'post' } -{ start: 3, - end: 9, - pre: 'pre', - body: 'first', - post: 'between{second}post' } -{ start: 3, end: 17, pre: 'pre', body: 'in{nest}', post: 'post' } -``` - -## API - -### var m = balanced(a, b, str) - -For the first non-nested matching pair of `a` and `b` in `str`, return an -object with those keys: - -* **start** the index of the first match of `a` -* **end** the index of the matching `b` -* **pre** the preamble, `a` and `b` not included -* **body** the match, `a` and `b` not included -* **post** the postscript, `a` and `b` not included - -If there's no match, `undefined` will be returned. - -If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `['{', 'a', '']` and `{a}}` will match `['', 'a', '}']`. - -### var r = balanced.range(a, b, str) - -For the first non-nested matching pair of `a` and `b` in `str`, return an -array with indexes: `[ , ]`. - -If there's no match, `undefined` will be returned. - -If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `[ 1, 3 ]` and `{a}}` will match `[0, 2]`. - -## Installation - -With [npm](https://npmjs.org) do: - -```bash -npm install balanced-match -``` - -## License - -(MIT) - -Copyright (c) 2013 Julian Gruber <julian@juliangruber.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/node_modules/eslint/node_modules/balanced-match/index.js b/tools/node_modules/eslint/node_modules/balanced-match/index.js deleted file mode 100644 index 1685a762932558..00000000000000 --- a/tools/node_modules/eslint/node_modules/balanced-match/index.js +++ /dev/null @@ -1,59 +0,0 @@ -'use strict'; -module.exports = balanced; -function balanced(a, b, str) { - if (a instanceof RegExp) a = maybeMatch(a, str); - if (b instanceof RegExp) b = maybeMatch(b, str); - - var r = range(a, b, str); - - return r && { - start: r[0], - end: r[1], - pre: str.slice(0, r[0]), - body: str.slice(r[0] + a.length, r[1]), - post: str.slice(r[1] + b.length) - }; -} - -function maybeMatch(reg, str) { - var m = str.match(reg); - return m ? m[0] : null; -} - -balanced.range = range; -function range(a, b, str) { - var begs, beg, left, right, result; - var ai = str.indexOf(a); - var bi = str.indexOf(b, ai + 1); - var i = ai; - - if (ai >= 0 && bi > 0) { - begs = []; - left = str.length; - - while (i >= 0 && !result) { - if (i == ai) { - begs.push(i); - ai = str.indexOf(a, i + 1); - } else if (begs.length == 1) { - result = [ begs.pop(), bi ]; - } else { - beg = begs.pop(); - if (beg < left) { - left = beg; - right = bi; - } - - bi = str.indexOf(b, i + 1); - } - - i = ai < bi && ai >= 0 ? ai : bi; - } - - if (begs.length) { - result = [ left, right ]; - } - } - - return result; -} diff --git a/tools/node_modules/eslint/node_modules/balanced-match/package.json b/tools/node_modules/eslint/node_modules/balanced-match/package.json deleted file mode 100644 index 354df6cf2f70da..00000000000000 --- a/tools/node_modules/eslint/node_modules/balanced-match/package.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "author": { - "name": "Julian Gruber", - "email": "mail@juliangruber.com", - "url": "http://juliangruber.com" - }, - "bugs": { - "url": "https://github.com/juliangruber/balanced-match/issues" - }, - "bundleDependencies": false, - "dependencies": {}, - "deprecated": false, - "description": "Match balanced character pairs, like \"{\" and \"}\"", - "devDependencies": { - "matcha": "^0.7.0", - "tape": "^4.6.0" - }, - "homepage": "https://github.com/juliangruber/balanced-match", - "keywords": [ - "match", - "regexp", - "test", - "balanced", - "parse" - ], - "license": "MIT", - "main": "index.js", - "name": "balanced-match", - "repository": { - "type": "git", - "url": "git://github.com/juliangruber/balanced-match.git" - }, - "scripts": { - "bench": "make bench", - "test": "make test" - }, - "testling": { - "files": "test/*.js", - "browsers": [ - "ie/8..latest", - "firefox/20..latest", - "firefox/nightly", - "chrome/25..latest", - "chrome/canary", - "opera/12..latest", - "opera/next", - "safari/5.1..latest", - "ipad/6.0..latest", - "iphone/6.0..latest", - "android-browser/4.2..latest" - ] - }, - "version": "1.0.0" -} \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/brace-expansion/LICENSE b/tools/node_modules/eslint/node_modules/brace-expansion/LICENSE deleted file mode 100644 index de3226673c3874..00000000000000 --- a/tools/node_modules/eslint/node_modules/brace-expansion/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2013 Julian Gruber - -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/node_modules/eslint/node_modules/brace-expansion/README.md b/tools/node_modules/eslint/node_modules/brace-expansion/README.md deleted file mode 100644 index 6b4e0e16409152..00000000000000 --- a/tools/node_modules/eslint/node_modules/brace-expansion/README.md +++ /dev/null @@ -1,129 +0,0 @@ -# brace-expansion - -[Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html), -as known from sh/bash, in JavaScript. - -[![build status](https://secure.travis-ci.org/juliangruber/brace-expansion.svg)](http://travis-ci.org/juliangruber/brace-expansion) -[![downloads](https://img.shields.io/npm/dm/brace-expansion.svg)](https://www.npmjs.org/package/brace-expansion) -[![Greenkeeper badge](https://badges.greenkeeper.io/juliangruber/brace-expansion.svg)](https://greenkeeper.io/) - -[![testling badge](https://ci.testling.com/juliangruber/brace-expansion.png)](https://ci.testling.com/juliangruber/brace-expansion) - -## Example - -```js -var expand = require('brace-expansion'); - -expand('file-{a,b,c}.jpg') -// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] - -expand('-v{,,}') -// => ['-v', '-v', '-v'] - -expand('file{0..2}.jpg') -// => ['file0.jpg', 'file1.jpg', 'file2.jpg'] - -expand('file-{a..c}.jpg') -// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] - -expand('file{2..0}.jpg') -// => ['file2.jpg', 'file1.jpg', 'file0.jpg'] - -expand('file{0..4..2}.jpg') -// => ['file0.jpg', 'file2.jpg', 'file4.jpg'] - -expand('file-{a..e..2}.jpg') -// => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg'] - -expand('file{00..10..5}.jpg') -// => ['file00.jpg', 'file05.jpg', 'file10.jpg'] - -expand('{{A..C},{a..c}}') -// => ['A', 'B', 'C', 'a', 'b', 'c'] - -expand('ppp{,config,oe{,conf}}') -// => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf'] -``` - -## API - -```js -var expand = require('brace-expansion'); -``` - -### var expanded = expand(str) - -Return an array of all possible and valid expansions of `str`. If none are -found, `[str]` is returned. - -Valid expansions are: - -```js -/^(.*,)+(.+)?$/ -// {a,b,...} -``` - -A comma separated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`. - -```js -/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ -// {x..y[..incr]} -``` - -A numeric sequence from `x` to `y` inclusive, with optional increment. -If `x` or `y` start with a leading `0`, all the numbers will be padded -to have equal length. Negative numbers and backwards iteration work too. - -```js -/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ -// {x..y[..incr]} -``` - -An alphabetic sequence from `x` to `y` inclusive, with optional increment. -`x` and `y` must be exactly one character, and if given, `incr` must be a -number. - -For compatibility reasons, the string `${` is not eligible for brace expansion. - -## Installation - -With [npm](https://npmjs.org) do: - -```bash -npm install brace-expansion -``` - -## Contributors - -- [Julian Gruber](https://github.com/juliangruber) -- [Isaac Z. Schlueter](https://github.com/isaacs) - -## Sponsors - -This module is proudly supported by my [Sponsors](https://github.com/juliangruber/sponsors)! - -Do you want to support modules like this to improve their quality, stability and weigh in on new features? Then please consider donating to my [Patreon](https://www.patreon.com/juliangruber). Not sure how much of my modules you're using? Try [feross/thanks](https://github.com/feross/thanks)! - -## License - -(MIT) - -Copyright (c) 2013 Julian Gruber <julian@juliangruber.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/node_modules/eslint/node_modules/brace-expansion/index.js b/tools/node_modules/eslint/node_modules/brace-expansion/index.js deleted file mode 100644 index 0478be81eabc2b..00000000000000 --- a/tools/node_modules/eslint/node_modules/brace-expansion/index.js +++ /dev/null @@ -1,201 +0,0 @@ -var concatMap = require('concat-map'); -var balanced = require('balanced-match'); - -module.exports = expandTop; - -var escSlash = '\0SLASH'+Math.random()+'\0'; -var escOpen = '\0OPEN'+Math.random()+'\0'; -var escClose = '\0CLOSE'+Math.random()+'\0'; -var escComma = '\0COMMA'+Math.random()+'\0'; -var escPeriod = '\0PERIOD'+Math.random()+'\0'; - -function numeric(str) { - return parseInt(str, 10) == str - ? parseInt(str, 10) - : str.charCodeAt(0); -} - -function escapeBraces(str) { - return str.split('\\\\').join(escSlash) - .split('\\{').join(escOpen) - .split('\\}').join(escClose) - .split('\\,').join(escComma) - .split('\\.').join(escPeriod); -} - -function unescapeBraces(str) { - return str.split(escSlash).join('\\') - .split(escOpen).join('{') - .split(escClose).join('}') - .split(escComma).join(',') - .split(escPeriod).join('.'); -} - - -// Basically just str.split(","), but handling cases -// where we have nested braced sections, which should be -// treated as individual members, like {a,{b,c},d} -function parseCommaParts(str) { - if (!str) - return ['']; - - var parts = []; - var m = balanced('{', '}', str); - - if (!m) - return str.split(','); - - var pre = m.pre; - var body = m.body; - var post = m.post; - var p = pre.split(','); - - p[p.length-1] += '{' + body + '}'; - var postParts = parseCommaParts(post); - if (post.length) { - p[p.length-1] += postParts.shift(); - p.push.apply(p, postParts); - } - - parts.push.apply(parts, p); - - return parts; -} - -function expandTop(str) { - if (!str) - return []; - - // I don't know why Bash 4.3 does this, but it does. - // Anything starting with {} will have the first two bytes preserved - // but *only* at the top level, so {},a}b will not expand to anything, - // but a{},b}c will be expanded to [a}c,abc]. - // One could argue that this is a bug in Bash, but since the goal of - // this module is to match Bash's rules, we escape a leading {} - if (str.substr(0, 2) === '{}') { - str = '\\{\\}' + str.substr(2); - } - - return expand(escapeBraces(str), true).map(unescapeBraces); -} - -function identity(e) { - return e; -} - -function embrace(str) { - return '{' + str + '}'; -} -function isPadded(el) { - return /^-?0\d/.test(el); -} - -function lte(i, y) { - return i <= y; -} -function gte(i, y) { - return i >= y; -} - -function expand(str, isTop) { - var expansions = []; - - var m = balanced('{', '}', str); - if (!m || /\$$/.test(m.pre)) return [str]; - - var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); - var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); - var isSequence = isNumericSequence || isAlphaSequence; - var isOptions = m.body.indexOf(',') >= 0; - if (!isSequence && !isOptions) { - // {a},b} - if (m.post.match(/,.*\}/)) { - str = m.pre + '{' + m.body + escClose + m.post; - return expand(str); - } - return [str]; - } - - var n; - if (isSequence) { - n = m.body.split(/\.\./); - } else { - n = parseCommaParts(m.body); - if (n.length === 1) { - // x{{a,b}}y ==> x{a}y x{b}y - n = expand(n[0], false).map(embrace); - if (n.length === 1) { - var post = m.post.length - ? expand(m.post, false) - : ['']; - return post.map(function(p) { - return m.pre + n[0] + p; - }); - } - } - } - - // at this point, n is the parts, and we know it's not a comma set - // with a single entry. - - // no need to expand pre, since it is guaranteed to be free of brace-sets - var pre = m.pre; - var post = m.post.length - ? expand(m.post, false) - : ['']; - - var N; - - if (isSequence) { - var x = numeric(n[0]); - var y = numeric(n[1]); - var width = Math.max(n[0].length, n[1].length) - var incr = n.length == 3 - ? Math.abs(numeric(n[2])) - : 1; - var test = lte; - var reverse = y < x; - if (reverse) { - incr *= -1; - test = gte; - } - var pad = n.some(isPadded); - - N = []; - - for (var i = x; test(i, y); i += incr) { - var c; - if (isAlphaSequence) { - c = String.fromCharCode(i); - if (c === '\\') - c = ''; - } else { - c = String(i); - if (pad) { - var need = width - c.length; - if (need > 0) { - var z = new Array(need + 1).join('0'); - if (i < 0) - c = '-' + z + c.slice(1); - else - c = z + c; - } - } - } - N.push(c); - } - } else { - N = concatMap(n, function(el) { return expand(el, false) }); - } - - for (var j = 0; j < N.length; j++) { - for (var k = 0; k < post.length; k++) { - var expansion = pre + N[j] + post[k]; - if (!isTop || isSequence || expansion) - expansions.push(expansion); - } - } - - return expansions; -} - diff --git a/tools/node_modules/eslint/node_modules/brace-expansion/package.json b/tools/node_modules/eslint/node_modules/brace-expansion/package.json deleted file mode 100644 index af3bc67cac86e1..00000000000000 --- a/tools/node_modules/eslint/node_modules/brace-expansion/package.json +++ /dev/null @@ -1,52 +0,0 @@ -{ - "author": { - "name": "Julian Gruber", - "email": "mail@juliangruber.com", - "url": "http://juliangruber.com" - }, - "bugs": { - "url": "https://github.com/juliangruber/brace-expansion/issues" - }, - "bundleDependencies": false, - "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - }, - "deprecated": false, - "description": "Brace expansion as known from sh/bash", - "devDependencies": { - "matcha": "^0.7.0", - "tape": "^4.6.0" - }, - "homepage": "https://github.com/juliangruber/brace-expansion", - "keywords": [], - "license": "MIT", - "main": "index.js", - "name": "brace-expansion", - "repository": { - "type": "git", - "url": "git://github.com/juliangruber/brace-expansion.git" - }, - "scripts": { - "bench": "matcha test/perf/bench.js", - "gentest": "bash test/generate.sh", - "test": "tape test/*.js" - }, - "testling": { - "files": "test/*.js", - "browsers": [ - "ie/8..latest", - "firefox/20..latest", - "firefox/nightly", - "chrome/25..latest", - "chrome/canary", - "opera/12..latest", - "opera/next", - "safari/5.1..latest", - "ipad/6.0..latest", - "iphone/6.0..latest", - "android-browser/4.2..latest" - ] - }, - "version": "1.1.11" -} \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/callsites/index.js b/tools/node_modules/eslint/node_modules/callsites/index.js deleted file mode 100644 index c408fc8091bd3f..00000000000000 --- a/tools/node_modules/eslint/node_modules/callsites/index.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; - -const callsites = () => { - const _prepareStackTrace = Error.prepareStackTrace; - Error.prepareStackTrace = (_, stack) => stack; - const stack = new Error().stack.slice(1); - Error.prepareStackTrace = _prepareStackTrace; - return stack; -}; - -module.exports = callsites; -module.exports.default = callsites; diff --git a/tools/node_modules/eslint/node_modules/callsites/license b/tools/node_modules/eslint/node_modules/callsites/license deleted file mode 100644 index e7af2f77107d73..00000000000000 --- a/tools/node_modules/eslint/node_modules/callsites/license +++ /dev/null @@ -1,9 +0,0 @@ -MIT License - -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/node_modules/eslint/node_modules/callsites/package.json b/tools/node_modules/eslint/node_modules/callsites/package.json deleted file mode 100644 index d0b8df24d1859a..00000000000000 --- a/tools/node_modules/eslint/node_modules/callsites/package.json +++ /dev/null @@ -1,48 +0,0 @@ -{ - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" - }, - "bugs": { - "url": "https://github.com/sindresorhus/callsites/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Get callsites from the V8 stack trace API", - "devDependencies": { - "ava": "^0.25.0", - "tsd-check": "^0.2.1", - "xo": "^0.23.0" - }, - "engines": { - "node": ">=6" - }, - "files": [ - "index.js", - "index.d.ts" - ], - "homepage": "https://github.com/sindresorhus/callsites#readme", - "keywords": [ - "stacktrace", - "v8", - "callsite", - "callsites", - "stack", - "trace", - "function", - "file", - "line", - "debug" - ], - "license": "MIT", - "name": "callsites", - "repository": { - "type": "git", - "url": "git+https://github.com/sindresorhus/callsites.git" - }, - "scripts": { - "test": "xo && ava && tsd-check" - }, - "version": "3.0.0" -} \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/callsites/readme.md b/tools/node_modules/eslint/node_modules/callsites/readme.md deleted file mode 100644 index fc846138f4a80d..00000000000000 --- a/tools/node_modules/eslint/node_modules/callsites/readme.md +++ /dev/null @@ -1,48 +0,0 @@ -# callsites [![Build Status](https://travis-ci.org/sindresorhus/callsites.svg?branch=master)](https://travis-ci.org/sindresorhus/callsites) - -> Get callsites from the [V8 stack trace API](https://v8.dev/docs/stack-trace-api) - - -## Install - -``` -$ npm install callsites -``` - - -## Usage - -```js -const callsites = require('callsites'); - -function unicorn() { - console.log(callsites()[0].getFileName()); - //=> '/Users/sindresorhus/dev/callsites/test.js' -} - -unicorn(); -``` - - -## API - -Returns an array of callsite objects with the following methods: - -- `getThis`: returns the value of `this`. -- `getTypeName`: returns the type of `this` as a string. This is the name of the function stored in the constructor field of `this`, if available, otherwise the object's `[[Class]]` internal property. -- `getFunction`: returns the current function. -- `getFunctionName`: returns the name of the current function, typically its `name` property. If a name property is not available an attempt will be made to try to infer a name from the function's context. -- `getMethodName`: returns the name of the property of `this` or one of its prototypes that holds the current function. -- `getFileName`: if this function was defined in a script returns the name of the script. -- `getLineNumber`: if this function was defined in a script returns the current line number. -- `getColumnNumber`: if this function was defined in a script returns the current column number -- `getEvalOrigin`: if this function was created using a call to `eval` returns a string representing the location where `eval` was called. -- `isToplevel`: is this a top-level invocation, that is, is this the global object? -- `isEval`: does this call take place in code defined by a call to `eval`? -- `isNative`: is this call in native V8 code? -- `isConstructor`: is this a constructor call? - - -## License - -MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/tools/node_modules/eslint/node_modules/chalk/index.js b/tools/node_modules/eslint/node_modules/chalk/index.js deleted file mode 100644 index 1cc5fa89a95159..00000000000000 --- a/tools/node_modules/eslint/node_modules/chalk/index.js +++ /dev/null @@ -1,228 +0,0 @@ -'use strict'; -const escapeStringRegexp = require('escape-string-regexp'); -const ansiStyles = require('ansi-styles'); -const stdoutColor = require('supports-color').stdout; - -const template = require('./templates.js'); - -const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); - -// `supportsColor.level` → `ansiStyles.color[name]` mapping -const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; - -// `color-convert` models to exclude from the Chalk API due to conflicts and such -const skipModels = new Set(['gray']); - -const styles = Object.create(null); - -function applyOptions(obj, options) { - options = options || {}; - - // Detect level if not set manually - const scLevel = stdoutColor ? stdoutColor.level : 0; - obj.level = options.level === undefined ? scLevel : options.level; - obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0; -} - -function Chalk(options) { - // We check for this.template here since calling `chalk.constructor()` - // by itself will have a `this` of a previously constructed chalk object - if (!this || !(this instanceof Chalk) || this.template) { - const chalk = {}; - applyOptions(chalk, options); - - chalk.template = function () { - const args = [].slice.call(arguments); - return chalkTag.apply(null, [chalk.template].concat(args)); - }; - - Object.setPrototypeOf(chalk, Chalk.prototype); - Object.setPrototypeOf(chalk.template, chalk); - - chalk.template.constructor = Chalk; - - return chalk.template; - } - - applyOptions(this, options); -} - -// Use bright blue on Windows as the normal blue color is illegible -if (isSimpleWindowsTerm) { - ansiStyles.blue.open = '\u001B[94m'; -} - -for (const key of Object.keys(ansiStyles)) { - ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); - - styles[key] = { - get() { - const codes = ansiStyles[key]; - return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key); - } - }; -} - -styles.visible = { - get() { - return build.call(this, this._styles || [], true, 'visible'); - } -}; - -ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g'); -for (const model of Object.keys(ansiStyles.color.ansi)) { - if (skipModels.has(model)) { - continue; - } - - styles[model] = { - get() { - const level = this.level; - return function () { - const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments); - const codes = { - open, - close: ansiStyles.color.close, - closeRe: ansiStyles.color.closeRe - }; - return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); - }; - } - }; -} - -ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g'); -for (const model of Object.keys(ansiStyles.bgColor.ansi)) { - if (skipModels.has(model)) { - continue; - } - - const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); - styles[bgModel] = { - get() { - const level = this.level; - return function () { - const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments); - const codes = { - open, - close: ansiStyles.bgColor.close, - closeRe: ansiStyles.bgColor.closeRe - }; - return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); - }; - } - }; -} - -const proto = Object.defineProperties(() => {}, styles); - -function build(_styles, _empty, key) { - const builder = function () { - return applyStyle.apply(builder, arguments); - }; - - builder._styles = _styles; - builder._empty = _empty; - - const self = this; - - Object.defineProperty(builder, 'level', { - enumerable: true, - get() { - return self.level; - }, - set(level) { - self.level = level; - } - }); - - Object.defineProperty(builder, 'enabled', { - enumerable: true, - get() { - return self.enabled; - }, - set(enabled) { - self.enabled = enabled; - } - }); - - // See below for fix regarding invisible grey/dim combination on Windows - builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; - - // `__proto__` is used because we must return a function, but there is - // no way to create a function with a different prototype - builder.__proto__ = proto; // eslint-disable-line no-proto - - return builder; -} - -function applyStyle() { - // Support varags, but simply cast to string in case there's only one arg - const args = arguments; - const argsLen = args.length; - let str = String(arguments[0]); - - if (argsLen === 0) { - return ''; - } - - if (argsLen > 1) { - // Don't slice `arguments`, it prevents V8 optimizations - for (let a = 1; a < argsLen; a++) { - str += ' ' + args[a]; - } - } - - if (!this.enabled || this.level <= 0 || !str) { - return this._empty ? '' : str; - } - - // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, - // see https://github.com/chalk/chalk/issues/58 - // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. - const originalDim = ansiStyles.dim.open; - if (isSimpleWindowsTerm && this.hasGrey) { - ansiStyles.dim.open = ''; - } - - for (const code of this._styles.slice().reverse()) { - // Replace any instances already present with a re-opening code - // otherwise only the part of the string until said closing code - // will be colored, and the rest will simply be 'plain'. - str = code.open + str.replace(code.closeRe, code.open) + code.close; - - // Close the styling before a linebreak and reopen - // after next line to fix a bleed issue on macOS - // https://github.com/chalk/chalk/pull/92 - str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`); - } - - // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue - ansiStyles.dim.open = originalDim; - - return str; -} - -function chalkTag(chalk, strings) { - if (!Array.isArray(strings)) { - // If chalk() was called by itself or with a string, - // return the string itself as a string. - return [].slice.call(arguments, 1).join(' '); - } - - const args = [].slice.call(arguments, 2); - const parts = [strings.raw[0]]; - - for (let i = 1; i < strings.length; i++) { - parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&')); - parts.push(String(strings.raw[i])); - } - - return template(chalk, parts.join('')); -} - -Object.defineProperties(Chalk.prototype, styles); - -module.exports = Chalk(); // eslint-disable-line new-cap -module.exports.supportsColor = stdoutColor; -module.exports.default = module.exports; // For TypeScript diff --git a/tools/node_modules/eslint/node_modules/chalk/index.js.flow b/tools/node_modules/eslint/node_modules/chalk/index.js.flow deleted file mode 100644 index 622caaa2e803f3..00000000000000 --- a/tools/node_modules/eslint/node_modules/chalk/index.js.flow +++ /dev/null @@ -1,93 +0,0 @@ -// @flow strict - -type TemplateStringsArray = $ReadOnlyArray; - -export type Level = $Values<{ - None: 0, - Basic: 1, - Ansi256: 2, - TrueColor: 3 -}>; - -export type ChalkOptions = {| - enabled?: boolean, - level?: Level -|}; - -export type ColorSupport = {| - level: Level, - hasBasic: boolean, - has256: boolean, - has16m: boolean -|}; - -export interface Chalk { - (...text: string[]): string, - (text: TemplateStringsArray, ...placeholders: string[]): string, - constructor(options?: ChalkOptions): Chalk, - enabled: boolean, - level: Level, - rgb(r: number, g: number, b: number): Chalk, - hsl(h: number, s: number, l: number): Chalk, - hsv(h: number, s: number, v: number): Chalk, - hwb(h: number, w: number, b: number): Chalk, - bgHex(color: string): Chalk, - bgKeyword(color: string): Chalk, - bgRgb(r: number, g: number, b: number): Chalk, - bgHsl(h: number, s: number, l: number): Chalk, - bgHsv(h: number, s: number, v: number): Chalk, - bgHwb(h: number, w: number, b: number): Chalk, - hex(color: string): Chalk, - keyword(color: string): Chalk, - - +reset: Chalk, - +bold: Chalk, - +dim: Chalk, - +italic: Chalk, - +underline: Chalk, - +inverse: Chalk, - +hidden: Chalk, - +strikethrough: Chalk, - - +visible: Chalk, - - +black: Chalk, - +red: Chalk, - +green: Chalk, - +yellow: Chalk, - +blue: Chalk, - +magenta: Chalk, - +cyan: Chalk, - +white: Chalk, - +gray: Chalk, - +grey: Chalk, - +blackBright: Chalk, - +redBright: Chalk, - +greenBright: Chalk, - +yellowBright: Chalk, - +blueBright: Chalk, - +magentaBright: Chalk, - +cyanBright: Chalk, - +whiteBright: Chalk, - - +bgBlack: Chalk, - +bgRed: Chalk, - +bgGreen: Chalk, - +bgYellow: Chalk, - +bgBlue: Chalk, - +bgMagenta: Chalk, - +bgCyan: Chalk, - +bgWhite: Chalk, - +bgBlackBright: Chalk, - +bgRedBright: Chalk, - +bgGreenBright: Chalk, - +bgYellowBright: Chalk, - +bgBlueBright: Chalk, - +bgMagentaBright: Chalk, - +bgCyanBright: Chalk, - +bgWhiteBrigh: Chalk, - - supportsColor: ColorSupport -}; - -declare module.exports: Chalk; diff --git a/tools/node_modules/eslint/node_modules/chalk/license b/tools/node_modules/eslint/node_modules/chalk/license deleted file mode 100644 index e7af2f77107d73..00000000000000 --- a/tools/node_modules/eslint/node_modules/chalk/license +++ /dev/null @@ -1,9 +0,0 @@ -MIT License - -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/node_modules/eslint/node_modules/chalk/package.json b/tools/node_modules/eslint/node_modules/chalk/package.json deleted file mode 100644 index 270fecdc347d42..00000000000000 --- a/tools/node_modules/eslint/node_modules/chalk/package.json +++ /dev/null @@ -1,80 +0,0 @@ -{ - "bugs": { - "url": "https://github.com/chalk/chalk/issues" - }, - "bundleDependencies": false, - "dependencies": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - }, - "deprecated": false, - "description": "Terminal string styling done right", - "devDependencies": { - "ava": "*", - "coveralls": "^3.0.0", - "execa": "^0.9.0", - "flow-bin": "^0.68.0", - "import-fresh": "^2.0.0", - "matcha": "^0.7.0", - "nyc": "^11.0.2", - "resolve-from": "^4.0.0", - "typescript": "^2.5.3", - "xo": "*" - }, - "engines": { - "node": ">=4" - }, - "files": [ - "index.js", - "templates.js", - "types/index.d.ts", - "index.js.flow" - ], - "homepage": "https://github.com/chalk/chalk#readme", - "keywords": [ - "color", - "colour", - "colors", - "terminal", - "console", - "cli", - "string", - "str", - "ansi", - "style", - "styles", - "tty", - "formatting", - "rgb", - "256", - "shell", - "xterm", - "log", - "logging", - "command-line", - "text" - ], - "license": "MIT", - "name": "chalk", - "repository": { - "type": "git", - "url": "git+https://github.com/chalk/chalk.git" - }, - "scripts": { - "bench": "matcha benchmark.js", - "coveralls": "nyc report --reporter=text-lcov | coveralls", - "test": "xo && tsc --project types && flow --max-warnings=0 && nyc ava" - }, - "types": "types/index.d.ts", - "version": "2.4.2", - "xo": { - "envs": [ - "node", - "mocha" - ], - "ignores": [ - "test/_flow.js" - ] - } -} \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/chalk/readme.md b/tools/node_modules/eslint/node_modules/chalk/readme.md deleted file mode 100644 index d298e2c48d64a0..00000000000000 --- a/tools/node_modules/eslint/node_modules/chalk/readme.md +++ /dev/null @@ -1,314 +0,0 @@ -

-
-
- Chalk -
-
-
-

- -> Terminal string styling done right - -[![Build Status](https://travis-ci.org/chalk/chalk.svg?branch=master)](https://travis-ci.org/chalk/chalk) [![Coverage Status](https://coveralls.io/repos/github/chalk/chalk/badge.svg?branch=master)](https://coveralls.io/github/chalk/chalk?branch=master) [![](https://img.shields.io/badge/unicorn-approved-ff69b4.svg)](https://www.youtube.com/watch?v=9auOCbH5Ns4) [![XO code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/xojs/xo) [![Mentioned in Awesome Node.js](https://awesome.re/mentioned-badge.svg)](https://github.com/sindresorhus/awesome-nodejs) - -### [See what's new in Chalk 2](https://github.com/chalk/chalk/releases/tag/v2.0.0) - - - - -## Highlights - -- Expressive API -- Highly performant -- Ability to nest styles -- [256/Truecolor color support](#256-and-truecolor-color-support) -- Auto-detects color support -- Doesn't extend `String.prototype` -- Clean and focused -- Actively maintained -- [Used by ~23,000 packages](https://www.npmjs.com/browse/depended/chalk) as of December 31, 2017 - - -## Install - -```console -$ npm install chalk -``` - -
- - - - -## Usage - -```js -const chalk = require('chalk'); - -console.log(chalk.blue('Hello world!')); -``` - -Chalk comes with an easy to use composable API where you just chain and nest the styles you want. - -```js -const chalk = require('chalk'); -const log = console.log; - -// Combine styled and normal strings -log(chalk.blue('Hello') + ' World' + chalk.red('!')); - -// Compose multiple styles using the chainable API -log(chalk.blue.bgRed.bold('Hello world!')); - -// Pass in multiple arguments -log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz')); - -// Nest styles -log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!')); - -// Nest styles of the same type even (color, underline, background) -log(chalk.green( - 'I am a green line ' + - chalk.blue.underline.bold('with a blue substring') + - ' that becomes green again!' -)); - -// ES2015 template literal -log(` -CPU: ${chalk.red('90%')} -RAM: ${chalk.green('40%')} -DISK: ${chalk.yellow('70%')} -`); - -// ES2015 tagged template literal -log(chalk` -CPU: {red ${cpu.totalPercent}%} -RAM: {green ${ram.used / ram.total * 100}%} -DISK: {rgb(255,131,0) ${disk.used / disk.total * 100}%} -`); - -// Use RGB colors in terminal emulators that support it. -log(chalk.keyword('orange')('Yay for orange colored text!')); -log(chalk.rgb(123, 45, 67).underline('Underlined reddish color')); -log(chalk.hex('#DEADED').bold('Bold gray!')); -``` - -Easily define your own themes: - -```js -const chalk = require('chalk'); - -const error = chalk.bold.red; -const warning = chalk.keyword('orange'); - -console.log(error('Error!')); -console.log(warning('Warning!')); -``` - -Take advantage of console.log [string substitution](https://nodejs.org/docs/latest/api/console.html#console_console_log_data_args): - -```js -const name = 'Sindre'; -console.log(chalk.green('Hello %s'), name); -//=> 'Hello Sindre' -``` - - -## API - -### chalk.`