diff --git a/tools/node_modules/eslint/README.md b/tools/node_modules/eslint/README.md index 172c956add7540..163f008944bd90 100644 --- a/tools/node_modules/eslint/README.md +++ b/tools/node_modules/eslint/README.md @@ -24,15 +24,25 @@ ESLint is a tool for identifying and reporting on patterns found in ECMAScript/J * ESLint uses an AST to evaluate patterns in code. * ESLint is completely pluggable, every single rule is a plugin and you can add more at runtime. -## Installation and Usage +## Table of Contents -Prerequisites: [Node.js](https://nodejs.org/en/) (>=6.14), npm version 3+. +1. [Installation and Usage](#installation-and-usage) +2. [Configuration](#configuration) +3. [Code of Conduct](#code-of-conduct) +4. [Filing Issues](#filing-issues) +5. [Frequently Asked Questions](#faq) +6. [Releases](#releases) +7. [Semantic Versioning Policy](#semantic-versioning-policy) +8. [License](#license) +9. [Team](#team) +10. [Sponsors](#sponsors) +11. [Technology Sponsors](#technology-sponsors) -There are two ways to install ESLint: globally and locally. +## Installation and Usage -### Local Installation and Usage +Prerequisites: [Node.js](https://nodejs.org/) (`^8.10.0`, `^10.13.0`, or `>=11.10.1`), npm version 3+. -If you want to include ESLint as part of your project's build system, we recommend installing it locally. You can do so using npm: +You can install ESLint using npm: ``` $ npm install eslint --save-dev @@ -50,33 +60,9 @@ After that, you can run ESLint on any file or directory like this: $ ./node_modules/.bin/eslint yourfile.js ``` -Any plugins or shareable configs that you use must also be installed locally to work with a locally-installed ESLint. +It is also possible to install ESLint globally rather than locally (using `npm install eslint --global`). However, any plugins or shareable configs that you use must be installed locally in either case. -### Global Installation and Usage - -If you want to make ESLint available to tools that run across all of your projects, we recommend installing ESLint globally. You can do so using npm: - -``` -$ npm install -g eslint -``` - -You should then set up a configuration file: - -``` -$ eslint --init -``` - -After that, you can run ESLint on any file or directory like this: - -``` -$ eslint yourfile.js -``` - -Any plugins or shareable configs that you use must also be installed globally to work with a globally-installed ESLint. - -**Note:** `eslint --init` is intended for setting up and configuring ESLint on a per-project basis and will perform a local installation of ESLint and its plugins in the directory in which it is run. If you prefer using a global installation of ESLint, any plugins used in your configuration must also be installed globally. - -## Configuration +## Configuration After running `eslint --init`, you'll have a `.eslintrc` file in your directory. In it, you'll see some rules configured like this: @@ -97,11 +83,11 @@ The names `"semi"` and `"quotes"` are the names of [rules](https://eslint.org/do The three error levels allow you fine-grained control over how ESLint applies rules (for more configuration options and details, see the [configuration docs](https://eslint.org/docs/user-guide/configuring)). -## Code of Conduct +## Code of Conduct ESLint adheres to the [JS Foundation Code of Conduct](https://js.foundation/community/code-of-conduct). -## Filing Issues +## Filing Issues Before filing an issue, please be sure to read the guidelines for what you're reporting: @@ -110,13 +96,15 @@ Before filing an issue, please be sure to read the guidelines for what you're re * [Proposing a Rule Change](https://eslint.org/docs/developer-guide/contributing/rule-changes) * [Request a Change](https://eslint.org/docs/developer-guide/contributing/changes) -## Frequently Asked Questions +## Frequently Asked Questions ### I'm using JSCS, should I migrate to ESLint? -Maybe, depending on how much you need it. [JSCS has reached end of life](https://eslint.org/blog/2016/07/jscs-end-of-life), but if it is working for you then there is no reason to move yet. There are still [a few issues](https://github.com/eslint/eslint/milestones/JSCS%20Compatibility) pending. We’ll announce when all of the changes necessary to support JSCS users in ESLint are complete and will start encouraging JSCS users to switch to ESLint at that time. +Yes. [JSCS has reached end of life](https://eslint.org/blog/2016/07/jscs-end-of-life) and is no longer supported. -If you are having issues with JSCS, you can try to move to ESLint. Have a look at our [migration guide](https://eslint.org/docs/user-guide/migrating-from-jscs). +We have prepared a [migration guide](https://eslint.org/docs/user-guide/migrating-from-jscs) to help you convert your JSCS settings to an ESLint configuration. + +We are now at or near 100% compatibility with JSCS. If you try ESLint and believe we are not yet compatible with a JSCS rule/configuration, please create an issue (mentioning that it is a JSCS compatibility issue) and we will evaluate it as per our normal process. ### Does Prettier replace ESLint? @@ -124,16 +112,9 @@ No, ESLint does both traditional linting (looking for problematic patterns) and ### Why can't ESLint find my plugins? -ESLint can be [globally or locally installed](#installation-and-usage). If you install ESLint globally, your plugins must also be installed globally; if you install ESLint locally, your plugins must also be installed locally. - -If you are trying to run globally, make sure your plugins are installed globally (use `npm ls -g`). - -If you are trying to run locally: - * Make sure your plugins (and ESLint) are both in your project's `package.json` as devDependencies (or dependencies, if your project uses ESLint at runtime). * Make sure you have run `npm install` and all your dependencies are installed. - -In all cases, make sure your plugins' peerDependencies have been installed as well. You can use `npm view eslint-plugin-myplugin peerDependencies` to see what peer dependencies `eslint-plugin-myplugin` has. +* Make sure your plugins' peerDependencies have been installed as well. You can use `npm view eslint-plugin-myplugin peerDependencies` to see what peer dependencies `eslint-plugin-myplugin` has. ### Does ESLint support JSX? @@ -155,11 +136,11 @@ Once a language feature has been adopted into the ECMAScript standard (stage 4 a Join our [Mailing List](https://groups.google.com/group/eslint) or [Chatroom](https://gitter.im/eslint/eslint). -## Releases +## Releases We have scheduled releases every two weeks on Friday or Saturday. You can follow a [release issue](https://github.com/eslint/eslint/issues?q=is%3Aopen+is%3Aissue+label%3Arelease) for updates about the scheduling of any particular release. -## Semantic Versioning Policy +## Semantic Versioning Policy ESLint follows [semantic versioning](https://semver.org). However, due to the nature of ESLint as a code quality tool, it's not always clear when a minor or major version bump occurs. To help clarify this for everyone, we've defined the following semantic versioning policy for ESLint: @@ -185,11 +166,11 @@ ESLint follows [semantic versioning](https://semver.org). However, due to the na According to our policy, any minor update may report more errors than the previous release (ex: from a bug fix). As such, we recommend using the tilde (`~`) in `package.json` e.g. `"eslint": "~3.1.0"` to guarantee the results of your builds. -## License +## License [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Feslint%2Feslint.svg?type=large)](https://app.fossa.io/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Feslint%2Feslint?ref=badge_large) -## Team +## Team These folks keep the project moving and are resources for help. @@ -243,18 +224,25 @@ Teddy Katz +### Reviewers - -### Committers - -The people who review and fix bugs and help triage issues. +The people who review and implement new features.

薛定谔的猫
-
+
+ + + + +### Committers + +The people who review and fix bugs and help triage issues. + +

Pig Fang @@ -264,19 +252,19 @@ Pig Fang -## Sponsors +##
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

-

Airbnb Facebook Open Source Badoo

Silver Sponsors

-

AMP Project

Bronze Sponsors

-

Faithlife JSHeroes

+

Salesforce Airbnb Facebook Open Source Badoo Shopify

Silver Sponsors

+

AMP Project

Bronze Sponsors

+

Usave TekHattan Faithlife ThemeIsle Marfeel clay Discord JSHeroes Fire Stick Tricks

-## Technology Sponsors +## Technology Sponsors * Site search ([eslint.org](https://eslint.org)) is sponsored by [Algolia](https://www.algolia.com) diff --git a/tools/node_modules/eslint/bin/eslint.js b/tools/node_modules/eslint/bin/eslint.js index e51121ec6afe7f..1c41bafd24539e 100755 --- a/tools/node_modules/eslint/bin/eslint.js +++ b/tools/node_modules/eslint/bin/eslint.js @@ -65,7 +65,7 @@ if (useStdIn) { process.exitCode = cli.execute(process.argv, fs.readFileSync(STDIN_FILE_DESCRIPTOR, "utf8")); } else if (init) { - const configInit = require("../lib/config/config-initializer"); + const configInit = require("../lib/init/config-initializer"); configInit.initializeConfig().then(() => { process.exitCode = 0; diff --git a/tools/node_modules/eslint/conf/config-schema.js b/tools/node_modules/eslint/conf/config-schema.js index 626e1d54c520cc..36f3c27de6007e 100644 --- a/tools/node_modules/eslint/conf/config-schema.js +++ b/tools/node_modules/eslint/conf/config-schema.js @@ -7,64 +7,71 @@ const baseConfigProperties = { env: { type: "object" }, + extends: { $ref: "#/definitions/stringOrStrings" }, globals: { type: "object" }, + overrides: { + type: "array", + items: { $ref: "#/definitions/overrideConfig" }, + additionalItems: false + }, parser: { type: ["string", "null"] }, parserOptions: { type: "object" }, plugins: { type: "array" }, + processor: { type: "string" }, rules: { type: "object" }, settings: { type: "object" }, ecmaFeatures: { type: "object" } // deprecated; logs a warning when used }; -const overrideProperties = Object.assign( - {}, - baseConfigProperties, - { - files: { +const configSchema = { + definitions: { + stringOrStrings: { oneOf: [ { type: "string" }, { type: "array", items: { type: "string" }, - minItems: 1 + additionalItems: false } ] }, - excludedFiles: { + stringOrStringsRequired: { oneOf: [ { type: "string" }, { type: "array", - items: { type: "string" } + items: { type: "string" }, + additionalItems: false, + minItems: 1 } ] - } - } -); + }, + + // Config at top-level. + objectConfig: { + type: "object", + properties: { + root: { type: "boolean" }, + ...baseConfigProperties + }, + additionalProperties: false + }, -const topLevelConfigProperties = Object.assign( - {}, - baseConfigProperties, - { - extends: { type: ["string", "array"] }, - root: { type: "boolean" }, - overrides: { - type: "array", - items: { - type: "object", - properties: overrideProperties, - required: ["files"], - additionalProperties: false - } + // Config in `overrides`. + overrideConfig: { + type: "object", + properties: { + excludedFiles: { $ref: "#/definitions/stringOrStrings" }, + files: { $ref: "#/definitions/stringOrStringsRequired" }, + ...baseConfigProperties + }, + required: ["files"], + additionalProperties: false } - } -); + }, -const configSchema = { - type: "object", - properties: topLevelConfigProperties, - additionalProperties: false + $ref: "#/definitions/objectConfig" }; module.exports = configSchema; diff --git a/tools/node_modules/eslint/conf/environments.js b/tools/node_modules/eslint/conf/environments.js index 1c2b12eed31bb5..f77340cea27c75 100644 --- a/tools/node_modules/eslint/conf/environments.js +++ b/tools/node_modules/eslint/conf/environments.js @@ -14,7 +14,8 @@ const globals = require("globals"); // Public Interface //------------------------------------------------------------------------------ -module.exports = { +/** @type {Map} */ +module.exports = new Map(Object.entries({ builtin: { globals: globals.es5 }, @@ -106,4 +107,4 @@ module.exports = { greasemonkey: { globals: globals.greasemonkey } -}; +})); diff --git a/tools/node_modules/eslint/conf/eslint-all.js b/tools/node_modules/eslint/conf/eslint-all.js index 3850fcea3abb1c..10c5304fd3f243 100644 --- a/tools/node_modules/eslint/conf/eslint-all.js +++ b/tools/node_modules/eslint/conf/eslint-all.js @@ -9,21 +9,23 @@ // Requirements //------------------------------------------------------------------------------ -const builtInRules = require("../lib/built-in-rules-index"); +const builtInRules = require("../lib/rules"); //------------------------------------------------------------------------------ // Helpers //------------------------------------------------------------------------------ -const enabledRules = Object.keys(builtInRules).reduce((result, ruleId) => { - if (!builtInRules[ruleId].meta.deprecated) { - result[ruleId] = "error"; +const allRules = {}; + +for (const [ruleId, rule] of builtInRules) { + if (!rule.meta.deprecated) { + allRules[ruleId] = "error"; } - return result; -}, {}); +} //------------------------------------------------------------------------------ // Public Interface //------------------------------------------------------------------------------ -module.exports = { rules: enabledRules }; +/** @type {import("../lib/shared/types").ConfigData} */ +module.exports = { rules: allRules }; diff --git a/tools/node_modules/eslint/conf/eslint-recommended.js b/tools/node_modules/eslint/conf/eslint-recommended.js index 447a99638a4423..7cc6e01652ba2a 100644 --- a/tools/node_modules/eslint/conf/eslint-recommended.js +++ b/tools/node_modules/eslint/conf/eslint-recommended.js @@ -6,10 +6,65 @@ "use strict"; -const builtInRules = require("../lib/built-in-rules-index"); +/* eslint sort-keys: ["error", "asc"] */ +/** @type {import("../lib/shared/types").ConfigData} */ module.exports = { - rules: Object.assign({}, ...Object.keys(builtInRules).map(ruleId => ({ - [ruleId]: builtInRules[ruleId].meta.docs.recommended ? "error" : "off" - }))) + rules: { + "constructor-super": "error", + "for-direction": "error", + "getter-return": "error", + "no-async-promise-executor": "error", + "no-case-declarations": "error", + "no-class-assign": "error", + "no-compare-neg-zero": "error", + "no-cond-assign": "error", + "no-const-assign": "error", + "no-constant-condition": "error", + "no-control-regex": "error", + "no-debugger": "error", + "no-delete-var": "error", + "no-dupe-args": "error", + "no-dupe-class-members": "error", + "no-dupe-keys": "error", + "no-duplicate-case": "error", + "no-empty": "error", + "no-empty-character-class": "error", + "no-empty-pattern": "error", + "no-ex-assign": "error", + "no-extra-boolean-cast": "error", + "no-extra-semi": "error", + "no-fallthrough": "error", + "no-func-assign": "error", + "no-global-assign": "error", + "no-inner-declarations": "error", + "no-invalid-regexp": "error", + "no-irregular-whitespace": "error", + "no-misleading-character-class": "error", + "no-mixed-spaces-and-tabs": "error", + "no-new-symbol": "error", + "no-obj-calls": "error", + "no-octal": "error", + "no-prototype-builtins": "error", + "no-redeclare": "error", + "no-regex-spaces": "error", + "no-self-assign": "error", + "no-shadow-restricted-names": "error", + "no-sparse-arrays": "error", + "no-this-before-super": "error", + "no-undef": "error", + "no-unexpected-multiline": "error", + "no-unreachable": "error", + "no-unsafe-finally": "error", + "no-unsafe-negation": "error", + "no-unused-labels": "error", + "no-unused-vars": "error", + "no-useless-catch": "error", + "no-useless-escape": "error", + "no-with": "error", + "require-atomic-updates": "error", + "require-yield": "error", + "use-isnan": "error", + "valid-typeof": "error" + } }; diff --git a/tools/node_modules/eslint/lib/api.js b/tools/node_modules/eslint/lib/api.js index 91dae3c7cbb42b..40a5cc9fa5ccd4 100644 --- a/tools/node_modules/eslint/lib/api.js +++ b/tools/node_modules/eslint/lib/api.js @@ -5,15 +5,19 @@ "use strict"; -const Linter = require("./linter"); +const { CLIEngine } = require("./cli-engine"); +const { Linter } = require("./linter"); +const { RuleTester } = require("./rule-tester"); +const { SourceCode } = require("./source-code"); module.exports = { Linter, - CLIEngine: require("./cli-engine"), - RuleTester: require("./testers/rule-tester"), - SourceCode: require("./util/source-code") + CLIEngine, + RuleTester, + SourceCode }; +// DOTO: remove deprecated API. let deprecatedLinterInstance = null; Object.defineProperty(module.exports, "linter", { 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 d75fbbc698db36..00000000000000 --- a/tools/node_modules/eslint/lib/built-in-rules-index.js +++ /dev/null @@ -1,278 +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-named-capture-group": require("./rules/prefer-named-capture-group"), - "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 301ffe3c78867e..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 = /^\./u.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(/\\/gu, "/"); - - 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-engine/cascading-config-array-factory.js b/tools/node_modules/eslint/lib/cli-engine/cascading-config-array-factory.js new file mode 100644 index 00000000000000..7d162e5c048760 --- /dev/null +++ b/tools/node_modules/eslint/lib/cli-engine/cascading-config-array-factory.js @@ -0,0 +1,405 @@ +/** + * @fileoverview `CascadingConfigArrayFactory` class. + * + * `CascadingConfigArrayFactory` class has a responsibility: + * + * 1. Handles cascading of config files. + * + * It provides two methods: + * + * - `getConfigArrayForFile(filePath)` + * Get the corresponded configuration of a given file. This method doesn't + * throw even if the given file didn't exist. + * - `clearCache()` + * Clear the internal cache. You have to call this method when + * `additionalPluginPool` was updated if `baseConfig` or `cliConfig` depends + * on the additional plugins. (`CLIEngine#addPlugin()` method calls this.) + * + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const os = require("os"); +const path = require("path"); +const { validateConfigArray } = require("../shared/config-validator"); +const { ConfigArrayFactory } = require("./config-array-factory"); +const { ConfigDependency } = require("./config-array"); +const loadRules = require("./load-rules"); +const debug = require("debug")("eslint:cascading-config-array-factory"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +// Define types for VSCode IntelliSense. +/** @typedef {import("../shared/types").ConfigData} ConfigData */ +/** @typedef {import("../shared/types").Parser} Parser */ +/** @typedef {import("../shared/types").Plugin} Plugin */ +/** @typedef {ReturnType} ConfigArray */ + +/** + * @typedef {Object} CascadingConfigArrayFactoryOptions + * @property {Map} [additionalPluginPool] The map for additional plugins. + * @property {ConfigData} [baseConfig] The config by `baseConfig` option. + * @property {ConfigData} [cliConfig] The config by CLI options (`--env`, `--global`, `--parser`, `--parser-options`, `--plugin`, and `--rule`). CLI options overwrite the setting in config files. + * @property {string} [cwd] The base directory to start lookup. + * @property {string[]} [rulePaths] The value of `--rulesdir` option. + * @property {string} [specificConfigPath] The value of `--config` option. + * @property {boolean} [useEslintrc] if `false` then it doesn't load config files. + */ + +/** + * @typedef {Object} CascadingConfigArrayFactoryInternalSlots + * @property {ConfigArray} baseConfigArray The config array of `baseConfig` option. + * @property {ConfigData} baseConfigData The config data of `baseConfig` option. This is used to reset `baseConfigArray`. + * @property {ConfigArray} cliConfigArray The config array of CLI options. + * @property {ConfigData} cliConfigData The config data of CLI options. This is used to reset `cliConfigArray`. + * @property {ConfigArrayFactory} configArrayFactory The factory for config arrays. + * @property {Map} configCache The cache from directory paths to config arrays. + * @property {string} cwd The base directory to start lookup. + * @property {WeakMap} finalizeCache The cache from config arrays to finalized config arrays. + * @property {string[]|null} rulePaths The value of `--rulesdir` option. This is used to reset `baseConfigArray`. + * @property {string|null} specificConfigPath The value of `--config` option. This is used to reset `cliConfigArray`. + * @property {boolean} useEslintrc if `false` then it doesn't load config files. + */ + +/** @type {WeakMap} */ +const internalSlotsMap = new WeakMap(); + +/** + * Create the config array from `baseConfig` and `rulePaths`. + * @param {CascadingConfigArrayFactoryInternalSlots} slots The slots. + * @returns {ConfigArray} The config array of the base configs. + */ +function createBaseConfigArray({ + configArrayFactory, + baseConfigData, + rulePaths, + cwd +}) { + const baseConfigArray = configArrayFactory.create( + baseConfigData, + { name: "BaseConfig" } + ); + + if (rulePaths && rulePaths.length > 0) { + + /* + * Load rules `--rulesdir` option as a pseudo plugin. + * Use a pseudo plugin to define rules of `--rulesdir`, so we can + * validate the rule's options with only information in the config + * array. + */ + baseConfigArray.push({ + name: "--rulesdir", + filePath: "", + plugins: { + "": new ConfigDependency({ + definition: { + rules: rulePaths.reduce( + (map, rulesPath) => Object.assign( + map, + loadRules(rulesPath, cwd) + ), + {} + ) + }, + filePath: "", + id: "", + importerName: "--rulesdir", + importerPath: "" + }) + } + }); + } + + return baseConfigArray; +} + +/** + * Create the config array from CLI options. + * @param {CascadingConfigArrayFactoryInternalSlots} slots The slots. + * @returns {ConfigArray} The config array of the base configs. + */ +function createCLIConfigArray({ + cliConfigData, + configArrayFactory, + specificConfigPath +}) { + const cliConfigArray = configArrayFactory.create( + cliConfigData, + { name: "CLIOptions" } + ); + + if (specificConfigPath) { + cliConfigArray.unshift( + ...configArrayFactory.loadFile( + specificConfigPath, + { name: "--config" } + ) + ); + } + + return cliConfigArray; +} + +/** + * The error type when there are files matched by a glob, but all of them have been ignored. + */ +class ConfigurationNotFoundError extends Error { + + /** + * @param {string} directoryPath - The directory path. + */ + constructor(directoryPath) { + super(`No ESLint configuration found in ${directoryPath}.`); + this.messageTemplate = "no-config-found"; + this.messageData = { directoryPath }; + } +} + +/** + * This class provides the functionality that enumerates every file which is + * matched by given glob patterns and that configuration. + */ +class CascadingConfigArrayFactory { + + /** + * Initialize this enumerator. + * @param {CascadingConfigArrayFactoryOptions} options The options. + */ + constructor({ + additionalPluginPool = new Map(), + baseConfig: baseConfigData = null, + cliConfig: cliConfigData = null, + cwd = process.cwd(), + resolvePluginsRelativeTo = cwd, + rulePaths = [], + specificConfigPath = null, + useEslintrc = true + } = {}) { + const configArrayFactory = new ConfigArrayFactory({ + additionalPluginPool, + cwd, + resolvePluginsRelativeTo + }); + + internalSlotsMap.set(this, { + baseConfigArray: createBaseConfigArray({ + baseConfigData, + configArrayFactory, + cwd, + rulePaths + }), + baseConfigData, + cliConfigArray: createCLIConfigArray({ + cliConfigData, + configArrayFactory, + specificConfigPath + }), + cliConfigData, + configArrayFactory, + configCache: new Map(), + cwd, + finalizeCache: new WeakMap(), + rulePaths, + specificConfigPath, + useEslintrc + }); + } + + /** + * The path to the current working directory. + * This is used by tests. + * @type {string} + */ + get cwd() { + const { cwd } = internalSlotsMap.get(this); + + return cwd; + } + + /** + * Get the config array of a given file. + * @param {string} filePath The file path to a file. + * @returns {ConfigArray} The config array of the file. + */ + getConfigArrayForFile(filePath) { + const { cwd } = internalSlotsMap.get(this); + const directoryPath = path.dirname(path.resolve(cwd, filePath)); + + debug(`Load config files for ${directoryPath}.`); + + return this._finalizeConfigArray( + this._loadConfigInAncestors(directoryPath), + directoryPath + ); + } + + /** + * Clear config cache. + * @returns {void} + */ + clearCache() { + const slots = internalSlotsMap.get(this); + + slots.baseConfigArray = createBaseConfigArray(slots); + slots.cliConfigArray = createCLIConfigArray(slots); + slots.configCache.clear(); + } + + /** + * Load and normalize config files from the ancestor directories. + * @param {string} directoryPath The path to a leaf directory. + * @returns {ConfigArray} The loaded config. + * @private + */ + _loadConfigInAncestors(directoryPath) { + const { + baseConfigArray, + configArrayFactory, + configCache, + cwd, + useEslintrc + } = internalSlotsMap.get(this); + + if (!useEslintrc) { + return baseConfigArray; + } + + let configArray = configCache.get(directoryPath); + + // Hit cache. + if (configArray) { + debug(`Cache hit: ${directoryPath}.`); + return configArray; + } + debug(`No cache found: ${directoryPath}.`); + + const homePath = os.homedir(); + + // Consider this is root. + if (directoryPath === homePath && cwd !== homePath) { + debug("Stop traversing because of considered root."); + return this._cacheConfig(directoryPath, baseConfigArray); + } + + // Load the config on this directory. + try { + configArray = configArrayFactory.loadInDirectory(directoryPath); + } catch (error) { + /* istanbul ignore next */ + if (error.code === "EACCES") { + debug("Stop traversing because of 'EACCES' error."); + return this._cacheConfig(directoryPath, baseConfigArray); + } + throw error; + } + + if (configArray.length > 0 && configArray.isRoot()) { + debug("Stop traversing because of 'root:true'."); + return this._cacheConfig(directoryPath, configArray); + } + + // Load from the ancestors and merge it. + const parentPath = path.dirname(directoryPath); + const parentConfigArray = parentPath && parentPath !== directoryPath + ? this._loadConfigInAncestors(parentPath) + : baseConfigArray; + + if (configArray.length > 0) { + configArray.unshift(...parentConfigArray); + } else { + configArray = parentConfigArray; + } + + // Cache and return. + return this._cacheConfig(directoryPath, configArray); + } + + /** + * Freeze and cache a given config. + * @param {string} directoryPath The path to a directory as a cache key. + * @param {ConfigArray} configArray The config array as a cache value. + * @returns {ConfigArray} The `configArray` (frozen). + */ + _cacheConfig(directoryPath, configArray) { + const { configCache } = internalSlotsMap.get(this); + + Object.freeze(configArray); + configCache.set(directoryPath, configArray); + + return configArray; + } + + /** + * Finalize a given config array. + * Concatenate `--config` and other CLI options. + * @param {ConfigArray} configArray The parent config array. + * @param {string} directoryPath The path to the leaf directory to find config files. + * @returns {ConfigArray} The loaded config. + * @private + */ + _finalizeConfigArray(configArray, directoryPath) { + const { + cliConfigArray, + configArrayFactory, + finalizeCache, + useEslintrc + } = internalSlotsMap.get(this); + + let finalConfigArray = finalizeCache.get(configArray); + + if (!finalConfigArray) { + finalConfigArray = configArray; + + // Load the personal config if there are no regular config files. + if ( + useEslintrc && + configArray.every(c => !c.filePath) && + cliConfigArray.every(c => !c.filePath) // `--config` option can be a file. + ) { + debug("Loading the config file of the home directory."); + + finalConfigArray = configArrayFactory.loadInDirectory( + os.homedir(), + { name: "PersonalConfig", parent: finalConfigArray } + ); + } + + // Apply CLI options. + if (cliConfigArray.length > 0) { + finalConfigArray = finalConfigArray.concat(cliConfigArray); + } + + // Validate rule settings and environments. + validateConfigArray(finalConfigArray); + + // Cache it. + Object.freeze(finalConfigArray); + finalizeCache.set(configArray, finalConfigArray); + + debug( + "Configuration was determined: %o on %s", + finalConfigArray, + directoryPath + ); + } + + if (useEslintrc && finalConfigArray.length === 0) { + throw new ConfigurationNotFoundError(directoryPath); + } + + return finalConfigArray; + } +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = { CascadingConfigArrayFactory }; diff --git a/tools/node_modules/eslint/lib/cli-engine/cli-engine.js b/tools/node_modules/eslint/lib/cli-engine/cli-engine.js new file mode 100644 index 00000000000000..a2359d801e81db --- /dev/null +++ b/tools/node_modules/eslint/lib/cli-engine/cli-engine.js @@ -0,0 +1,988 @@ +/** + * @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"); +const path = require("path"); +const defaultOptions = require("../../conf/default-cli-options"); +const pkg = require("../../package.json"); +const ConfigOps = require("../shared/config-ops"); +const ModuleResolver = require("../shared/relative-module-resolver"); +const { Linter } = require("../linter"); +const builtInRules = require("../rules"); +const { CascadingConfigArrayFactory } = require("./cascading-config-array-factory"); +const { getUsedExtractedConfigs } = require("./config-array"); +const { FileEnumerator } = require("./file-enumerator"); +const hash = require("./hash"); +const { IgnoredPaths } = require("./ignored-paths"); +const LintResultCache = require("./lint-result-cache"); +const naming = require("./naming"); + +const debug = require("debug")("eslint:cli-engine"); +const validFixTypes = new Set(["problem", "suggestion", "layout"]); + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +// For VSCode IntelliSense +/** @typedef {import("../shared/types").ConfigData} ConfigData */ +/** @typedef {import("../shared/types").LintMessage} LintMessage */ +/** @typedef {import("../shared/types").ParserOptions} ParserOptions */ +/** @typedef {import("../shared/types").Plugin} Plugin */ +/** @typedef {import("../shared/types").RuleConf} RuleConf */ +/** @typedef {import("../shared/types").Rule} Rule */ +/** @typedef {ReturnType} ConfigArray */ +/** @typedef {ReturnType} ExtractedConfig */ + +/** + * The options to configure a CLI engine with. + * @typedef {Object} CLIEngineOptions + * @property {boolean} allowInlineConfig Enable or disable inline configuration comments. + * @property {ConfigData} 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 {ParserOptions} parserOptions An object of parserOption settings to use. + * @property {string[]} plugins An array of plugins to load. + * @property {Record} 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 + * @property {boolean} globInputPaths Set to false to skip glob resolution of input file paths to lint (default: true). If false, each input file paths is assumed to be a non-glob path to an existing file. + * @property {string} resolvePluginsRelativeTo The folder where plugins should be resolved from, defaulting to the CWD + */ + +/** + * 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. + */ + +/** + * Information of deprecated rules. + * @typedef {Object} DeprecatedRuleInfo + * @property {string} ruleId The rule ID. + * @property {string[]} replacedBy The rule IDs that replace this deprecated rule. + */ + +/** + * Linting results. + * @typedef {Object} LintReport + * @property {LintResult[]} results All of 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 {DeprecatedRuleInfo[]} usedDeprecatedRules The list of used deprecated rules. + */ + +/** + * Private data for CLIEngine. + * @typedef {Object} CLIEngineInternalSlots + * @property {Map} additionalPluginPool The map for additional plugins. + * @property {string} cacheFilePath The path to the cache of lint results. + * @property {CascadingConfigArrayFactory} configArrayFactory The factory of configs. + * @property {FileEnumerator} fileEnumerator The file enumerator. + * @property {IgnoredPaths} ignoredPaths The ignored paths. + * @property {ConfigArray[]} lastConfigArrays The list of config arrays that the last `executeOnFiles` or `executeOnText` used. + * @property {LintResultCache|null} lintResultCache The cache of lint results. + * @property {Linter} linter The linter instance which has loaded rules. + * @property {CLIEngineOptions} options The normalized options of this instance. + */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** @type {WeakMap} */ +const internalSlotsMap = new WeakMap(); + +/** + * 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 {LintMessage[]} 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 {LintResult[]} 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 {Object} config The config object. + * @param {string} config.text The source code to verify. + * @param {string} config.cwd The path to the current working directory. + * @param {string|undefined} config.filePath The path to the file of `text`. If this is undefined, it uses ``. + * @param {ConfigArray} config.config The config. + * @param {boolean} config.fix If `true` then it does fix. + * @param {boolean} config.allowInlineConfig If `true` then it uses directive comments. + * @param {boolean} config.reportUnusedDisableDirectives If `true` then it reports unused `eslint-disable` comments. + * @param {RegExp} config.extensionRegExp The `RegExp` object that tests if a file path has the allowed file extensions. + * @param {Linter} config.linter The linter instance to verify. + * @returns {LintResult} The result of linting. + * @private + */ +function verifyText({ + text, + cwd, + filePath: providedFilePath, + config, + fix, + allowInlineConfig, + reportUnusedDisableDirectives, + extensionRegExp, + linter +}) { + const filePath = providedFilePath || ""; + + debug(`Lint ${filePath}`); + + /* + * Verify. + * `config.extractConfig(filePath)` requires an absolute path, but `linter` + * doesn't know CWD, so it gives `linter` an absolute path always. + */ + const filePathToVerify = filePath === "" ? path.join(cwd, filePath) : filePath; + const { fixed, messages, output } = linter.verifyAndFix( + text, + config, + { + allowInlineConfig, + filename: filePathToVerify, + fix, + reportUnusedDisableDirectives, + + /** + * Check if the linter should adopt a given code block or not. + * Currently, the linter adopts code blocks if the name matches `--ext` option. + * In the future, `overrides` in the configuration would affect the adoption (https://github.com/eslint/rfcs/pull/20). + * @param {string} blockFilename The virtual filename of a code block. + * @returns {boolean} `true` if the linter should adopt the code block. + */ + filterCodeBlock(blockFilename) { + return extensionRegExp.test(blockFilename); + } + } + ); + + // Tweak and return. + const result = { + filePath, + messages, + ...calculateStatsPerFile(messages) + }; + + if (fixed) { + result.output = output; + } + if ( + result.errorCount + result.warningCount > 0 && + typeof result.output === "undefined" + ) { + result.source = text; + } + + return result; +} + +/** + * 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 = /^\./u.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 + }; +} + +/** + * Get a rule. + * @param {string} ruleId The rule ID to get. + * @param {ConfigArray[]} configArrays The config arrays that have plugin rules. + * @returns {Rule|null} The rule or null. + */ +function getRule(ruleId, configArrays) { + for (const configArray of configArrays) { + const rule = configArray.pluginRules.get(ruleId); + + if (rule) { + return rule; + } + } + return builtInRules.get(ruleId) || null; +} + +/** + * Collect used deprecated rules. + * @param {ConfigArray[]} usedConfigArrays The config arrays which were used. + * @param {Map} ruleMap The rule definitions which were used (built-ins). + * @returns {IterableIterator} Used deprecated rules. + */ +function *iterateRuleDeprecationWarnings(usedConfigArrays) { + const processedRuleIds = new Set(); + + // Flatten used configs. + /** @type {ExtractedConfig[]} */ + const configs = [].concat( + ...usedConfigArrays.map(getUsedExtractedConfigs) + ); + + // Traverse rule configs. + for (const config of configs) { + for (const [ruleId, ruleConfig] of Object.entries(config.rules)) { + + // Skip if it was processed. + if (processedRuleIds.has(ruleId)) { + continue; + } + processedRuleIds.add(ruleId); + + // Skip if it's not used. + if (!ConfigOps.getRuleSeverity(ruleConfig)) { + continue; + } + const rule = getRule(ruleId, usedConfigArrays); + + // Skip if it's not deprecated. + if (!(rule && rule.meta && rule.meta.deprecated)) { + continue; + } + + // This rule was used and deprecated. + yield { + ruleId, + replacedBy: rule.meta.replacedBy || [] + }; + } + } +} + +/** + * Checks if the given message is an error message. + * @param {LintMessage} 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; +} + +/** + * Convert a string array to a boolean map. + * @param {string[]|null} keys The keys to assign true. + * @param {boolean} defaultValue The default value for each property. + * @param {string} displayName The property name which is used in error message. + * @returns {Record} The boolean map. + */ +function toBooleanMap(keys, defaultValue, displayName) { + if (keys && !Array.isArray(keys)) { + throw new Error(`${displayName} must be an array.`); + } + if (keys && keys.length > 0) { + return keys.reduce((map, def) => { + const [key, value] = def.split(":"); + + if (key !== "__proto__") { + map[key] = value === void 0 + ? defaultValue + : value === "true"; + } + + return map; + }, {}); + } + return void 0; +} + +/** + * Create a config data from CLI options. + * @param {CLIEngineOptions} options The options + * @returns {ConfigData|null} The created config data. + */ +function createConfigDataFromOptions(options) { + const { parser, parserOptions, plugins, rules } = options; + const env = toBooleanMap(options.envs, true, "envs"); + const globals = toBooleanMap(options.globals, false, "globals"); + + if ( + env === void 0 && + globals === void 0 && + parser === void 0 && + parserOptions === void 0 && + plugins === void 0 && + rules === void 0 + ) { + return null; + } + return { env, globals, parser, parserOptions, plugins, rules }; +} + +/** + * 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) { + try { + return fs.statSync(resolvedPath).isDirectory(); + } catch (error) { + if (error && error.code === "ENOENT") { + return false; + } + throw error; + } +} + +//------------------------------------------------------------------------------ +// 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 (options.fix === void 0) { + options.fix = false; + } + + const additionalPluginPool = new Map(); + const cacheFilePath = getCacheFile( + options.cacheLocation || options.cacheFile, + options.cwd + ); + const configArrayFactory = new CascadingConfigArrayFactory({ + additionalPluginPool, + baseConfig: options.baseConfig || null, + cliConfig: createConfigDataFromOptions(options), + cwd: options.cwd, + resolvePluginsRelativeTo: options.resolvePluginsRelativeTo, + rulePaths: options.rulePaths, + specificConfigPath: options.configFile, + useEslintrc: options.useEslintrc + }); + const ignoredPaths = new IgnoredPaths(options); + const fileEnumerator = new FileEnumerator({ + configArrayFactory, + cwd: options.cwd, + extensions: options.extensions, + globInputPaths: options.globInputPaths, + ignore: options.ignore, + ignoredPaths + }); + const lintResultCache = + options.cache ? new LintResultCache(cacheFilePath) : null; + const linter = new Linter(); + + /** @type {ConfigArray[]} */ + const lastConfigArrays = []; + + // Store private data. + internalSlotsMap.set(this, { + additionalPluginPool, + cacheFilePath, + configArrayFactory, + fileEnumerator, + ignoredPaths, + lastConfigArrays, + lintResultCache, + linter, + options + }); + + // setup special filter for fixes + if (options.fix && options.fixTypes && options.fixTypes.length > 0) { + debug(`Using fix types ${options.fixTypes}`); + + // throw an error if any invalid fix types are found + validateFixTypes(options.fixTypes); + + // convert to Set for faster lookup + const fixTypes = new Set(options.fixTypes); + + // save original value of options.fix in case it's a function + const originalFix = (typeof options.fix === "function") + ? options.fix : () => true; + + options.fix = message => { + const rule = message.ruleId && getRule(message.ruleId, lastConfigArrays); + const matches = rule && rule.meta && fixTypes.has(rule.meta.type); + + return matches && originalFix(message); + }; + } + } + + getRules() { + const { lastConfigArrays } = internalSlotsMap.get(this); + + return new Map(function *() { + yield* builtInRules; + + for (const configArray of lastConfigArrays) { + yield* configArray.pluginRules; + } + }()); + } + + /** + * 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({ + ...result, + messages: filteredMessages, + errorCount: filteredMessages.length, + warningCount: 0, + fixableErrorCount: result.fixableErrorCount, + fixableWarningCount: 0 + }); + } + }); + + return filtered; + } + + /** + * Outputs fixes from the given results to files. + * @param {LintReport} 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 {Plugin} pluginObject Plugin configuration object. + * @returns {void} + */ + addPlugin(name, pluginObject) { + const { + additionalPluginPool, + configArrayFactory + } = internalSlotsMap.get(this); + + additionalPluginPool.set(name, pluginObject); + configArrayFactory.clearCache(); + } + + /** + * 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) { + const { options } = internalSlotsMap.get(this); + + if (options.globInputPaths === false) { + return patterns.filter(Boolean); + } + + const extensions = options.extensions.map(ext => ext.replace(/^\./u, "")); + const dirSuffix = `/**/*.{${extensions.join(",")}}`; + + return patterns.filter(Boolean).map(pathname => { + const resolvedPath = path.resolve(options.cwd, pathname); + const newPath = directoryExists(resolvedPath) + ? pathname.replace(/[/\\]$/u, "") + dirSuffix + : pathname; + + return path.normalize(newPath).replace(/\\/gu, "/"); + }); + } + + /** + * Executes the current configuration on an array of file and directory names. + * @param {string[]} patterns An array of file and directory names. + * @returns {LintReport} The results for all files that were linted. + */ + executeOnFiles(patterns) { + const { + cacheFilePath, + fileEnumerator, + lastConfigArrays, + lintResultCache, + linter, + options: { + allowInlineConfig, + cache, + cwd, + fix, + reportUnusedDisableDirectives + } + } = internalSlotsMap.get(this); + const results = []; + const startTime = Date.now(); + + // Clear the last used config arrays. + lastConfigArrays.length = 0; + + // Delete cache file; should this do here? + if (!cache) { + try { + fs.unlinkSync(cacheFilePath); + } catch (error) { + if (!error || error.code !== "ENOENT") { + throw error; + } + } + } + + // Iterate source code files. + for (const { config, filePath, ignored } of fileEnumerator.iterateFiles(patterns)) { + if (ignored) { + results.push(createIgnoreResult(filePath, cwd)); + continue; + } + + /* + * Store used configs for: + * - this method uses to collect used deprecated rules. + * - `getRules()` method uses to collect all loaded rules. + * - `--fix-type` option uses to get the loaded rule's meta data. + */ + if (!lastConfigArrays.includes(config)) { + lastConfigArrays.push(config); + } + + // Skip if there is cached result. + if (lintResultCache) { + const cachedResult = + lintResultCache.getCachedLintResults(filePath, config); + + if (cachedResult) { + const hadMessages = + cachedResult.messages && + cachedResult.messages.length > 0; + + if (hadMessages && fix) { + debug(`Reprocessing cached file to allow autofix: ${filePath}`); + } else { + debug(`Skipping file since it hasn't changed: ${filePath}`); + results.push(cachedResult); + continue; + } + } + } + + // Do lint. + const result = verifyText({ + text: fs.readFileSync(filePath, "utf8"), + filePath, + config, + cwd, + fix, + allowInlineConfig, + reportUnusedDisableDirectives, + extensionRegExp: fileEnumerator.extensionRegExp, + linter + }); + + results.push(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. + */ + if (lintResultCache) { + lintResultCache.setCachedLintResults(filePath, config, result); + } + } + + // Persist the cache to disk. + if (lintResultCache) { + lintResultCache.reconcile(); + } + + // Collect used deprecated rules. + const usedDeprecatedRules = Array.from( + iterateRuleDeprecationWarnings(lastConfigArrays) + ); + + debug(`Linting complete in: ${Date.now() - startTime}ms`); + return { + results, + ...calculateStatsPerRun(results), + 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 {LintReport} The results for the linting. + */ + executeOnText(text, filename, warnIgnored) { + const { + configArrayFactory, + fileEnumerator, + ignoredPaths, + lastConfigArrays, + linter, + options: { + allowInlineConfig, + cwd, + fix, + reportUnusedDisableDirectives + } + } = internalSlotsMap.get(this); + const results = []; + const startTime = Date.now(); + const resolvedFilename = filename && path.resolve(cwd, filename); + + // Clear the last used config arrays. + lastConfigArrays.length = 0; + + if (resolvedFilename && ignoredPaths.contains(resolvedFilename)) { + if (warnIgnored) { + results.push(createIgnoreResult(resolvedFilename, cwd)); + } + } else { + const config = configArrayFactory.getConfigArrayForFile( + resolvedFilename || "__placeholder__.js" + ); + + /* + * Store used configs for: + * - this method uses to collect used deprecated rules. + * - `getRules()` method uses to collect all loaded rules. + * - `--fix-type` option uses to get the loaded rule's meta data. + */ + lastConfigArrays.push(config); + + // Do lint. + results.push(verifyText({ + text, + filePath: resolvedFilename, + config, + cwd, + fix, + allowInlineConfig, + reportUnusedDisableDirectives, + extensionRegExp: fileEnumerator.extensionRegExp, + linter + })); + } + + // Collect used deprecated rules. + const usedDeprecatedRules = Array.from( + iterateRuleDeprecationWarnings(lastConfigArrays) + ); + + debug(`Linting complete in: ${Date.now() - startTime}ms`); + return { + results, + ...calculateStatsPerRun(results), + 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 {ConfigData} A configuration object for the file. + */ + getConfigForFile(filePath) { + const { configArrayFactory, options } = internalSlotsMap.get(this); + const absolutePath = path.resolve(options.cwd, filePath); + + return configArrayFactory + .getConfigArrayForFile(absolutePath) + .extractConfig(absolutePath) + .toCompatibleObjectAsConfigFileContent(); + } + + /** + * 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 { ignoredPaths } = internalSlotsMap.get(this); + + return ignoredPaths.contains(filePath); + } + + /** + * 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(/\\/gu, "/"); + + const slots = internalSlotsMap.get(this); + const cwd = slots ? slots.options.cwd : process.cwd(); + const namespace = naming.getNamespaceFromTerm(normalizedFormatName); + + let formatterPath; + + // if there's a slash, then it's a file (TODO: this check seems dubious for scoped npm packages) + if (!namespace && normalizedFormatName.indexOf("/") > -1) { + formatterPath = path.resolve(cwd, normalizedFormatName); + } else { + try { + const npmFormat = naming.normalizePackageName(normalizedFormatName, "eslint-formatter"); + + formatterPath = ModuleResolver.resolve(npmFormat, path.join(cwd, "__placeholder__.js")); + } catch (e) { + formatterPath = path.resolve(__dirname, "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, + + /** + * Get the internal slots of a given CLIEngine instance for tests. + * @param {CLIEngine} instance The CLIEngine instance to get. + * @returns {CLIEngineInternalSlots} The internal slots. + */ + getCLIEngineInternalSlots(instance) { + return internalSlotsMap.get(instance); + } +}; diff --git a/tools/node_modules/eslint/lib/cli-engine/config-array-factory.js b/tools/node_modules/eslint/lib/cli-engine/config-array-factory.js new file mode 100644 index 00000000000000..46b4e740516064 --- /dev/null +++ b/tools/node_modules/eslint/lib/cli-engine/config-array-factory.js @@ -0,0 +1,914 @@ +/** + * @fileoverview The factory of `ConfigArray` objects. + * + * This class provides methods to create `ConfigArray` instance. + * + * - `create(configData, options)` + * Create a `ConfigArray` instance from a config data. This is to handle CLI + * options except `--config`. + * - `loadFile(filePath, options)` + * Create a `ConfigArray` instance from a config file. This is to handle + * `--config` option. If the file was not found, throws the following error: + * - If the filename was `*.js`, a `MODULE_NOT_FOUND` error. + * - If the filename was `package.json`, an IO error or an + * `ESLINT_CONFIG_FIELD_NOT_FOUND` error. + * - Otherwise, an IO error such as `ENOENT`. + * - `loadInDirectory(directoryPath, options)` + * Create a `ConfigArray` instance from a config file which is on a given + * directory. This tries to load `.eslintrc.*` or `package.json`. If not + * found, returns an empty `ConfigArray`. + * + * `ConfigArrayFactory` class has the responsibility that loads configuration + * files, including loading `extends`, `parser`, and `plugins`. The created + * `ConfigArray` instance has the loaded `extends`, `parser`, and `plugins`. + * + * But this class doesn't handle cascading. `CascadingConfigArrayFactory` class + * handles cascading and hierarchy. + * + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const fs = require("fs"); +const path = require("path"); +const importFresh = require("import-fresh"); +const stripComments = require("strip-json-comments"); +const { validateConfigSchema } = require("../shared/config-validator"); +const ModuleResolver = require("../shared/relative-module-resolver"); +const { ConfigArray, ConfigDependency, OverrideTester } = require("./config-array"); +const naming = require("./naming"); +const debug = require("debug")("eslint:config-array-factory"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const eslintRecommendedPath = path.resolve(__dirname, "../../conf/eslint-recommended.js"); +const eslintAllPath = path.resolve(__dirname, "../../conf/eslint-all.js"); +const configFilenames = [ + ".eslintrc.js", + ".eslintrc.yaml", + ".eslintrc.yml", + ".eslintrc.json", + ".eslintrc", + "package.json" +]; + +// Define types for VSCode IntelliSense. +/** @typedef {import("../shared/types").ConfigData} ConfigData */ +/** @typedef {import("../shared/types").OverrideConfigData} OverrideConfigData */ +/** @typedef {import("../shared/types").Parser} Parser */ +/** @typedef {import("../shared/types").Plugin} Plugin */ +/** @typedef {import("./config-array/config-dependency").DependentParser} DependentParser */ +/** @typedef {import("./config-array/config-dependency").DependentPlugin} DependentPlugin */ +/** @typedef {ConfigArray[0]} ConfigArrayElement */ + +/** + * @typedef {Object} ConfigArrayFactoryOptions + * @property {Map} [additionalPluginPool] The map for additional plugins. + * @property {string} [cwd] The path to the current working directory. + * @property {string} [resolvePluginsRelativeTo] A path to the directory that plugins should be resolved from. Defaults to `cwd`. + */ + +/** + * @typedef {Object} ConfigArrayFactoryInternalSlots + * @property {Map} additionalPluginPool The map for additional plugins. + * @property {string} cwd The path to the current working directory. + * @property {string} resolvePluginsRelativeTo An absolute path the the directory that plugins should be resolved from. + */ + +/** @type {WeakMap} */ +const internalSlotsMap = new WeakMap(); + +/** + * Check if a given string is a file path. + * @param {string} nameOrPath A module name or file path. + * @returns {boolean} `true` if the `nameOrPath` is a file path. + */ +function isFilePath(nameOrPath) { + return ( + /^\.{1,2}[/\\]/u.test(nameOrPath) || + path.isAbsolute(nameOrPath) + ); +} + +/** + * 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/u, ""); +} + +/** + * Loads a YAML configuration from a file. + * @param {string} filePath The filename to load. + * @returns {ConfigData} 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 {ConfigData} 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 {ConfigData} The configuration object from the file. + * @throws {Error} If the file cannot be read. + * @private + */ +function loadLegacyConfigFile(filePath) { + debug(`Loading legacy 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: %s\n%o", filePath, e); + 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 {ConfigData} 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 {ConfigData} 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 { + const packageData = loadJSONConfigFile(filePath); + + if (!Object.hasOwnProperty.call(packageData, "eslintConfig")) { + throw Object.assign( + new Error("package.json file doesn't have 'eslintConfig' field."), + { code: "ESLINT_CONFIG_FIELD_NOT_FOUND" } + ); + } + + return packageData.eslintConfig; + } 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) { + return Object.assign( + new Error(`Failed to load config "${configName}" to extend from.`), + { + messageTemplate: "extend-config-missing", + messageData: { configName } + } + ); +} + +/** + * Loads a configuration file regardless of the source. Inspects the file path + * to determine the correctly way to load the config file. + * @param {string} filePath The path to the configuration. + * @returns {ConfigData|null} The configuration information. + * @private + */ +function loadConfigFile(filePath) { + switch (path.extname(filePath)) { + case ".js": + return loadJSConfigFile(filePath); + + case ".json": + if (path.basename(filePath) === "package.json") { + return loadPackageJSONConfigFile(filePath); + } + return loadJSONConfigFile(filePath); + + case ".yaml": + case ".yml": + return loadYAMLConfigFile(filePath); + + default: + return loadLegacyConfigFile(filePath); + } +} + +/** + * Write debug log. + * @param {string} request The requested module name. + * @param {string} relativeTo The file path to resolve the request relative to. + * @param {string} filePath The resolved file path. + * @returns {void} + */ +function writeDebugLogForLoading(request, relativeTo, filePath) { + /* istanbul ignore next */ + if (debug.enabled) { + let nameAndVersion = null; + + try { + const packageJsonPath = ModuleResolver.resolve( + `${request}/package.json`, + relativeTo + ); + const { version = "unknown" } = require(packageJsonPath); + + nameAndVersion = `${request}@${version}`; + } catch (error) { + debug("package.json was not found:", error.message); + nameAndVersion = request; + } + + debug("Loaded: %s (%s)", nameAndVersion, filePath); + } +} + +/** + * Concatenate two config data. + * @param {IterableIterator|null} elements The config elements. + * @param {ConfigArray|null} parentConfigArray The parent config array. + * @returns {ConfigArray} The concatenated config array. + */ +function createConfigArray(elements, parentConfigArray) { + if (!elements) { + return parentConfigArray || new ConfigArray(); + } + const configArray = new ConfigArray(...elements); + + if (parentConfigArray && !configArray.isRoot()) { + configArray.unshift(...parentConfigArray); + } + return configArray; +} + +/** + * Normalize a given plugin. + * - Ensure the object to have four properties: configs, environments, processors, and rules. + * - Ensure the object to not have other properties. + * @param {Plugin} plugin The plugin to normalize. + * @returns {Plugin} The normalized plugin. + */ +function normalizePlugin(plugin) { + return { + configs: plugin.configs || {}, + environments: plugin.environments || {}, + processors: plugin.processors || {}, + rules: plugin.rules || {} + }; +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * The factory of `ConfigArray` objects. + */ +class ConfigArrayFactory { + + /** + * Initialize this instance. + * @param {ConfigArrayFactoryOptions} [options] The map for additional plugins. + */ + constructor({ + additionalPluginPool = new Map(), + cwd = process.cwd(), + resolvePluginsRelativeTo = cwd + } = {}) { + internalSlotsMap.set(this, { additionalPluginPool, cwd, resolvePluginsRelativeTo: path.resolve(cwd, resolvePluginsRelativeTo) }); + } + + /** + * Create `ConfigArray` instance from a config data. + * @param {ConfigData|null} configData The config data to create. + * @param {Object} [options] The options. + * @param {string} [options.filePath] The path to this config data. + * @param {string} [options.name] The config name. + * @param {ConfigArray} [options.parent] The parent config array. + * @returns {ConfigArray} Loaded config. + */ + create(configData, { filePath, name, parent } = {}) { + return createConfigArray( + configData + ? this._normalizeConfigData(configData, filePath, name) + : null, + parent + ); + } + + /** + * Load a config file. + * @param {string} filePath The path to a config file. + * @param {Object} [options] The options. + * @param {string} [options.name] The config name. + * @param {ConfigArray} [options.parent] The parent config array. + * @returns {ConfigArray} Loaded config. + */ + loadFile(filePath, { name, parent } = {}) { + const { cwd } = internalSlotsMap.get(this); + const absolutePath = path.resolve(cwd, filePath); + + return createConfigArray( + this._loadConfigData(absolutePath, name), + parent + ); + } + + /** + * Load the config file on a given directory if exists. + * @param {string} directoryPath The path to a directory. + * @param {Object} [options] The options. + * @param {string} [options.name] The config name. + * @param {ConfigArray} [options.parent] The parent config array. + * @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist. + */ + loadInDirectory(directoryPath, { name, parent } = {}) { + const { cwd } = internalSlotsMap.get(this); + const absolutePath = path.resolve(cwd, directoryPath); + + return createConfigArray( + this._loadConfigDataInDirectory(absolutePath, name), + parent + ); + } + + /** + * Load a given config file. + * @param {string} filePath The path to a config file. + * @param {string} name The config name. + * @returns {IterableIterator} Loaded config. + * @private + */ + _loadConfigData(filePath, name) { + return this._normalizeConfigData( + loadConfigFile(filePath), + filePath, + name + ); + } + + /** + * Load the config file in a given directory if exists. + * @param {string} directoryPath The path to a directory. + * @param {string} name The config name. + * @returns {IterableIterator | null} Loaded config. `null` if any config doesn't exist. + * @private + */ + _loadConfigDataInDirectory(directoryPath, name) { + for (const filename of configFilenames) { + const filePath = path.join(directoryPath, filename); + + if (fs.existsSync(filePath)) { + let configData; + + try { + configData = loadConfigFile(filePath); + } catch (error) { + if (!error || error.code !== "ESLINT_CONFIG_FIELD_NOT_FOUND") { + throw error; + } + } + + if (configData) { + debug(`Config file found: ${filePath}`); + return this._normalizeConfigData(configData, filePath, name); + } + } + } + + debug(`Config file not found on ${directoryPath}`); + return null; + } + + /** + * Normalize a given config to an array. + * @param {ConfigData} configData The config data to normalize. + * @param {string|undefined} providedFilePath The file path of this config. + * @param {string|undefined} providedName The name of this config. + * @returns {IterableIterator} The normalized config. + * @private + */ + _normalizeConfigData(configData, providedFilePath, providedName) { + const { cwd } = internalSlotsMap.get(this); + const filePath = providedFilePath + ? path.resolve(cwd, providedFilePath) + : ""; + const name = providedName || (filePath && path.relative(cwd, filePath)); + + validateConfigSchema(configData, name || filePath); + + return this._normalizeObjectConfigData(configData, filePath, name); + } + + /** + * Normalize a given config to an array. + * @param {ConfigData|OverrideConfigData} configData The config data to normalize. + * @param {string} filePath The file path of this config. + * @param {string} name The name of this config. + * @returns {IterableIterator} The normalized config. + * @private + */ + *_normalizeObjectConfigData(configData, filePath, name) { + const { cwd } = internalSlotsMap.get(this); + const { files, excludedFiles, ...configBody } = configData; + const basePath = filePath ? path.dirname(filePath) : cwd; + const criteria = OverrideTester.create(files, excludedFiles, basePath); + const elements = + this._normalizeObjectConfigDataBody(configBody, filePath, name); + + // Apply the criteria to every element. + for (const element of elements) { + + // Adopt the base path of the entry file (the outermost base path). + if (element.criteria) { + element.criteria.basePath = basePath; + } + + /* + * Merge the criteria; this is for only file extension processors in + * `overrides` section for now. + */ + element.criteria = OverrideTester.and(criteria, element.criteria); + + /* + * Remove `root` property to ignore `root` settings which came from + * `extends` in `overrides`. + */ + if (element.criteria) { + element.root = void 0; + } + + yield element; + } + } + + /** + * Normalize a given config to an array. + * @param {ConfigData} configData The config data to normalize. + * @param {string} filePath The file path of this config. + * @param {string} name The name of this config. + * @returns {IterableIterator} The normalized config. + * @private + */ + *_normalizeObjectConfigDataBody( + { + env, + extends: extend, + globals, + parser: parserName, + parserOptions, + plugins: pluginList, + processor, + root, + rules, + settings, + overrides: overrideList = [] + }, + filePath, + name + ) { + const extendList = Array.isArray(extend) ? extend : [extend]; + + // Flatten `extends`. + for (const extendName of extendList.filter(Boolean)) { + yield* this._loadExtends(extendName, filePath, name); + } + + // Load parser & plugins. + const parser = + parserName && this._loadParser(parserName, filePath, name); + const plugins = + pluginList && this._loadPlugins(pluginList, filePath, name); + + // Yield pseudo config data for file extension processors. + if (plugins) { + yield* this._takeFileExtensionProcessors(plugins, filePath, name); + } + + // Yield the config data except `extends` and `overrides`. + yield { + + // Debug information. + name, + filePath, + + // Config data. + criteria: null, + env, + globals, + parser, + parserOptions, + plugins, + processor, + root, + rules, + settings + }; + + // Flatten `overries`. + for (let i = 0; i < overrideList.length; ++i) { + yield* this._normalizeObjectConfigData( + overrideList[i], + filePath, + `${name}#overrides[${i}]` + ); + } + } + + /** + * Load configs of an element in `extends`. + * @param {string} extendName The name of a base config. + * @param {string} importerPath The file path which has the `extends` property. + * @param {string} importerName The name of the config which has the `extends` property. + * @returns {IterableIterator} The normalized config. + * @private + */ + _loadExtends(extendName, importerPath, importerName) { + debug("Loading {extends:%j} relative to %s", extendName, importerPath); + try { + if (extendName.startsWith("eslint:")) { + return this._loadExtendedBuiltInConfig( + extendName, + importerName + ); + } + if (extendName.startsWith("plugin:")) { + return this._loadExtendedPluginConfig( + extendName, + importerPath, + importerName + ); + } + return this._loadExtendedShareableConfig( + extendName, + importerPath, + importerName + ); + } catch (error) { + error.message += `\nReferenced from: ${importerPath || importerName}`; + throw error; + } + } + + /** + * Load configs of an element in `extends`. + * @param {string} extendName The name of a base config. + * @param {string} importerName The name of the config which has the `extends` property. + * @returns {IterableIterator} The normalized config. + * @private + */ + _loadExtendedBuiltInConfig(extendName, importerName) { + const name = `${importerName} » ${extendName}`; + + if (extendName === "eslint:recommended") { + return this._loadConfigData(eslintRecommendedPath, name); + } + if (extendName === "eslint:all") { + return this._loadConfigData(eslintAllPath, name); + } + + throw configMissingError(extendName); + } + + /** + * Load configs of an element in `extends`. + * @param {string} extendName The name of a base config. + * @param {string} importerPath The file path which has the `extends` property. + * @param {string} importerName The name of the config which has the `extends` property. + * @returns {IterableIterator} The normalized config. + * @private + */ + _loadExtendedPluginConfig(extendName, importerPath, importerName) { + const slashIndex = extendName.lastIndexOf("/"); + const pluginName = extendName.slice("plugin:".length, slashIndex); + const configName = extendName.slice(slashIndex + 1); + + if (isFilePath(pluginName)) { + throw new Error("'extends' cannot use a file path for plugins."); + } + + const plugin = this._loadPlugin(pluginName, importerPath, importerName); + const configData = + plugin.definition && + plugin.definition.configs[configName]; + + if (configData) { + return this._normalizeConfigData( + configData, + plugin.filePath, + `${importerName} » plugin:${plugin.id}/${configName}` + ); + } + + throw plugin.error || configMissingError(extendName); + } + + /** + * Load configs of an element in `extends`. + * @param {string} extendName The name of a base config. + * @param {string} importerPath The file path which has the `extends` property. + * @param {string} importerName The name of the config which has the `extends` property. + * @returns {IterableIterator} The normalized config. + * @private + */ + _loadExtendedShareableConfig(extendName, importerPath, importerName) { + const { cwd } = internalSlotsMap.get(this); + const relativeTo = importerPath || path.join(cwd, "__placeholder__.js"); + let request; + + if (isFilePath(extendName)) { + request = extendName; + } else if (extendName.startsWith(".")) { + request = `./${extendName}`; // For backward compatibility. A ton of tests depended on this behavior. + } else { + request = naming.normalizePackageName( + extendName, + "eslint-config" + ); + } + + let filePath; + + try { + filePath = ModuleResolver.resolve(request, relativeTo); + } catch (error) { + /* istanbul ignore else */ + if (error && error.code === "MODULE_NOT_FOUND") { + throw configMissingError(extendName); + } + throw error; + } + + writeDebugLogForLoading(request, relativeTo, filePath); + return this._loadConfigData(filePath, `${importerName} » ${request}`); + } + + /** + * Load given plugins. + * @param {string[]} names The plugin names to load. + * @param {string} importerPath The path to a config file that imports it. This is just a debug info. + * @param {string} importerName The name of a config file that imports it. This is just a debug info. + * @returns {Record} The loaded parser. + * @private + */ + _loadPlugins(names, importerPath, importerName) { + return names.reduce((map, name) => { + if (isFilePath(name)) { + throw new Error("Plugins array cannot includes file paths."); + } + const plugin = this._loadPlugin(name, importerPath, importerName); + + map[plugin.id] = plugin; + + return map; + }, {}); + } + + /** + * Load a given parser. + * @param {string} nameOrPath The package name or the path to a parser file. + * @param {string} importerPath The path to a config file that imports it. + * @param {string} importerName The name of a config file that imports it. This is just a debug info. + * @returns {DependentParser} The loaded parser. + */ + _loadParser(nameOrPath, importerPath, importerName) { + debug("Loading parser %j from %s", nameOrPath, importerPath); + + const { cwd } = internalSlotsMap.get(this); + const relativeTo = importerPath || path.join(cwd, "__placeholder__.js"); + + try { + const filePath = ModuleResolver.resolve(nameOrPath, relativeTo); + + writeDebugLogForLoading(nameOrPath, relativeTo, filePath); + + return new ConfigDependency({ + definition: require(filePath), + filePath, + id: nameOrPath, + importerName, + importerPath + }); + } catch (error) { + + // If the parser name is "espree", load the espree of ESLint. + if (nameOrPath === "espree") { + debug("Fallback espree."); + return new ConfigDependency({ + definition: require("espree"), + filePath: require.resolve("espree"), + id: nameOrPath, + importerName, + importerPath + }); + } + + debug("Failed to load parser '%s' declared in '%s'.", nameOrPath, importerName); + error.message = `Failed to load parser '${nameOrPath}' declared in '${importerName}': ${error.message}`; + + return new ConfigDependency({ + error, + id: nameOrPath, + importerName, + importerPath + }); + } + } + + /** + * Load a given plugin. + * @param {string} name The plugin name to load. + * @param {string} importerPath The path to a config file that imports it. This is just a debug info. + * @param {string} importerName The name of a config file that imports it. This is just a debug info. + * @returns {DependentPlugin} The loaded plugin. + * @private + */ + _loadPlugin(name, importerPath, importerName) { + debug("Loading plugin %j from %s", name, importerPath); + + const { additionalPluginPool, resolvePluginsRelativeTo } = internalSlotsMap.get(this); + const request = naming.normalizePackageName(name, "eslint-plugin"); + const id = naming.getShorthandName(request, "eslint-plugin"); + const relativeTo = path.join(resolvePluginsRelativeTo, "__placeholder__.js"); + + if (name.match(/\s+/u)) { + const error = Object.assign( + new Error(`Whitespace found in plugin name '${name}'`), + { + messageTemplate: "whitespace-found", + messageData: { pluginName: request } + } + ); + + return new ConfigDependency({ + error, + id, + importerName, + importerPath + }); + } + + // Check for additional pool. + const plugin = + additionalPluginPool.get(request) || + additionalPluginPool.get(id); + + if (plugin) { + return new ConfigDependency({ + definition: normalizePlugin(plugin), + filePath: importerPath, + id, + importerName, + importerPath + }); + } + + let filePath; + let error; + + try { + filePath = ModuleResolver.resolve(request, relativeTo); + } catch (resolveError) { + error = resolveError; + /* istanbul ignore else */ + if (error && error.code === "MODULE_NOT_FOUND") { + error.messageTemplate = "plugin-missing"; + error.messageData = { + pluginName: request, + resolvePluginsRelativeTo, + importerName + }; + } + } + + if (filePath) { + try { + writeDebugLogForLoading(request, relativeTo, filePath); + return new ConfigDependency({ + definition: normalizePlugin(require(filePath)), + filePath, + id, + importerName, + importerPath + }); + } catch (loadError) { + error = loadError; + } + } + + debug("Failed to load plugin '%s' declared in '%s'.", name, importerName); + error.message = `Failed to load plugin '${name}' declared in '${importerName}': ${error.message}`; + return new ConfigDependency({ + error, + id, + importerName, + importerPath + }); + } + + /** + * Take file expression processors as config array elements. + * @param {Record} plugins The plugin definitions. + * @param {string} filePath The file path of this config. + * @param {string} name The name of this config. + * @returns {IterableIterator} The config array elements of file expression processors. + * @private + */ + *_takeFileExtensionProcessors(plugins, filePath, name) { + for (const pluginId of Object.keys(plugins)) { + const processors = + plugins[pluginId] && + plugins[pluginId].definition && + plugins[pluginId].definition.processors; + + if (!processors) { + continue; + } + + for (const processorId of Object.keys(processors)) { + if (processorId.startsWith(".")) { + yield* this._normalizeObjectConfigData( + { + files: [`*${processorId}`], + processor: `${pluginId}/${processorId}` + }, + filePath, + `${name}#processors["${pluginId}/${processorId}"]` + ); + } + } + } + } +} + +module.exports = { ConfigArrayFactory }; diff --git a/tools/node_modules/eslint/lib/cli-engine/config-array/config-array.js b/tools/node_modules/eslint/lib/cli-engine/config-array/config-array.js new file mode 100644 index 00000000000000..d85fc94bf140b5 --- /dev/null +++ b/tools/node_modules/eslint/lib/cli-engine/config-array/config-array.js @@ -0,0 +1,455 @@ +/** + * @fileoverview `ConfigArray` class. + * + * `ConfigArray` class expresses the full of a configuration. It has the entry + * config file, base config files that were extended, loaded parsers, and loaded + * plugins. + * + * `ConfigArray` class provies three properties and two methods. + * + * - `pluginEnvironments` + * - `pluginProcessors` + * - `pluginRules` + * The `Map` objects that contain the members of all plugins that this + * config array contains. Those map objects don't have mutation methods. + * Those keys are the member ID such as `pluginId/memberName`. + * - `isRoot()` + * If `true` then this configuration has `root:true` property. + * - `extractConfig(filePath)` + * Extract the final configuration for a given file. This means merging + * every config array element which that `criteria` property matched. The + * `filePath` argument must be an absolute path. + * + * `ConfigArrayFactory` provides the loading logic of config files. + * + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const { ExtractedConfig } = require("./extracted-config"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +// Define types for VSCode IntelliSense. +/** @typedef {import("../../shared/types").Environment} Environment */ +/** @typedef {import("../../shared/types").GlobalConf} GlobalConf */ +/** @typedef {import("../../shared/types").RuleConf} RuleConf */ +/** @typedef {import("../../shared/types").Rule} Rule */ +/** @typedef {import("../../shared/types").Plugin} Plugin */ +/** @typedef {import("../../shared/types").Processor} Processor */ +/** @typedef {import("./config-dependency").DependentParser} DependentParser */ +/** @typedef {import("./config-dependency").DependentPlugin} DependentPlugin */ +/** @typedef {import("./override-tester")["OverrideTester"]} OverrideTester */ + +/** + * @typedef {Object} ConfigArrayElement + * @property {string} name The name of this config element. + * @property {string} filePath The path to the source file of this config element. + * @property {InstanceType|null} criteria The tester for the `files` and `excludedFiles` of this config element. + * @property {Record|undefined} env The environment settings. + * @property {Record|undefined} globals The global variable settings. + * @property {DependentParser|undefined} parser The parser loader. + * @property {Object|undefined} parserOptions The parser options. + * @property {Record|undefined} plugins The plugin loaders. + * @property {string|undefined} processor The processor name to refer plugin's processor. + * @property {boolean|undefined} root The flag to express root. + * @property {Record|undefined} rules The rule settings + * @property {Object|undefined} settings The shared settings. + */ + +/** + * @typedef {Object} ConfigArrayInternalSlots + * @property {Map} cache The cache to extract configs. + * @property {ReadonlyMap|null} envMap The map from environment ID to environment definition. + * @property {ReadonlyMap|null} processorMap The map from processor ID to environment definition. + * @property {ReadonlyMap|null} ruleMap The map from rule ID to rule definition. + */ + +/** @type {WeakMap} */ +const internalSlotsMap = new class extends WeakMap { + get(key) { + let value = super.get(key); + + if (!value) { + value = { + cache: new Map(), + envMap: null, + processorMap: null, + ruleMap: null + }; + super.set(key, value); + } + + return value; + } +}(); + +/** + * Get the indices which are matched to a given file. + * @param {ConfigArrayElement[]} elements The elements. + * @param {string} filePath The path to a target file. + * @returns {number[]} The indices. + */ +function getMatchedIndices(elements, filePath) { + const indices = []; + + for (let i = elements.length - 1; i >= 0; --i) { + const element = elements[i]; + + if (!element.criteria || element.criteria.test(filePath)) { + indices.push(i); + } + } + + return indices; +} + +/** + * Check if a value is a non-null object. + * @param {any} x The value to check. + * @returns {boolean} `true` if the value is a non-null object. + */ +function isNonNullObject(x) { + return typeof x === "object" && x !== null; +} + +/** + * Merge two objects. + * + * Assign every property values of `y` to `x` if `x` doesn't have the property. + * If `x`'s property value is an object, it does recursive. + * + * @param {Object} target The destination to merge + * @param {Object|undefined} source The source to merge. + * @returns {void} + */ +function mergeWithoutOverwrite(target, source) { + if (!isNonNullObject(source)) { + return; + } + + for (const key of Object.keys(source)) { + if (key === "__proto__") { + continue; + } + + if (isNonNullObject(target[key])) { + mergeWithoutOverwrite(target[key], source[key]); + } else if (target[key] === void 0) { + if (isNonNullObject(source[key])) { + target[key] = Array.isArray(source[key]) ? [] : {}; + mergeWithoutOverwrite(target[key], source[key]); + } else if (source[key] !== void 0) { + target[key] = source[key]; + } + } + } +} + +/** + * Merge plugins. + * `target`'s definition is prior to `source`'s. + * + * @param {Record} target The destination to merge + * @param {Record|undefined} source The source to merge. + * @returns {void} + */ +function mergePlugins(target, source) { + if (!isNonNullObject(source)) { + return; + } + + for (const key of Object.keys(source)) { + if (key === "__proto__") { + continue; + } + const targetValue = target[key]; + const sourceValue = source[key]; + + // Adopt the plugin which was found at first. + if (targetValue === void 0) { + if (sourceValue.error) { + throw sourceValue.error; + } + target[key] = sourceValue; + } + } +} + +/** + * Merge rule configs. + * `target`'s definition is prior to `source`'s. + * + * @param {Record} target The destination to merge + * @param {Record|undefined} source The source to merge. + * @returns {void} + */ +function mergeRuleConfigs(target, source) { + if (!isNonNullObject(source)) { + return; + } + + for (const key of Object.keys(source)) { + if (key === "__proto__") { + continue; + } + const targetDef = target[key]; + const sourceDef = source[key]; + + // Adopt the rule config which was found at first. + if (targetDef === void 0) { + if (Array.isArray(sourceDef)) { + target[key] = [...sourceDef]; + } else { + target[key] = [sourceDef]; + } + + /* + * If the first found rule config is severity only and the current rule + * config has options, merge the severity and the options. + */ + } else if ( + targetDef.length === 1 && + Array.isArray(sourceDef) && + sourceDef.length >= 2 + ) { + targetDef.push(...sourceDef.slice(1)); + } + } +} + +/** + * Create the extracted config. + * @param {ConfigArray} instance The config elements. + * @param {number[]} indices The indices to use. + * @returns {ExtractedConfig} The extracted config. + */ +function createConfig(instance, indices) { + const slots = internalSlotsMap.get(instance); + const config = new ExtractedConfig(); + + // Merge elements. + for (const index of indices) { + const element = instance[index]; + + // Adopt the parser which was found at first. + if (!config.parser && element.parser) { + if (element.parser.error) { + throw element.parser.error; + } + config.parser = element.parser; + } + + // Adopt the processor which was found at first. + if (!config.processor && element.processor) { + config.processor = element.processor; + } + + // Merge others. + mergeWithoutOverwrite(config.env, element.env); + mergeWithoutOverwrite(config.globals, element.globals); + mergeWithoutOverwrite(config.parserOptions, element.parserOptions); + mergeWithoutOverwrite(config.settings, element.settings); + mergePlugins(config.plugins, element.plugins, slots); + mergeRuleConfigs(config.rules, element.rules); + } + + return config; +} + +/** + * Collect definitions. + * @template T, U + * @param {string} pluginId The plugin ID for prefix. + * @param {Record} defs The definitions to collect. + * @param {Map} map The map to output. + * @param {function(T): U} [normalize] The normalize function for each value. + * @returns {void} + */ +function collect(pluginId, defs, map, normalize) { + if (defs) { + const prefix = pluginId && `${pluginId}/`; + + for (const [key, value] of Object.entries(defs)) { + map.set( + `${prefix}${key}`, + normalize ? normalize(value) : value + ); + } + } +} + +/** + * Normalize a rule definition. + * @param {Function|Rule} rule The rule definition to normalize. + * @returns {Rule} The normalized rule definition. + */ +function normalizePluginRule(rule) { + return typeof rule === "function" ? { create: rule } : rule; +} + +/** + * Delete the mutation methods from a given map. + * @param {Map} map The map object to delete. + * @returns {void} + */ +function deleteMutationMethods(map) { + Object.defineProperties(map, { + clear: { configurable: true, value: void 0 }, + delete: { configurable: true, value: void 0 }, + set: { configurable: true, value: void 0 } + }); +} + +/** + * Create `envMap`, `processorMap`, `ruleMap` with the plugins in the config array. + * @param {ConfigArrayElement[]} elements The config elements. + * @param {ConfigArrayInternalSlots} slots The internal slots. + * @returns {void} + */ +function initPluginMemberMaps(elements, slots) { + const processed = new Set(); + + slots.envMap = new Map(); + slots.processorMap = new Map(); + slots.ruleMap = new Map(); + + for (const element of elements) { + if (!element.plugins) { + continue; + } + + for (const [pluginId, value] of Object.entries(element.plugins)) { + const plugin = value.definition; + + if (!plugin || processed.has(pluginId)) { + continue; + } + processed.add(pluginId); + + collect(pluginId, plugin.environments, slots.envMap); + collect(pluginId, plugin.processors, slots.processorMap); + collect(pluginId, plugin.rules, slots.ruleMap, normalizePluginRule); + } + } + + deleteMutationMethods(slots.envMap); + deleteMutationMethods(slots.processorMap); + deleteMutationMethods(slots.ruleMap); +} + +/** + * Create `envMap`, `processorMap`, `ruleMap` with the plugins in the config array. + * @param {ConfigArray} instance The config elements. + * @returns {ConfigArrayInternalSlots} The extracted config. + */ +function ensurePluginMemberMaps(instance) { + const slots = internalSlotsMap.get(instance); + + if (!slots.ruleMap) { + initPluginMemberMaps(instance, slots); + } + + return slots; +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * The Config Array. + * + * `ConfigArray` instance contains all settings, parsers, and plugins. + * You need to call `ConfigArray#extractConfig(filePath)` method in order to + * extract, merge and get only the config data which is related to an arbitrary + * file. + * + * @extends {Array} + */ +class ConfigArray extends Array { + + /** + * Get the plugin environments. + * The returned map cannot be mutated. + * @type {ReadonlyMap} The plugin environments. + */ + get pluginEnvironments() { + return ensurePluginMemberMaps(this).envMap; + } + + /** + * Get the plugin processors. + * The returned map cannot be mutated. + * @type {ReadonlyMap} The plugin processors. + */ + get pluginProcessors() { + return ensurePluginMemberMaps(this).processorMap; + } + + /** + * Get the plugin rules. + * The returned map cannot be mutated. + * @returns {ReadonlyMap} The plugin rules. + */ + get pluginRules() { + return ensurePluginMemberMaps(this).ruleMap; + } + + /** + * Check if this config has `root` flag. + * @returns {boolean} `true` if this config array is root. + */ + isRoot() { + for (let i = this.length - 1; i >= 0; --i) { + const root = this[i].root; + + if (typeof root === "boolean") { + return root; + } + } + return false; + } + + /** + * Extract the config data which is related to a given file. + * @param {string} filePath The absolute path to the target file. + * @returns {ExtractedConfig} The extracted config data. + */ + extractConfig(filePath) { + const { cache } = internalSlotsMap.get(this); + const indices = getMatchedIndices(this, filePath); + const cacheKey = indices.join(","); + + if (!cache.has(cacheKey)) { + cache.set(cacheKey, createConfig(this, indices)); + } + + return cache.get(cacheKey); + } +} + +const exportObject = { + ConfigArray, + + /** + * Get the used extracted configs. + * CLIEngine will use this method to collect used deprecated rules. + * @param {ConfigArray} instance The config array object to get. + * @returns {ExtractedConfig[]} The used extracted configs. + * @private + */ + getUsedExtractedConfigs(instance) { + const { cache } = internalSlotsMap.get(instance); + + return Array.from(cache.values()); + } +}; + +module.exports = exportObject; diff --git a/tools/node_modules/eslint/lib/cli-engine/config-array/config-dependency.js b/tools/node_modules/eslint/lib/cli-engine/config-array/config-dependency.js new file mode 100644 index 00000000000000..8db9ff00c5c287 --- /dev/null +++ b/tools/node_modules/eslint/lib/cli-engine/config-array/config-dependency.js @@ -0,0 +1,114 @@ +/** + * @fileoverview `ConfigDependency` class. + * + * `ConfigDependency` class expresses a loaded parser or plugin. + * + * If the parser or plugin was loaded successfully, it has `definition` property + * and `filePath` property. Otherwise, it has `error` property. + * + * When `JSON.stringify()` converted a `ConfigDependency` object to a JSON, it + * omits `definition` property. + * + * `ConfigArrayFactory` creates `ConfigDependency` objects when it loads parsers + * or plugins. + * + * @author Toru Nagashima + */ +"use strict"; + +const util = require("util"); + +/** + * The class is to store parsers or plugins. + * This class hides the loaded object from `JSON.stringify()` and `console.log`. + * @template T + */ +class ConfigDependency { + + /** + * Initialize this instance. + * @param {Object} data The dependency data. + * @param {T} [data.definition] The dependency if the loading succeeded. + * @param {Error} [data.error] The error object if the loading failed. + * @param {string} [data.filePath] The actual path to the dependency if the loading succeeded. + * @param {string} data.id The ID of this dependency. + * @param {string} data.importerName The name of the config file which loads this dependency. + * @param {string} data.importerPath The path to the config file which loads this dependency. + */ + constructor({ + definition = null, + error = null, + filePath = null, + id, + importerName, + importerPath + }) { + + /** + * The loaded dependency if the loading succeeded. + * @type {T|null} + */ + this.definition = definition; + + /** + * The error object if the loading failed. + * @type {Error|null} + */ + this.error = error; + + /** + * The loaded dependency if the loading succeeded. + * @type {string|null} + */ + this.filePath = filePath; + + /** + * The ID of this dependency. + * @type {string} + */ + this.id = id; + + /** + * The name of the config file which loads this dependency. + * @type {string} + */ + this.importerName = importerName; + + /** + * The path to the config file which loads this dependency. + * @type {string} + */ + this.importerPath = importerPath; + } + + /** + * @returns {Object} a JSON compatible object. + */ + toJSON() { + const obj = this[util.inspect.custom](); + + // Display `error.message` (`Error#message` is unenumerable). + if (obj.error instanceof Error) { + obj.error = { ...obj.error, message: obj.error.message }; + } + + return obj; + } + + /** + * @returns {Object} an object to display by `console.log()`. + */ + [util.inspect.custom]() { + const { + definition: _ignore, // eslint-disable-line no-unused-vars + ...obj + } = this; + + return obj; + } +} + +/** @typedef {ConfigDependency} DependentParser */ +/** @typedef {ConfigDependency} DependentPlugin */ + +module.exports = { ConfigDependency }; diff --git a/tools/node_modules/eslint/lib/cli-engine/config-array/extracted-config.js b/tools/node_modules/eslint/lib/cli-engine/config-array/extracted-config.js new file mode 100644 index 00000000000000..377cc0fa91589c --- /dev/null +++ b/tools/node_modules/eslint/lib/cli-engine/config-array/extracted-config.js @@ -0,0 +1,98 @@ +/** + * @fileoverview `ExtractedConfig` class. + * + * `ExtractedConfig` class expresses a final configuration for a specific file. + * + * It provides one method. + * + * - `toCompatibleObjectAsConfigFileContent()` + * Convert this configuration to the compatible object as the content of + * config files. It converts the loaded parser and plugins to strings. + * `CLIEngine#getConfigForFile(filePath)` method uses this method. + * + * `ConfigArray#extractConfig(filePath)` creates a `ExtractedConfig` instance. + * + * @author Toru Nagashima + */ +"use strict"; + +// For VSCode intellisense +/** @typedef {import("../../shared/types").ConfigData} ConfigData */ +/** @typedef {import("../../shared/types").GlobalConf} GlobalConf */ +/** @typedef {import("../../shared/types").SeverityConf} SeverityConf */ +/** @typedef {import("./config-dependency").DependentParser} DependentParser */ +/** @typedef {import("./config-dependency").DependentPlugin} DependentPlugin */ + +/** + * The class for extracted config data. + */ +class ExtractedConfig { + constructor() { + + /** + * Environments. + * @type {Record} + */ + this.env = {}; + + /** + * Global variables. + * @type {Record} + */ + this.globals = {}; + + /** + * Parser definition. + * @type {DependentParser|null} + */ + this.parser = null; + + /** + * Options for the parser. + * @type {Object} + */ + this.parserOptions = {}; + + /** + * Plugin definitions. + * @type {Record} + */ + this.plugins = {}; + + /** + * Processor ID. + * @type {string|null} + */ + this.processor = null; + + /** + * Rule settings. + * @type {Record} + */ + this.rules = {}; + + /** + * Shared settings. + * @type {Object} + */ + this.settings = {}; + } + + /** + * Convert this config to the compatible object as a config file content. + * @returns {ConfigData} The converted object. + */ + toCompatibleObjectAsConfigFileContent() { + const { + processor: _ignore, // eslint-disable-line no-unused-vars + ...config + } = this; + + config.parser = config.parser && config.parser.filePath; + config.plugins = Object.keys(config.plugins).filter(Boolean).reverse(); + + return config; + } +} + +module.exports = { ExtractedConfig }; diff --git a/tools/node_modules/eslint/lib/cli-engine/config-array/index.js b/tools/node_modules/eslint/lib/cli-engine/config-array/index.js new file mode 100644 index 00000000000000..de8831906fd6ef --- /dev/null +++ b/tools/node_modules/eslint/lib/cli-engine/config-array/index.js @@ -0,0 +1,18 @@ +/** + * @fileoverview `ConfigArray` class. + * @author Toru Nagashima + */ +"use strict"; + +const { ConfigArray, getUsedExtractedConfigs } = require("./config-array"); +const { ConfigDependency } = require("./config-dependency"); +const { ExtractedConfig } = require("./extracted-config"); +const { OverrideTester } = require("./override-tester"); + +module.exports = { + ConfigArray, + ConfigDependency, + ExtractedConfig, + OverrideTester, + getUsedExtractedConfigs +}; diff --git a/tools/node_modules/eslint/lib/cli-engine/config-array/override-tester.js b/tools/node_modules/eslint/lib/cli-engine/config-array/override-tester.js new file mode 100644 index 00000000000000..2aaefac7d1c2f5 --- /dev/null +++ b/tools/node_modules/eslint/lib/cli-engine/config-array/override-tester.js @@ -0,0 +1,183 @@ +/** + * @fileoverview `OverrideTester` class. + * + * `OverrideTester` class handles `files` property and `excludedFiles` property + * of `overrides` config. + * + * It provides one method. + * + * - `test(filePath)` + * Test if a file path matches the pair of `files` property and + * `excludedFiles` property. The `filePath` argument must be an absolute + * path. + * + * `ConfigArrayFactory` creates `OverrideTester` objects when it processes + * `overrides` properties. + * + * @author Toru Nagashima + */ +"use strict"; + +const assert = require("assert"); +const path = require("path"); +const util = require("util"); +const { Minimatch } = require("minimatch"); +const minimatchOpts = { dot: true, matchBase: true }; + +/** + * @typedef {Object} Pattern + * @property {InstanceType[] | null} includes The positive matchers. + * @property {InstanceType[] | null} excludes The negative matchers. + */ + +/** + * Normalize a given pattern to an array. + * @param {string|string[]|undefined} patterns A glob pattern or an array of glob patterns. + * @returns {string[]|null} Normalized patterns. + * @private + */ +function normalizePatterns(patterns) { + if (Array.isArray(patterns)) { + return patterns.filter(Boolean); + } + if (typeof patterns === "string" && patterns) { + return [patterns]; + } + return []; +} + +/** + * Create the matchers of given patterns. + * @param {string[]} patterns The patterns. + * @returns {InstanceType[] | null} The matchers. + */ +function toMatcher(patterns) { + if (patterns.length === 0) { + return null; + } + return patterns.map(pattern => new Minimatch(pattern, minimatchOpts)); +} + +/** + * Convert a given matcher to string. + * @param {Pattern} matchers The matchers. + * @returns {string} The string expression of the matcher. + */ +function patternToJson({ includes, excludes }) { + return { + includes: includes && includes.map(m => m.pattern), + excludes: excludes && excludes.map(m => m.pattern) + }; +} + +/** + * The class to test given paths are matched by the patterns. + */ +class OverrideTester { + + /** + * Create a tester with given criteria. + * If there are no criteria, returns `null`. + * @param {string|string[]} files The glob patterns for included files. + * @param {string|string[]} excludedFiles The glob patterns for excluded files. + * @param {string} basePath The path to the base directory to test paths. + * @returns {OverrideTester|null} The created instance or `null`. + */ + static create(files, excludedFiles, basePath) { + const includePatterns = normalizePatterns(files); + const excludePatterns = normalizePatterns(excludedFiles); + const allPatterns = includePatterns.concat(excludePatterns); + + if (allPatterns.length === 0) { + return null; + } + + // Rejects absolute paths or relative paths to parents. + for (const pattern of allPatterns) { + if (path.isAbsolute(pattern) || pattern.includes("..")) { + throw new Error(`Invalid override pattern (expected relative path not containing '..'): ${pattern}`); + } + } + + const includes = toMatcher(includePatterns); + const excludes = toMatcher(excludePatterns); + + return new OverrideTester([{ includes, excludes }], basePath); + } + + /** + * Combine two testers by logical and. + * If either of the testers was `null`, returns the other tester. + * The `basePath` property of the two must be the same value. + * @param {OverrideTester|null} a A tester. + * @param {OverrideTester|null} b Another tester. + * @returns {OverrideTester|null} Combined tester. + */ + static and(a, b) { + if (!b) { + return a; + } + if (!a) { + return b; + } + + assert.strictEqual(a.basePath, b.basePath); + return new OverrideTester(a.patterns.concat(b.patterns), a.basePath); + } + + /** + * Initialize this instance. + * @param {Pattern[]} patterns The matchers. + * @param {string} basePath The base path. + */ + constructor(patterns, basePath) { + + /** @type {Pattern[]} */ + this.patterns = patterns; + + /** @type {string} */ + this.basePath = basePath; + } + + /** + * Test if a given path is matched or not. + * @param {string} filePath The absolute path to the target file. + * @returns {boolean} `true` if the path was matched. + */ + test(filePath) { + if (typeof filePath !== "string" || !path.isAbsolute(filePath)) { + throw new Error(`'filePath' should be an absolute path, but got ${filePath}.`); + } + const relativePath = path.relative(this.basePath, filePath); + + return this.patterns.every(({ includes, excludes }) => ( + (!includes || includes.some(m => m.match(relativePath))) && + (!excludes || !excludes.some(m => m.match(relativePath))) + )); + } + + /** + * @returns {Object} a JSON compatible object. + */ + toJSON() { + if (this.patterns.length === 1) { + return { + ...patternToJson(this.patterns[0]), + basePath: this.basePath + }; + } + return { + AND: this.patterns.map(patternToJson), + basePath: this.basePath + }; + } + + /** + * @returns {Object} an object to display by `console.log()`. + */ + [util.inspect.custom]() { + return this.toJSON(); + } +} + +module.exports = { OverrideTester }; diff --git a/tools/node_modules/eslint/lib/cli-engine/file-enumerator.js b/tools/node_modules/eslint/lib/cli-engine/file-enumerator.js new file mode 100644 index 00000000000000..2840d9fe2da75a --- /dev/null +++ b/tools/node_modules/eslint/lib/cli-engine/file-enumerator.js @@ -0,0 +1,465 @@ +/** + * @fileoverview `FileEnumerator` class. + * + * `FileEnumerator` class has two responsibilities: + * + * 1. Find target files by processing glob patterns. + * 2. Tie each target file and appropriate configuration. + * + * It provies a method: + * + * - `iterateFiles(patterns)` + * Iterate files which are matched by given patterns together with the + * corresponded configuration. This is for `CLIEngine#executeOnFiles()`. + * While iterating files, it loads the configuration file of each directory + * before iterate files on the directory, so we can use the configuration + * files to determine target files. + * + * @example + * const enumerator = new FileEnumerator(); + * const linter = new Linter(); + * + * for (const { config, filePath } of enumerator.iterateFiles(["*.js"])) { + * const code = fs.readFileSync(filePath, "utf8"); + * const messages = linter.verify(code, config, filePath); + * + * console.log(messages); + * } + * + * @author Toru Nagashima + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const fs = require("fs"); +const path = require("path"); +const getGlobParent = require("glob-parent"); +const isGlob = require("is-glob"); +const { escapeRegExp } = require("lodash"); +const { Minimatch } = require("minimatch"); +const { CascadingConfigArrayFactory } = require("./cascading-config-array-factory"); +const { IgnoredPaths } = require("./ignored-paths"); +const debug = require("debug")("eslint:file-enumerator"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const minimatchOpts = { dot: true, matchBase: true }; +const dotfilesPattern = /(?:(?:^\.)|(?:[/\\]\.))[^/\\.].*/u; +const NONE = 0; +const IGNORED_SILENTLY = 1; +const IGNORED = 2; + +// For VSCode intellisense +/** @typedef {ReturnType} ConfigArray */ + +/** + * @typedef {Object} FileEnumeratorOptions + * @property {CascadingConfigArrayFactory} [configArrayFactory] The factory for config arrays. + * @property {string} [cwd] The base directory to start lookup. + * @property {string[]} [extensions] The extensions to match files for directory patterns. + * @property {boolean} [globInputPaths] Set to false to skip glob resolution of input file paths to lint (default: true). If false, each input file paths is assumed to be a non-glob path to an existing file. + * @property {boolean} [ignore] The flag to check ignored files. + * @property {IgnoredPaths} [ignoredPaths] The ignored paths. + * @property {string[]} [rulePaths] The value of `--rulesdir` option. + */ + +/** + * @typedef {Object} FileAndConfig + * @property {string} filePath The path to a target file. + * @property {ConfigArray} config The config entries of that file. + * @property {boolean} ignored If `true` then this file should be ignored and warned because it was directly specified. + */ + +/** + * @typedef {Object} FileEntry + * @property {string} filePath The path to a target file. + * @property {ConfigArray} config The config entries of that file. + * @property {NONE|IGNORED_SILENTLY|IGNORED} flag The flag. + * - `NONE` means the file is a target file. + * - `IGNORED_SILENTLY` means the file should be ignored silently. + * - `IGNORED` means the file should be ignored and warned because it was directly specified. + */ + +/** + * @typedef {Object} FileEnumeratorInternalSlots + * @property {CascadingConfigArrayFactory} configArrayFactory The factory for config arrays. + * @property {string} cwd The base directory to start lookup. + * @property {RegExp} extensionRegExp The RegExp to test if a string ends with specific file extensions. + * @property {boolean} globInputPaths Set to false to skip glob resolution of input file paths to lint (default: true). If false, each input file paths is assumed to be a non-glob path to an existing file. + * @property {boolean} ignoreFlag The flag to check ignored files. + * @property {IgnoredPaths} ignoredPathsWithDotfiles The ignored paths but don't include dot files. + * @property {IgnoredPaths} ignoredPaths The ignored paths. + */ + +/** @type {WeakMap} */ +const internalSlotsMap = new WeakMap(); + +/** + * Check if a string is a glob pattern or not. + * @param {string} pattern A glob pattern. + * @returns {boolean} `true` if the string is a glob pattern. + */ +function isGlobPattern(pattern) { + return isGlob(path.sep === "\\" ? pattern.replace(/\\/gu, "/") : pattern); +} + +/** + * Get stats of a given path. + * @param {string} filePath The path to target file. + * @returns {fs.Stats|null} The stats. + * @private + */ +function statSafeSync(filePath) { + try { + return fs.statSync(filePath); + } catch (error) { + /* istanbul ignore next */ + if (error.code !== "ENOENT") { + throw error; + } + return null; + } +} + +/** + * Get filenames in a given path to a directory. + * @param {string} directoryPath The path to target directory. + * @returns {string[]} The filenames. + * @private + */ +function readdirSafeSync(directoryPath) { + try { + return fs.readdirSync(directoryPath); + } catch (error) { + /* istanbul ignore next */ + if (error.code !== "ENOENT") { + throw error; + } + return []; + } +} + +/** + * The error type when no files match a glob. + */ +class NoFilesFoundError extends Error { + + /** + * @param {string} pattern - The glob pattern which was not found. + * @param {boolean} globDisabled - If `true` then the pattern was a glob pattern, but glob was disabled. + */ + constructor(pattern, globDisabled) { + super(`No files matching '${pattern}' were found${globDisabled ? " (glob was disabled)" : ""}.`); + this.messageTemplate = "file-not-found"; + this.messageData = { pattern, globDisabled }; + } +} + +/** + * 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 }; + } +} + +/** + * This class provides the functionality that enumerates every file which is + * matched by given glob patterns and that configuration. + */ +class FileEnumerator { + + /** + * Initialize this enumerator. + * @param {FileEnumeratorOptions} options The options. + */ + constructor({ + cwd = process.cwd(), + configArrayFactory = new CascadingConfigArrayFactory({ cwd }), + extensions = [".js"], + globInputPaths = true, + ignore = true, + ignoredPaths = new IgnoredPaths({ cwd, ignore }) + } = {}) { + internalSlotsMap.set(this, { + configArrayFactory, + cwd, + extensionRegExp: new RegExp( + `.\\.(?:${extensions + .map(ext => escapeRegExp( + ext.startsWith(".") + ? ext.slice(1) + : ext + )) + .join("|") + })$`, + "u" + ), + globInputPaths, + ignoreFlag: ignore, + ignoredPaths, + ignoredPathsWithDotfiles: new IgnoredPaths({ + ...ignoredPaths.options, + dotfiles: true + }) + }); + } + + /** + * The `RegExp` object that tests if a file path has the allowed file extensions. + * @type {RegExp} + */ + get extensionRegExp() { + return internalSlotsMap.get(this).extensionRegExp; + } + + /** + * Iterate files which are matched by given glob patterns. + * @param {string|string[]} patternOrPatterns The glob patterns to iterate files. + * @returns {IterableIterator} The found files. + */ + *iterateFiles(patternOrPatterns) { + const { globInputPaths } = internalSlotsMap.get(this); + const patterns = Array.isArray(patternOrPatterns) + ? patternOrPatterns + : [patternOrPatterns]; + + debug("Start to iterate files: %o", patterns); + + // The set of paths to remove duplicate. + const set = new Set(); + + for (const pattern of patterns) { + let foundRegardlessOfIgnored = false; + let found = false; + + // Skip empty string. + if (!pattern) { + continue; + } + + // Iterate files of this pttern. + for (const { config, filePath, flag } of this._iterateFiles(pattern)) { + foundRegardlessOfIgnored = true; + if (flag === IGNORED_SILENTLY) { + continue; + } + found = true; + + // Remove duplicate paths while yielding paths. + if (!set.has(filePath)) { + set.add(filePath); + yield { + config, + filePath, + ignored: flag === IGNORED + }; + } + } + + // Raise an error if any files were not found. + if (!foundRegardlessOfIgnored) { + throw new NoFilesFoundError( + pattern, + !globInputPaths && isGlob(pattern) + ); + } + if (!found) { + throw new AllFilesIgnoredError(pattern); + } + } + + debug(`Complete iterating files: ${JSON.stringify(patterns)}`); + } + + /** + * Iterate files which are matched by a given glob pattern. + * @param {string} pattern The glob pattern to iterate files. + * @returns {IterableIterator} The found files. + */ + _iterateFiles(pattern) { + const { cwd, globInputPaths } = internalSlotsMap.get(this); + const absolutePath = path.resolve(cwd, pattern); + + if (globInputPaths && isGlobPattern(pattern)) { + return this._iterateFilesWithGlob( + absolutePath, + dotfilesPattern.test(pattern) + ); + } + + const stat = statSafeSync(absolutePath); + + if (stat && stat.isDirectory()) { + return this._iterateFilesWithDirectory( + absolutePath, + dotfilesPattern.test(pattern) + ); + } + + if (stat && stat.isFile()) { + return this._iterateFilesWithFile(absolutePath); + } + + return []; + } + + /** + * Iterate a file which is matched by a given path. + * @param {string} filePath The path to the target file. + * @returns {IterableIterator} The found files. + * @private + */ + _iterateFilesWithFile(filePath) { + debug(`File: ${filePath}`); + + const { configArrayFactory } = internalSlotsMap.get(this); + const config = configArrayFactory.getConfigArrayForFile(filePath); + const ignored = this._isIgnoredFile(filePath, { direct: true }); + const flag = ignored ? IGNORED : NONE; + + return [{ config, filePath, flag }]; + } + + /** + * Iterate files in a given path. + * @param {string} directoryPath The path to the target directory. + * @param {boolean} dotfiles If `true` then it doesn't skip dot files by default. + * @returns {IterableIterator} The found files. + * @private + */ + _iterateFilesWithDirectory(directoryPath, dotfiles) { + debug(`Directory: ${directoryPath}`); + + return this._iterateFilesRecursive( + directoryPath, + { dotfiles, recursive: true, selector: null } + ); + } + + /** + * Iterate files which are matched by a given glob pattern. + * @param {string} pattern The glob pattern to iterate files. + * @param {boolean} dotfiles If `true` then it doesn't skip dot files by default. + * @returns {IterableIterator} The found files. + * @private + */ + _iterateFilesWithGlob(pattern, dotfiles) { + debug(`Glob: ${pattern}`); + + const directoryPath = getGlobParent(pattern); + const globPart = pattern.slice(directoryPath.length + 1); + + /* + * recursive if there are `**` or path separators in the glob part. + * Otherwise, patterns such as `src/*.js`, it doesn't need recursive. + */ + const recursive = /\*\*|\/|\\/u.test(globPart); + const selector = new Minimatch(pattern, minimatchOpts); + + debug(`recursive? ${recursive}`); + + return this._iterateFilesRecursive( + directoryPath, + { dotfiles, recursive, selector } + ); + } + + /** + * Iterate files in a given path. + * @param {string} directoryPath The path to the target directory. + * @param {Object} options The options to iterate files. + * @param {boolean} [options.dotfiles] If `true` then it doesn't skip dot files by default. + * @param {boolean} [options.recursive] If `true` then it dives into sub directories. + * @param {InstanceType} [options.selector] The matcher to choose files. + * @returns {IterableIterator} The found files. + * @private + */ + *_iterateFilesRecursive(directoryPath, options) { + if (this._isIgnoredFile(directoryPath + path.sep, options)) { + return; + } + debug(`Enter the directory: ${directoryPath}`); + const { configArrayFactory, extensionRegExp } = internalSlotsMap.get(this); + + /** @type {ConfigArray|null} */ + let config = null; + + // Enumerate the files of this directory. + for (const filename of readdirSafeSync(directoryPath)) { + const filePath = path.join(directoryPath, filename); + const stat = statSafeSync(filePath); // TODO: Use `withFileTypes` in the future. + + // Check if the file is matched. + if (stat && stat.isFile()) { + if (!config) { + config = configArrayFactory.getConfigArrayForFile(filePath); + } + const ignored = this._isIgnoredFile(filePath, options); + const flag = ignored ? IGNORED_SILENTLY : NONE; + const matched = options.selector + + // Started with a glob pattern; choose by the pattern. + ? options.selector.match(filePath) + + // Started with a directory path; choose by file extensions. + : extensionRegExp.test(filePath); + + if (matched) { + debug(`Yield: ${filename}${ignored ? " but ignored" : ""}`); + yield { config, filePath, flag }; + } else { + debug(`Didn't match: ${filename}`); + } + + // Dive into the sub directory. + } else if (options.recursive && stat && stat.isDirectory()) { + yield* this._iterateFilesRecursive(filePath, options); + } + } + + debug(`Leave the directory: ${directoryPath}`); + } + + /** + * Check if a given file should be ignored. + * @param {string} filePath The path to a file to check. + * @param {Object} options Options + * @param {boolean} [options.dotfiles] If `true` then this is not ignore dot files by default. + * @param {boolean} [options.direct] If `true` then this is a direct specified file. + * @returns {boolean} `true` if the file should be ignored. + * @private + */ + _isIgnoredFile(filePath, { dotfiles = false, direct = false }) { + const { + ignoreFlag, + ignoredPaths, + ignoredPathsWithDotfiles + } = internalSlotsMap.get(this); + const adoptedIgnoredPaths = dotfiles + ? ignoredPathsWithDotfiles + : ignoredPaths; + + return ignoreFlag + ? adoptedIgnoredPaths.contains(filePath) + : (!direct && adoptedIgnoredPaths.contains(filePath, "default")); + } +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = { FileEnumerator }; diff --git a/tools/node_modules/eslint/lib/formatters/checkstyle.js b/tools/node_modules/eslint/lib/cli-engine/formatters/checkstyle.js similarity index 97% rename from tools/node_modules/eslint/lib/formatters/checkstyle.js rename to tools/node_modules/eslint/lib/cli-engine/formatters/checkstyle.js index c807871930bdec..ba4d1b5b3ec532 100644 --- a/tools/node_modules/eslint/lib/formatters/checkstyle.js +++ b/tools/node_modules/eslint/lib/cli-engine/formatters/checkstyle.js @@ -4,7 +4,7 @@ */ "use strict"; -const xmlEscape = require("../util/xml-escape"); +const xmlEscape = require("../xml-escape"); //------------------------------------------------------------------------------ // Helper Functions diff --git a/tools/node_modules/eslint/lib/formatters/codeframe.js b/tools/node_modules/eslint/lib/cli-engine/formatters/codeframe.js similarity index 100% rename from tools/node_modules/eslint/lib/formatters/codeframe.js rename to tools/node_modules/eslint/lib/cli-engine/formatters/codeframe.js diff --git a/tools/node_modules/eslint/lib/formatters/compact.js b/tools/node_modules/eslint/lib/cli-engine/formatters/compact.js similarity index 100% rename from tools/node_modules/eslint/lib/formatters/compact.js rename to tools/node_modules/eslint/lib/cli-engine/formatters/compact.js diff --git a/tools/node_modules/eslint/lib/formatters/html-template-message.html b/tools/node_modules/eslint/lib/cli-engine/formatters/html-template-message.html similarity index 100% rename from tools/node_modules/eslint/lib/formatters/html-template-message.html rename to tools/node_modules/eslint/lib/cli-engine/formatters/html-template-message.html diff --git a/tools/node_modules/eslint/lib/formatters/html-template-page.html b/tools/node_modules/eslint/lib/cli-engine/formatters/html-template-page.html similarity index 100% rename from tools/node_modules/eslint/lib/formatters/html-template-page.html rename to tools/node_modules/eslint/lib/cli-engine/formatters/html-template-page.html diff --git a/tools/node_modules/eslint/lib/formatters/html-template-result.html b/tools/node_modules/eslint/lib/cli-engine/formatters/html-template-result.html similarity index 100% rename from tools/node_modules/eslint/lib/formatters/html-template-result.html rename to tools/node_modules/eslint/lib/cli-engine/formatters/html-template-result.html diff --git a/tools/node_modules/eslint/lib/formatters/html.js b/tools/node_modules/eslint/lib/cli-engine/formatters/html.js similarity index 100% rename from tools/node_modules/eslint/lib/formatters/html.js rename to tools/node_modules/eslint/lib/cli-engine/formatters/html.js diff --git a/tools/node_modules/eslint/lib/formatters/jslint-xml.js b/tools/node_modules/eslint/lib/cli-engine/formatters/jslint-xml.js similarity index 95% rename from tools/node_modules/eslint/lib/formatters/jslint-xml.js rename to tools/node_modules/eslint/lib/cli-engine/formatters/jslint-xml.js index 14743430d8ff94..0ca1cbaed1a3cc 100644 --- a/tools/node_modules/eslint/lib/formatters/jslint-xml.js +++ b/tools/node_modules/eslint/lib/cli-engine/formatters/jslint-xml.js @@ -4,7 +4,7 @@ */ "use strict"; -const xmlEscape = require("../util/xml-escape"); +const xmlEscape = require("../xml-escape"); //------------------------------------------------------------------------------ // Public Interface diff --git a/tools/node_modules/eslint/lib/formatters/json-with-metadata.js b/tools/node_modules/eslint/lib/cli-engine/formatters/json-with-metadata.js similarity index 100% rename from tools/node_modules/eslint/lib/formatters/json-with-metadata.js rename to tools/node_modules/eslint/lib/cli-engine/formatters/json-with-metadata.js diff --git a/tools/node_modules/eslint/lib/formatters/json.js b/tools/node_modules/eslint/lib/cli-engine/formatters/json.js similarity index 100% rename from tools/node_modules/eslint/lib/formatters/json.js rename to tools/node_modules/eslint/lib/cli-engine/formatters/json.js diff --git a/tools/node_modules/eslint/lib/formatters/junit.js b/tools/node_modules/eslint/lib/cli-engine/formatters/junit.js similarity index 97% rename from tools/node_modules/eslint/lib/formatters/junit.js rename to tools/node_modules/eslint/lib/cli-engine/formatters/junit.js index 77d548f380e2b6..c12736751d3ff2 100644 --- a/tools/node_modules/eslint/lib/formatters/junit.js +++ b/tools/node_modules/eslint/lib/cli-engine/formatters/junit.js @@ -4,7 +4,7 @@ */ "use strict"; -const xmlEscape = require("../util/xml-escape"); +const xmlEscape = require("../xml-escape"); //------------------------------------------------------------------------------ // Helper Functions diff --git a/tools/node_modules/eslint/lib/formatters/stylish.js b/tools/node_modules/eslint/lib/cli-engine/formatters/stylish.js similarity index 100% rename from tools/node_modules/eslint/lib/formatters/stylish.js rename to tools/node_modules/eslint/lib/cli-engine/formatters/stylish.js diff --git a/tools/node_modules/eslint/lib/formatters/table.js b/tools/node_modules/eslint/lib/cli-engine/formatters/table.js similarity index 100% rename from tools/node_modules/eslint/lib/formatters/table.js rename to tools/node_modules/eslint/lib/cli-engine/formatters/table.js diff --git a/tools/node_modules/eslint/lib/formatters/tap.js b/tools/node_modules/eslint/lib/cli-engine/formatters/tap.js similarity index 100% rename from tools/node_modules/eslint/lib/formatters/tap.js rename to tools/node_modules/eslint/lib/cli-engine/formatters/tap.js diff --git a/tools/node_modules/eslint/lib/formatters/unix.js b/tools/node_modules/eslint/lib/cli-engine/formatters/unix.js similarity index 100% rename from tools/node_modules/eslint/lib/formatters/unix.js rename to tools/node_modules/eslint/lib/cli-engine/formatters/unix.js diff --git a/tools/node_modules/eslint/lib/formatters/visualstudio.js b/tools/node_modules/eslint/lib/cli-engine/formatters/visualstudio.js similarity index 100% rename from tools/node_modules/eslint/lib/formatters/visualstudio.js rename to tools/node_modules/eslint/lib/cli-engine/formatters/visualstudio.js diff --git a/tools/node_modules/eslint/lib/util/hash.js b/tools/node_modules/eslint/lib/cli-engine/hash.js similarity index 100% rename from tools/node_modules/eslint/lib/util/hash.js rename to tools/node_modules/eslint/lib/cli-engine/hash.js diff --git a/tools/node_modules/eslint/lib/util/ignored-paths.js b/tools/node_modules/eslint/lib/cli-engine/ignored-paths.js similarity index 88% rename from tools/node_modules/eslint/lib/util/ignored-paths.js rename to tools/node_modules/eslint/lib/cli-engine/ignored-paths.js index 41bc3f48c84e3b..137d156e9c05af 100644 --- a/tools/node_modules/eslint/lib/util/ignored-paths.js +++ b/tools/node_modules/eslint/lib/cli-engine/ignored-paths.js @@ -11,8 +11,7 @@ const fs = require("fs"), path = require("path"), - ignore = require("ignore"), - pathUtils = require("./path-utils"); + ignore = require("ignore"); const debug = require("debug")("eslint:ignored-paths"); @@ -168,7 +167,11 @@ class IgnoredPaths { debug("Using specific ignore file"); try { - fs.statSync(options.ignorePath); + const stat = fs.statSync(options.ignorePath); + + if (!stat.isFile()) { + throw new Error(`${options.ignorePath} is not a file`); + } ignorePath = options.ignorePath; } catch (e) { e.message = `Cannot read ignore file: ${options.ignorePath}\nError: ${e.message}`; @@ -325,57 +328,35 @@ class IgnoredPaths { * @returns {boolean} true if the file path matches one or more patterns, false otherwise */ contains(filepath, category) { - + const isDir = filepath.endsWith(path.sep) || + (path.sep === "\\" && filepath.endsWith("/")); let result = false; + const basePath = this.getBaseDir(); const absolutePath = path.resolve(this.options.cwd, filepath); - const relativePath = pathUtils.getRelativePath(absolutePath, this.getBaseDir()); + let relativePath = path.relative(basePath, absolutePath); - 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); + if (relativePath) { + if (isDir) { + relativePath += path.sep; + } + 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); + debug(" target = %j", filepath); + debug(" base = %j", basePath); + debug(" relative = %j", relativePath); + 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; +module.exports = { IgnoredPaths }; diff --git a/tools/node_modules/eslint/lib/cli-engine/index.js b/tools/node_modules/eslint/lib/cli-engine/index.js new file mode 100644 index 00000000000000..52e45a6d7910a0 --- /dev/null +++ b/tools/node_modules/eslint/lib/cli-engine/index.js @@ -0,0 +1,7 @@ +"use strict"; + +const { CLIEngine } = require("./cli-engine"); + +module.exports = { + CLIEngine +}; diff --git a/tools/node_modules/eslint/lib/util/lint-result-cache.js b/tools/node_modules/eslint/lib/cli-engine/lint-result-cache.js similarity index 80% rename from tools/node_modules/eslint/lib/util/lint-result-cache.js rename to tools/node_modules/eslint/lib/cli-engine/lint-result-cache.js index f1e5aabfebf324..9408780fb022c6 100644 --- a/tools/node_modules/eslint/lib/util/lint-result-cache.js +++ b/tools/node_modules/eslint/lib/cli-engine/lint-result-cache.js @@ -8,12 +8,12 @@ // 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"); +const assert = require("assert"); +const fs = require("fs"); +const fileEntryCache = require("file-entry-cache"); +const stringify = require("json-stable-stringify-without-jsonify"); +const pkg = require("../../package.json"); +const hash = require("./hash"); //----------------------------------------------------------------------------- // Helpers @@ -22,14 +22,11 @@ const assert = require("assert"), 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 + * Calculates the hash of the config + * @param {ConfigArray} config The config. * @returns {string} The hash of the config */ -function hashOfConfigFor(configHelper, filename) { - const config = configHelper.getConfig(filename); - +function hashOfConfigFor(config) { if (!configHashCache.has(config)) { configHashCache.set(config, hash(`${pkg.version}_${stringify(config)}`)); } @@ -52,15 +49,12 @@ 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) { + constructor(cacheFileLocation) { assert(cacheFileLocation, "Cache file location is required"); - assert(configHelper, "Config helper is required"); this.fileEntryCache = fileEntryCache.create(cacheFileLocation); - this.configHelper = configHelper; } /** @@ -68,10 +62,11 @@ class LintResultCache { * 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. + * @param {ConfigArray} config The config of the file. * @returns {Object|null} The rebuilt lint results, or null if the file is * changed or not in the filesystem. */ - getCachedLintResults(filePath) { + getCachedLintResults(filePath, config) { /* * Cached lint results are valid if and only if: @@ -83,7 +78,7 @@ class LintResultCache { */ const fileDescriptor = this.fileEntryCache.getFileDescriptor(filePath); - const hashOfConfig = hashOfConfigFor(this.configHelper, filePath); + const hashOfConfig = hashOfConfigFor(config); const changed = fileDescriptor.changed || fileDescriptor.meta.hashOfConfig !== hashOfConfig; if (fileDescriptor.notFound || changed) { @@ -105,10 +100,11 @@ class LintResultCache { * 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 {ConfigArray} config The config of the file. * @param {Object} result The lint result to be set for the file. * @returns {void} */ - setCachedLintResults(filePath, result) { + setCachedLintResults(filePath, config, result) { if (result && Object.prototype.hasOwnProperty.call(result, "output")) { return; } @@ -130,7 +126,7 @@ class LintResultCache { } fileDescriptor.meta.results = resultToSerialize; - fileDescriptor.meta.hashOfConfig = hashOfConfigFor(this.configHelper, result.filePath); + fileDescriptor.meta.hashOfConfig = hashOfConfigFor(config); } } diff --git a/tools/node_modules/eslint/lib/load-rules.js b/tools/node_modules/eslint/lib/cli-engine/load-rules.js similarity index 90% rename from tools/node_modules/eslint/lib/load-rules.js rename to tools/node_modules/eslint/lib/cli-engine/load-rules.js index a7383624651c33..81bab63fab6330 100644 --- a/tools/node_modules/eslint/lib/load-rules.js +++ b/tools/node_modules/eslint/lib/cli-engine/load-rules.js @@ -22,7 +22,7 @@ const rulesDirCache = {}; * 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). + * @returns {Object} Loaded rule modules. */ module.exports = function(relativeRulesDir, cwd) { const rulesDir = path.resolve(cwd, relativeRulesDir); @@ -38,7 +38,7 @@ module.exports = function(relativeRulesDir, cwd) { if (path.extname(file) !== ".js") { return; } - rules[file.slice(0, -3)] = path.join(rulesDir, file); + rules[file.slice(0, -3)] = require(path.join(rulesDir, file)); }); rulesDirCache[rulesDir] = rules; diff --git a/tools/node_modules/eslint/lib/util/naming.js b/tools/node_modules/eslint/lib/cli-engine/naming.js similarity index 83% rename from tools/node_modules/eslint/lib/util/naming.js rename to tools/node_modules/eslint/lib/cli-engine/naming.js index ea1cc9518ea1c0..b99155f15cafa7 100644 --- a/tools/node_modules/eslint/lib/util/naming.js +++ b/tools/node_modules/eslint/lib/cli-engine/naming.js @@ -3,16 +3,6 @@ */ "use strict"; -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const pathUtils = require("../util/path-utils"); - -//------------------------------------------------------------------------------ -// Private -//------------------------------------------------------------------------------ - const NAMESPACE_REGEX = /^@.*\//iu; /** @@ -30,8 +20,8 @@ function normalizePackageName(name, prefix) { * 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.includes("\\")) { + normalizedName = normalizedName.replace(/\\/gu, "/"); } if (normalizedName.charAt(0) === "@") { @@ -53,7 +43,7 @@ function normalizePackageName(name, prefix) { */ normalizedName = normalizedName.replace(/^@([^/]+)\/(.*)$/u, `@$1/${prefix}-$2`); } - } else if (normalizedName.indexOf(`${prefix}-`) !== 0) { + } else if (!normalizedName.startsWith(`${prefix}-`)) { normalizedName = `${prefix}-${normalizedName}`; } diff --git a/tools/node_modules/eslint/lib/util/xml-escape.js b/tools/node_modules/eslint/lib/cli-engine/xml-escape.js similarity index 100% rename from tools/node_modules/eslint/lib/util/xml-escape.js rename to tools/node_modules/eslint/lib/cli-engine/xml-escape.js diff --git a/tools/node_modules/eslint/lib/cli.js b/tools/node_modules/eslint/lib/cli.js index 9ce81e55425ec5..c34545544b1040 100644 --- a/tools/node_modules/eslint/lib/cli.js +++ b/tools/node_modules/eslint/lib/cli.js @@ -17,10 +17,10 @@ const fs = require("fs"), path = require("path"), - options = require("./options"), - CLIEngine = require("./cli-engine"), mkdirp = require("mkdirp"), - log = require("./util/logging"); + { CLIEngine } = require("./cli-engine"), + options = require("./options"), + log = require("./shared/logging"); const debug = require("debug")("eslint:cli"); @@ -66,7 +66,8 @@ function translateOptions(cliOptions) { fix: (cliOptions.fix || cliOptions.fixDryRun) && (cliOptions.quiet ? quietFixPredicate : true), fixTypes: cliOptions.fixType, allowInlineConfig: cliOptions.inlineConfig, - reportUnusedDisableDirectives: cliOptions.reportUnusedDisableDirectives + reportUnusedDisableDirectives: cliOptions.reportUnusedDisableDirectives, + resolvePluginsRelativeTo: cliOptions.resolvePluginsRelativeTo }; } @@ -81,24 +82,27 @@ function translateOptions(cliOptions) { */ function printResults(engine, results, format, outputFile) { let formatter; - let rules; + let rulesMeta; try { formatter = engine.getFormatter(format); - rules = engine.getRules(); } catch (e) { log.error(e.message); return false; } - const rulesMeta = {}; - - rules.forEach((rule, ruleId) => { - rulesMeta[ruleId] = rule.meta; + const output = formatter(results, { + get rulesMeta() { + if (!rulesMeta) { + rulesMeta = {}; + for (const [ruleId, rule] of engine.getRules()) { + rulesMeta[ruleId] = rule.meta; + } + } + return rulesMeta; + } }); - const output = formatter(results, { rulesMeta }); - if (output) { if (outputFile) { const filePath = path.resolve(process.cwd(), outputFile); 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/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 80344f50973df2..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/u, ""); -} - -/** - * 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|@/u.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, ruleMap.get.bind(ruleMap), configContext.linterContext.environments, resolvedPath.configFullName); - - /* - * 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-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/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 029e7b106dbcfe..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+/u)) { - 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/config/autoconfig.js b/tools/node_modules/eslint/lib/init/autoconfig.js similarity index 98% rename from tools/node_modules/eslint/lib/config/autoconfig.js rename to tools/node_modules/eslint/lib/init/autoconfig.js index f2c707be843876..19c4986c31bbfe 100644 --- a/tools/node_modules/eslint/lib/config/autoconfig.js +++ b/tools/node_modules/eslint/lib/init/autoconfig.js @@ -10,10 +10,10 @@ //------------------------------------------------------------------------------ const lodash = require("lodash"), - Linter = require("../linter"), - configRule = require("./config-rule"), - ConfigOps = require("./config-ops"), - recConfig = require("../../conf/eslint-recommended"); + recConfig = require("../../conf/eslint-recommended"), + ConfigOps = require("../shared/config-ops"), + { Linter } = require("../linter"), + configRule = require("./config-rule"); const debug = require("debug")("eslint:autoconfig"); const linter = new Linter(); diff --git a/tools/node_modules/eslint/lib/init/config-file.js b/tools/node_modules/eslint/lib/init/config-file.js new file mode 100644 index 00000000000000..77f14a47299cde --- /dev/null +++ b/tools/node_modules/eslint/lib/init/config-file.js @@ -0,0 +1,144 @@ +/** + * @fileoverview Helper to locate and load configuration files. + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const fs = require("fs"), + path = require("path"), + stringify = require("json-stable-stringify-without-jsonify"); + +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 +//------------------------------------------------------------------------------ + +/** + * 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."); + } +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = { + write +}; diff --git a/tools/node_modules/eslint/lib/config/config-initializer.js b/tools/node_modules/eslint/lib/init/config-initializer.js similarity index 94% rename from tools/node_modules/eslint/lib/config/config-initializer.js rename to tools/node_modules/eslint/lib/init/config-initializer.js index adaf6c15840b8a..4d52377d26789a 100644 --- a/tools/node_modules/eslint/lib/config/config-initializer.js +++ b/tools/node_modules/eslint/lib/init/config-initializer.js @@ -11,17 +11,18 @@ //------------------------------------------------------------------------------ const util = require("util"), + path = require("path"), inquirer = require("inquirer"), ProgressBar = require("progress"), semver = require("semver"), + recConfig = require("../../conf/eslint-recommended"), + ConfigOps = require("../shared/config-ops"), + log = require("../shared/logging"), + ModuleResolver = require("../shared/relative-module-resolver"), 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"); + npmUtils = require("./npm-utils"), + { getSourceCodeOfFiles } = require("./source-code-utils"); const debug = require("debug")("eslint:config-initializer"); @@ -307,34 +308,13 @@ function processAnswers(answers) { 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 eslintPath = ModuleResolver.resolve("eslint", path.join(process.cwd(), "__placeholder__.js")); const eslint = require(eslintPath); return eslint.linter.version || null; @@ -573,7 +553,16 @@ function promptUser() { earlyAnswers.styleguide = "airbnb-base"; } - const config = ConfigOps.merge(processAnswers(earlyAnswers), getConfigForStyleGuide(earlyAnswers.styleguide)); + const config = processAnswers(earlyAnswers); + + if (Array.isArray(config.extends)) { + config.extends.push(earlyAnswers.styleguide); + } else if (config.extends) { + config.extends = [config.extends, earlyAnswers.styleguide]; + } else { + config.extends = [earlyAnswers.styleguide]; + } + const modules = getModulesList(config); return askInstallModules(modules, earlyAnswers.packageJsonExists) @@ -617,13 +606,6 @@ function promptUser() { 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); @@ -631,7 +613,7 @@ function promptUser() { const config = processAnswers(totalAnswers); const modules = getModulesList(config); - return askInstallModules(modules).then(() => writeFile(config, answers.format)); + return askInstallModules(modules).then(() => writeFile(config, earlyAnswers.format)); }); }); } @@ -641,7 +623,6 @@ function promptUser() { //------------------------------------------------------------------------------ const init = { - getConfigForStyleGuide, getModulesList, hasESLintVersionConflict, installModules, diff --git a/tools/node_modules/eslint/lib/config/config-rule.js b/tools/node_modules/eslint/lib/init/config-rule.js similarity index 95% rename from tools/node_modules/eslint/lib/config/config-rule.js rename to tools/node_modules/eslint/lib/init/config-rule.js index 29aac0b9a1a518..fbe9b779ab7f54 100644 --- a/tools/node_modules/eslint/lib/config/config-rule.js +++ b/tools/node_modules/eslint/lib/init/config-rule.js @@ -9,10 +9,7 @@ // Requirements //------------------------------------------------------------------------------ -const Rules = require("../rules"), - builtInRules = require("../built-in-rules-index"); - -const rules = new Rules(); +const builtInRules = require("../rules"); //------------------------------------------------------------------------------ // Helpers @@ -296,12 +293,17 @@ function generateConfigsFromSchema(schema) { /** * Generate possible rule configurations for all of the core rules + * @param {boolean} noDeprecated Indicates whether ignores deprecated rules or not. * @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); +function createCoreRuleConfigs(noDeprecated = false) { + return Array.from(builtInRules).reduce((accumulator, [id, rule]) => { const schema = (typeof rule === "function") ? rule.schema : rule.meta.schema; + const isDeprecated = (typeof rule === "function") ? rule.deprecated : rule.meta.deprecated; + + if (noDeprecated && isDeprecated) { + return accumulator; + } accumulator[id] = generateConfigsFromSchema(schema); return accumulator; diff --git a/tools/node_modules/eslint/lib/util/npm-utils.js b/tools/node_modules/eslint/lib/init/npm-utils.js similarity index 99% rename from tools/node_modules/eslint/lib/util/npm-utils.js rename to tools/node_modules/eslint/lib/init/npm-utils.js index ddf8f24cc76993..26e78406fdcdc6 100644 --- a/tools/node_modules/eslint/lib/util/npm-utils.js +++ b/tools/node_modules/eslint/lib/init/npm-utils.js @@ -12,7 +12,7 @@ const fs = require("fs"), spawn = require("cross-spawn"), path = require("path"), - log = require("./logging"); + log = require("../shared/logging"); //------------------------------------------------------------------------------ // Helpers diff --git a/tools/node_modules/eslint/lib/util/source-code-utils.js b/tools/node_modules/eslint/lib/init/source-code-utils.js similarity index 57% rename from tools/node_modules/eslint/lib/util/source-code-utils.js rename to tools/node_modules/eslint/lib/init/source-code-utils.js index cac13d37067dfc..dfc170a65cf71b 100644 --- a/tools/node_modules/eslint/lib/util/source-code-utils.js +++ b/tools/node_modules/eslint/lib/init/source-code-utils.js @@ -9,9 +9,21 @@ // Requirements //------------------------------------------------------------------------------ -const CLIEngine = require("../cli-engine"), - globUtils = require("./glob-utils"), - baseDefaultOptions = require("../../conf/default-cli-options"); +const { CLIEngine } = require("../cli-engine"); + +/* + * This is used for: + * + * 1. Enumerate target file because we have not expose such a API on `CLIEngine` + * (https://github.com/eslint/eslint/issues/11222). + * 2. Create `SourceCode` instances. Because we don't have any function which + * instantiate `SourceCode` so it needs to take the created `SourceCode` + * instance out after linting. + * + * TODO1: Expose the API that enumerates target files. + * TODO2: Extract the creation logic of `SourceCode` from `Linter` class. + */ +const { getCLIEngineInternalSlots } = require("../cli-engine/cli-engine"); // eslint-disable-line no-restricted-modules const debug = require("debug")("eslint:source-code-utils"); @@ -22,22 +34,23 @@ const debug = require("debug")("eslint:source-code-utils"); /** * 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. + * @param {Object} engine A CLIEngine. * @returns {Array} Array of the SourceCode object representing the file * and fatal error message. */ -function getSourceCodeOfFile(filename, options) { +function getSourceCodeOfFile(filename, engine) { debug("getting sourceCode of", filename); - const opts = Object.assign({}, options, { rules: {} }); - const cli = new CLIEngine(opts); - const results = cli.executeOnFiles([filename]); + const results = engine.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(); + + // TODO: extract the logic that creates source code objects to `SourceCode#parse(text, options)` or something like. + const { linter } = getCLIEngineInternalSlots(engine); + const sourceCode = linter.getSourceCode(); return sourceCode; } @@ -56,38 +69,28 @@ function getSourceCodeOfFile(filename, options) { /** * 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 + * @param {Object} options A CLIEngine options object. If not provided, the default cli options will be used. + * @param {progressCallback} callback Callback for reporting execution status * @returns {Object} The SourceCode of all processed files. */ -function getSourceCodeOfFiles(patterns, providedOptions, providedCallback) { +function getSourceCodeOfFiles(patterns, options, callback) { 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 engine = new CLIEngine({ ...options, rules: {} }); - const filenames = globUtils.listFilesToProcess(globPatternsList, options) - .filter(fileInfo => !fileInfo.ignored) - .reduce((files, fileInfo) => files.concat(fileInfo.filename), []); + // TODO: make file iteration as a public API and use it. + const { fileEnumerator } = getCLIEngineInternalSlots(engine); + const filenames = + Array.from(fileEnumerator.iterateFiles(globPatternsList)) + .filter(entry => !entry.ignored) + .map(entry => entry.filePath); if (filenames.length === 0) { debug(`Did not find any files matching pattern(s): ${globPatternsList}`); } + filenames.forEach(filename => { - const sourceCode = getSourceCodeOfFile(filename, options); + const sourceCode = getSourceCodeOfFile(filename, engine); if (sourceCode) { debug("got sourceCode of", filename); @@ -97,6 +100,7 @@ function getSourceCodeOfFiles(patterns, providedOptions, providedCallback) { callback(filenames.length); // eslint-disable-line callback-return } }); + return sourceCodes; } diff --git a/tools/node_modules/eslint/lib/util/apply-disable-directives.js b/tools/node_modules/eslint/lib/linter/apply-disable-directives.js similarity index 100% rename from tools/node_modules/eslint/lib/util/apply-disable-directives.js rename to tools/node_modules/eslint/lib/linter/apply-disable-directives.js diff --git a/tools/node_modules/eslint/lib/code-path-analysis/code-path-analyzer.js b/tools/node_modules/eslint/lib/linter/code-path-analysis/code-path-analyzer.js similarity index 96% rename from tools/node_modules/eslint/lib/code-path-analysis/code-path-analyzer.js rename to tools/node_modules/eslint/lib/linter/code-path-analysis/code-path-analyzer.js index b81e212e7f47dd..c1f4a600451846 100644 --- a/tools/node_modules/eslint/lib/code-path-analysis/code-path-analyzer.js +++ b/tools/node_modules/eslint/lib/linter/code-path-analysis/code-path-analyzer.js @@ -10,11 +10,11 @@ //------------------------------------------------------------------------------ const assert = require("assert"), + { breakableTypePattern } = require("../../shared/ast-utils"), CodePath = require("./code-path"), CodePathSegment = require("./code-path-segment"), IdGenerator = require("./id-generator"), - debug = require("./debug-helpers"), - astUtils = require("../util/ast-utils"); + debug = require("./debug-helpers"); //------------------------------------------------------------------------------ // Helpers @@ -41,6 +41,19 @@ function isHandledLogicalOperator(operator) { return operator === "&&" || operator === "||"; } +/** + * 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`. + */ +function getLabel(node) { + if (node.parent.type === "LabeledStatement") { + return node.parent.label.name; + } + return null; +} + /** * Checks whether or not a given logical expression node goes different path * between the `true` case and the `false` case. @@ -391,7 +404,7 @@ function processCodePathToEnter(analyzer, node) { case "SwitchStatement": state.pushSwitchContext( node.cases.some(isCaseNode), - astUtils.getLabel(node) + getLabel(node) ); break; @@ -416,11 +429,11 @@ function processCodePathToEnter(analyzer, node) { case "ForStatement": case "ForInStatement": case "ForOfStatement": - state.pushLoopContext(node.type, astUtils.getLabel(node)); + state.pushLoopContext(node.type, getLabel(node)); break; case "LabeledStatement": - if (!astUtils.isBreakableStatement(node.body)) { + if (!breakableTypePattern.test(node.body.type)) { state.pushBreakContext(false, node.label.name); } break; @@ -531,7 +544,7 @@ function processCodePathToExit(analyzer, node) { break; case "LabeledStatement": - if (!astUtils.isBreakableStatement(node.body)) { + if (!breakableTypePattern.test(node.body.type)) { state.popBreakContext(); } break; diff --git a/tools/node_modules/eslint/lib/code-path-analysis/code-path-segment.js b/tools/node_modules/eslint/lib/linter/code-path-analysis/code-path-segment.js similarity index 100% rename from tools/node_modules/eslint/lib/code-path-analysis/code-path-segment.js rename to tools/node_modules/eslint/lib/linter/code-path-analysis/code-path-segment.js diff --git a/tools/node_modules/eslint/lib/code-path-analysis/code-path-state.js b/tools/node_modules/eslint/lib/linter/code-path-analysis/code-path-state.js similarity index 100% rename from tools/node_modules/eslint/lib/code-path-analysis/code-path-state.js rename to tools/node_modules/eslint/lib/linter/code-path-analysis/code-path-state.js diff --git a/tools/node_modules/eslint/lib/code-path-analysis/code-path.js b/tools/node_modules/eslint/lib/linter/code-path-analysis/code-path.js similarity index 100% rename from tools/node_modules/eslint/lib/code-path-analysis/code-path.js rename to tools/node_modules/eslint/lib/linter/code-path-analysis/code-path.js diff --git a/tools/node_modules/eslint/lib/code-path-analysis/debug-helpers.js b/tools/node_modules/eslint/lib/linter/code-path-analysis/debug-helpers.js similarity index 100% rename from tools/node_modules/eslint/lib/code-path-analysis/debug-helpers.js rename to tools/node_modules/eslint/lib/linter/code-path-analysis/debug-helpers.js diff --git a/tools/node_modules/eslint/lib/code-path-analysis/fork-context.js b/tools/node_modules/eslint/lib/linter/code-path-analysis/fork-context.js similarity index 100% rename from tools/node_modules/eslint/lib/code-path-analysis/fork-context.js rename to tools/node_modules/eslint/lib/linter/code-path-analysis/fork-context.js diff --git a/tools/node_modules/eslint/lib/code-path-analysis/id-generator.js b/tools/node_modules/eslint/lib/linter/code-path-analysis/id-generator.js similarity index 100% rename from tools/node_modules/eslint/lib/code-path-analysis/id-generator.js rename to tools/node_modules/eslint/lib/linter/code-path-analysis/id-generator.js diff --git a/tools/node_modules/eslint/lib/util/config-comment-parser.js b/tools/node_modules/eslint/lib/linter/config-comment-parser.js similarity index 98% rename from tools/node_modules/eslint/lib/util/config-comment-parser.js rename to tools/node_modules/eslint/lib/linter/config-comment-parser.js index 7ac934757403bc..d0e24c5940e341 100644 --- a/tools/node_modules/eslint/lib/util/config-comment-parser.js +++ b/tools/node_modules/eslint/lib/linter/config-comment-parser.js @@ -11,7 +11,7 @@ //------------------------------------------------------------------------------ const levn = require("levn"), - ConfigOps = require("../config/config-ops"); + ConfigOps = require("../shared/config-ops"); const debug = require("debug")("eslint:config-comment-parser"); diff --git a/tools/node_modules/eslint/lib/linter/index.js b/tools/node_modules/eslint/lib/linter/index.js new file mode 100644 index 00000000000000..25fd769bde997f --- /dev/null +++ b/tools/node_modules/eslint/lib/linter/index.js @@ -0,0 +1,13 @@ +"use strict"; + +const { Linter } = require("./linter"); +const interpolate = require("./interpolate"); +const SourceCodeFixer = require("./source-code-fixer"); + +module.exports = { + Linter, + + // For testers. + SourceCodeFixer, + interpolate +}; diff --git a/tools/node_modules/eslint/lib/util/interpolate.js b/tools/node_modules/eslint/lib/linter/interpolate.js similarity index 100% rename from tools/node_modules/eslint/lib/util/interpolate.js rename to tools/node_modules/eslint/lib/linter/interpolate.js diff --git a/tools/node_modules/eslint/lib/linter.js b/tools/node_modules/eslint/lib/linter/linter.js similarity index 55% rename from tools/node_modules/eslint/lib/linter.js rename to tools/node_modules/eslint/lib/linter/linter.js index be38b99087de74..c97822f269cdd7 100644 --- a/tools/node_modules/eslint/lib/linter.js +++ b/tools/node_modules/eslint/lib/linter/linter.js @@ -1,6 +1,7 @@ /** * @fileoverview Main Linter Class * @author Gyandeep Singh + * @author aladdin-add */ "use strict"; @@ -9,45 +10,49 @@ // Requirements //------------------------------------------------------------------------------ -const eslintScope = require("eslint-scope"), +const + path = require("path"), + eslintScope = require("eslint-scope"), evk = require("eslint-visitor-keys"), espree = require("espree"), lodash = require("lodash"), + BuiltInEnvironments = require("../../conf/environments"), + pkg = require("../../package.json"), + astUtils = require("../shared/ast-utils"), + ConfigOps = require("../shared/config-ops"), + validator = require("../shared/config-validator"), + Traverser = require("../shared/traverser"), + { SourceCode } = require("../source-code"), 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"), + applyDisableDirectives = require("./apply-disable-directives"), + ConfigCommentParser = require("./config-comment-parser"), + NodeEventGenerator = require("./node-event-generator"), + createReportTranslator = require("./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"); + createEmitter = require("./safe-emitter"), + SourceCodeFixer = require("./source-code-fixer"), + timing = require("./timing"), + ruleReplacements = require("../../conf/replacements.json"); const debug = require("debug")("eslint:linter"); const MAX_AUTOFIX_PASSES = 10; const DEFAULT_PARSER_NAME = "espree"; const commentParser = new ConfigCommentParser(); +const DEFAULT_ERROR_LOC = { start: { line: 1, column: 0 }, end: { line: 1, column: 1 } }; //------------------------------------------------------------------------------ // 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 {InstanceType} ConfigArray */ +/** @typedef {InstanceType} ExtractedConfig */ +/** @typedef {import("../shared/types").ConfigData} ConfigData */ +/** @typedef {import("../shared/types").Environment} Environment */ +/** @typedef {import("../shared/types").GlobalConf} GlobalConf */ +/** @typedef {import("../shared/types").LintMessage} LintMessage */ +/** @typedef {import("../shared/types").ParserOptions} ParserOptions */ +/** @typedef {import("../shared/types").Processor} Processor */ +/** @typedef {import("../shared/types").Rule} Rule */ /** * @typedef {Object} DisableDirective @@ -57,6 +62,47 @@ const commentParser = new ConfigCommentParser(); * @property {(string|null)} ruleId */ +/** + * The private data for `Linter` instance. + * @typedef {Object} LinterInternalSlots + * @property {ConfigArray|null} lastConfigArray The `ConfigArray` instance that the last `verify()` call used. + * @property {SourceCode|null} lastSourceCode The `SourceCode` instance that the last `verify()` call used. + * @property {Map} parserMap The loaded parsers. + * @property {Rules} ruleMap The loaded rules. + */ + +/** + * @typedef {Object} VerifyOptions + * @property {boolean} [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. + * @property {boolean} [disableFixes] if `true` then the linter doesn't make `fix` + * properties into the lint result. + * @property {string} [filename] the filename of the source code. + * @property {boolean} [reportUnusedDisableDirectives] Adds reported errors for + * unused `eslint-disable` directives. + */ + +/** + * @typedef {Object} ProcessorOptions + * @property {(filename:string, text:string) => boolean} [filterCodeBlock] the + * predicate function that selects adopt code blocks. + * @property {Processor["postprocess"]} [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. + * @property {Processor["preprocess"]} [preprocess] preprocessor for source text. + * If provided, this should accept a string of source text, and return an + * array of code blocks to lint. + */ + +/** + * @typedef {Object} FixOptions + * @property {boolean | ((message: LintMessage) => boolean)} [fix] Determines + * whether fixes should be applied. + */ + //------------------------------------------------------------------------------ // Helpers //------------------------------------------------------------------------------ @@ -70,34 +116,41 @@ const commentParser = new ConfigCommentParser(); * @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) })) - ); +function addDeclaredGlobals(globalScope, configGlobals, { exportedVariables, enabledGlobals }) { - 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"); - }); + // Define configured global variables. + for (const id of new Set([...Object.keys(configGlobals), ...Object.keys(enabledGlobals)])) { + + /* + * `ConfigOps.normalizeConfigGlobal` will throw an error if a configured global value is invalid. However, these errors would + * typically be caught when validating a config anyway (validity for inline global comments is checked separately). + */ + const configValue = configGlobals[id] === void 0 ? void 0 : ConfigOps.normalizeConfigGlobal(configGlobals[id]); + const commentValue = enabledGlobals[id] && enabledGlobals[id].value; + const value = commentValue || configValue; + const sourceComments = enabledGlobals[id] && enabledGlobals[id].comments; + + if (value === "off") { + continue; + } + + let variable = globalScope.set.get(id); + + if (!variable) { + variable = new eslintScope.Variable(id, globalScope); + + globalScope.variables.push(variable); + globalScope.set.set(id, variable); + } + + variable.eslintImplicitGlobalSetting = configValue; + variable.eslintExplicitGlobal = sourceComments !== void 0; + variable.eslintExplicitGlobalComments = sourceComments; + variable.writeable = (value === "writable"); + } // mark all exported variables as such - Object.keys(commentDirectives.exportedVariables).forEach(name => { + Object.keys(exportedVariables).forEach(name => { const variable = globalScope.set.get(name); if (variable) { @@ -130,19 +183,71 @@ function addDeclaredGlobals(globalScope, configGlobals, commentDirectives) { }); } +/** + * creates a missing-rule message. + * @param {string} ruleId the ruleId to create + * @returns {string} created error message + * @private + */ +function createMissingRuleMessage(ruleId) { + return Object.prototype.hasOwnProperty.call(ruleReplacements.rules, ruleId) + ? `Rule '${ruleId}' was removed and replaced by: ${ruleReplacements.rules[ruleId].join(", ")}` + : `Definition for rule '${ruleId}' was not found.`; +} + +/** + * creates a linting problem + * @param {Object} options to create linting error + * @param {string} options.ruleId the ruleId to report + * @param {Object} options.loc the loc to report + * @param {string} options.message the error message to report + * @returns {Problem} created problem, returns a missing-rule problem if only provided ruleId. + * @private + */ +function createLintingProblem(options) { + const { ruleId, loc = DEFAULT_ERROR_LOC, message = createMissingRuleMessage(options.ruleId) } = options; + + return { + ruleId, + message, + line: loc.start.line, + column: loc.start.column + 1, + endLine: loc.end.line, + endColumn: loc.end.column + 1, + severity: 2, + nodeType: null + }; +} + /** * 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 + * @param {Object} options to create disable directives + * @param {("disable"|"enable"|"disable-line"|"disable-next-line")} options.type The type of directive comment + * @param {{line: number, column: number}} options.loc The 0-based location of the comment token + * @param {string} options.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 + * @param {function(string): {create: Function}} options.ruleMapper A map from rule IDs to defined rules + * @returns {Object} Directives and problems from the comment */ -function createDisableDirectives(type, loc, value) { +function createDisableDirectives(options) { + const { type, loc, value, ruleMapper } = options; const ruleIds = Object.keys(commentParser.parseListConfig(value)); const directiveRules = ruleIds.length ? ruleIds : [null]; + const result = { + directives: [], // valid disable directives + directiveProblems: [] // problems in directives + }; - return directiveRules.map(ruleId => ({ type, line: loc.line, column: loc.column + 1, ruleId })); + for (const ruleId of directiveRules) { + + // push to directives, if the rule is defined(including null, e.g. /*eslint enable*/) + if (ruleId === null || ruleMapper(ruleId) !== null) { + result.directives.push({ type, line: loc.start.line, column: loc.start.column + 1, ruleId }); + } else { + result.directiveProblems.push(createLintingProblem({ ruleId, loc })); + } + } + return result; } /** @@ -152,7 +257,7 @@ function createDisableDirectives(type, loc, value) { * @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[]}} + * @returns {{configuredRules: Object, enabledGlobals: {value:string,comment:Token}[], 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) { @@ -171,23 +276,19 @@ function getDirectiveComments(filename, ast, ruleMapper) { } const directiveValue = trimmedCommentText.slice(match.index + match[1].length); + let directiveType = ""; if (/^eslint-disable-(next-)?line$/u.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)); + directiveType = match[1].slice("eslint-".length); } else { - problems.push({ + const message = `${match[1]} comment should not span multiple lines.`; + + problems.push(createLintingProblem({ 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 - }); + message, + loc: comment.loc + })); } } else if (comment.type === "Block") { switch (match[1]) { @@ -197,15 +298,38 @@ function getDirectiveComments(filename, ast, ruleMapper) { case "globals": case "global": - Object.assign(enabledGlobals, commentParser.parseStringConfig(directiveValue, comment)); + for (const [id, { value }] of Object.entries(commentParser.parseStringConfig(directiveValue, comment))) { + let normalizedValue; + + try { + normalizedValue = ConfigOps.normalizeConfigGlobal(value); + } catch (err) { + problems.push(createLintingProblem({ + ruleId: null, + loc: comment.loc, + message: err.message + })); + continue; + } + + if (enabledGlobals[id]) { + enabledGlobals[id].comments.push(comment); + enabledGlobals[id].value = normalizedValue; + } else { + enabledGlobals[id] = { + comments: [comment], + value: normalizedValue + }; + } + } break; case "eslint-disable": - disableDirectives.push(...createDisableDirectives("disable", comment.loc.start, directiveValue)); + directiveType = "disable"; break; case "eslint-enable": - disableDirectives.push(...createDisableDirectives("enable", comment.loc.start, directiveValue)); + directiveType = "enable"; break; case "eslint": { @@ -213,22 +337,27 @@ function getDirectiveComments(filename, ast, ruleMapper) { if (parseResult.success) { Object.keys(parseResult.config).forEach(name => { + const rule = ruleMapper(name); const ruleValue = parseResult.config[name]; + if (rule === null) { + problems.push(createLintingProblem({ ruleId: name, loc: comment.loc })); + return; + } + try { - validator.validateRuleOptions(ruleMapper(name), name, ruleValue); + validator.validateRuleOptions(rule, name, ruleValue); } catch (err) { - problems.push({ + problems.push(createLintingProblem({ 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 - }); + loc: comment.loc + })); + + // do not apply the config, if found invalid options. + return; } + configuredRules[name] = ruleValue; }); } else { @@ -241,6 +370,14 @@ function getDirectiveComments(filename, ast, ruleMapper) { // no default } } + + if (directiveType !== "") { + const options = { type: directiveType, loc: comment.loc, value: directiveValue, ruleMapper }; + const { directives, directiveProblems } = createDisableDirectives(options); + + disableDirectives.push(...directives); + problems.push(...directiveProblems); + } }); return { @@ -255,25 +392,15 @@ function getDirectiveComments(filename, ast, ruleMapper) { /** * 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; - } +function normalizeEcmaVersion(ecmaVersion) { /* * 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; + return ecmaVersion >= 2015 ? ecmaVersion - 2009 : ecmaVersion; } const eslintEnvPattern = /\/\*\s*eslint-env\s(.+?)\*\//gu; @@ -295,65 +422,78 @@ function findEslintEnv(text) { return retv; } +/** + * Convert "/path/to/" to "". + * `CLIEngine#executeOnText()` method gives "/path/to/" if the filename + * was omitted because `configArray.extractConfig()` requires an absolute path. + * But the linter should pass `` to `RuleContext#getFilename()` in that + * case. + * Also, code blocks can have their virtual filename. If the parent filename was + * ``, the virtual filename is `/0_foo.js` or something like (i.e., + * it's not an absolute path). + * @param {string} filename The filename to normalize. + * @returns {string} The normalized filename. + */ +function normalizeFilename(filename) { + const parts = filename.split(path.sep); + const index = parts.lastIndexOf(""); + + return index === -1 ? filename : parts.slice(index).join(path.sep); +} + /** * 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 + * @param {VerifyOptions} providedOptions Options + * @returns {Required} 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 + filename: normalizeFilename(providedOptions.filename || ""), + allowInlineConfig: providedOptions.allowInlineConfig !== false, + reportUnusedDisableDirectives: Boolean(providedOptions.reportUnusedDisableDirectives), + disableFixes: Boolean(providedOptions.disableFixes) }; } /** * 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 {ParserOptions} 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 + * @returns {ParserOptions} 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 || {}); - + .reduce((parserOptions, env) => lodash.merge(parserOptions, env.parserOptions), {}); + const mergedParserOptions = lodash.merge(parserOptionsFromEnv, providedOptions || {}); const isModule = mergedParserOptions.sourceType === "module"; if (isModule) { - // can't have global return inside of modules + /* + * can't have global return inside of modules + * TODO: espree validate parserOptions.globalReturn when sourceType is setting to module.(@aladdin-add) + */ 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; - } + /* + * TODO: @aladdin-add + * 1. for a 3rd-party parser, do not normalize parserOptions + * 2. for espree, no need to do this (espree will do it) + */ + mergedParserOptions.ecmaVersion = normalizeEcmaVersion(mergedParserOptions.ecmaVersion); 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 + * @param {Record} providedGlobals The 'globals' key in a config + * @param {Environment[]} enabledEnvironments The environments enabled in configuration and with inline comments + * @returns {Record} The resolved globals object */ function resolveGlobals(providedGlobals, enabledEnvironments) { return Object.assign( @@ -398,8 +538,8 @@ function getRuleOptions(ruleConfig) { /** * 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. + * @param {ParserOptions} parserOptions The parser options. + * @param {Record} visitorKeys The visitor keys. * @returns {ScopeManager} The analysis result. */ function analyzeScope(ast, parserOptions, visitorKeys) { @@ -422,18 +562,15 @@ function analyzeScope(ast, parserOptions, visitorKeys) { * 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 {Parser} parser The parser to parse. + * @param {ParserOptions} providedParserOptions Options to pass to the parser * @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}`); +function parse(text, parser, providedParserOptions, filePath) { + const textToParse = stripUnicodeBOM(text).replace(astUtils.shebangPattern, (match, captured) => `//${captured}`); const parserOptions = Object.assign({}, providedParserOptions, { loc: true, range: true, @@ -445,24 +582,6 @@ function parse(text, providedParserOptions, parserName, parserMap, filePath) { 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 @@ -643,9 +762,10 @@ const BASE_TRAVERSAL_CONTEXT = Object.freeze( * @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 + * @param {boolean} disableFixes If true, it doesn't make `fix` properties. * @returns {Problem[]} An array of reported problems */ -function runRules(sourceCode, configuredRules, ruleMapper, parserOptions, parserName, settings, filename) { +function runRules(sourceCode, configuredRules, ruleMapper, parserOptions, parserName, settings, filename, disableFixes) { const emitter = createEmitter(); const nodeQueue = []; let currentNode = sourceCode.ast; @@ -690,11 +810,18 @@ function runRules(sourceCode, configuredRules, ruleMapper, parserOptions, parser Object.keys(configuredRules).forEach(ruleId => { const severity = ConfigOps.getRuleSeverity(configuredRules[ruleId]); + // not load disabled rules if (severity === 0) { return; } const rule = ruleMapper(ruleId); + + if (rule === null) { + lintingProblems.push(createLintingProblem({ ruleId })); + return; + } + const messageIds = rule.meta && rule.meta.messages; let reportTranslator = null; const ruleContext = Object.freeze( @@ -716,7 +843,13 @@ function runRules(sourceCode, configuredRules, ruleMapper, parserOptions, parser * with Node 8.4.0. */ if (reportTranslator === null) { - reportTranslator = createReportTranslator({ ruleId, severity, sourceCode, messageIds }); + reportTranslator = createReportTranslator({ + ruleId, + severity, + sourceCode, + messageIds, + disableFixes + }); } const problem = reportTranslator(...args); @@ -762,9 +895,56 @@ function runRules(sourceCode, configuredRules, ruleMapper, parserOptions, parser return lintingProblems; } -const lastSourceCodes = new WeakMap(); -const loadedParserMaps = new WeakMap(); -const ruleMaps = new WeakMap(); +/** + * Ensure the source code to be a string. + * @param {string|SourceCode} textOrSourceCode The text or source code object. + * @returns {string} The source code text. + */ +function ensureText(textOrSourceCode) { + if (typeof textOrSourceCode === "object") { + const { hasBOM, text } = textOrSourceCode; + const bom = hasBOM ? "\uFEFF" : ""; + + return bom + text; + } + + return String(textOrSourceCode); +} + +/** + * Get an environment. + * @param {LinterInternalSlots} slots The internal slots of Linter. + * @param {string} envId The environment ID to get. + * @returns {Environment|null} The environment. + */ +function getEnv(slots, envId) { + return ( + (slots.lastConfigArray && slots.lastConfigArray.pluginEnvironments.get(envId)) || + BuiltInEnvironments.get(envId) || + null + ); +} + +/** + * Get a rule. + * @param {LinterInternalSlots} slots The internal slots of Linter. + * @param {string} ruleId The rule ID to get. + * @returns {Rule} The rule. + */ +function getRule(slots, ruleId) { + return ( + (slots.lastConfigArray && slots.lastConfigArray.pluginRules.get(ruleId)) || + + // This returns the stub for missing rules if the rule does not exist. + slots.ruleMap.get(ruleId) + ); +} + +/** + * The map to store private data. + * @type {WeakMap} + */ +const internalSlotsMap = new WeakMap(); //------------------------------------------------------------------------------ // Public Interface @@ -774,16 +954,17 @@ const ruleMaps = new WeakMap(); * Object that is responsible for verifying JavaScript text * @name eslint */ -module.exports = class Linter { +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(); + internalSlotsMap.set(this, { + lastConfigArray: null, + lastSourceCode: null, + parserMap: new Map([["espree", espree]]), + ruleMap: new Rules() + }); - this.defineParser("espree", espree); + this.version = pkg.version; } /** @@ -795,63 +976,67 @@ module.exports = class Linter { 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. + * @param {ConfigData} providedConfig An ESLintConfig instance to configure everything. + * @param {VerifyOptions} [providedOptions] The optional filename of the file being checked. + * @returns {LintMessage[]} The results as an array of messages or an empty array if no messages. */ - _verifyWithoutProcessors(textOrSourceCode, providedConfig, filenameOrOptions) { + _verifyWithoutProcessors(textOrSourceCode, providedConfig, providedOptions) { + const slots = internalSlotsMap.get(this); const config = providedConfig || {}; - const options = normalizeVerifyOptions(filenameOrOptions); + const options = normalizeVerifyOptions(providedOptions); let text; // evaluate arguments if (typeof textOrSourceCode === "string") { - lastSourceCodes.set(this, null); + slots.lastSourceCode = null; text = textOrSourceCode; } else { - lastSourceCodes.set(this, textOrSourceCode); + slots.lastSourceCode = textOrSourceCode; text = textOrSourceCode.text; } + // Resolve parser. + let parserName = DEFAULT_PARSER_NAME; + let parser = espree; + + if (typeof config.parser === "object" && config.parser !== null) { + parserName = config.parser.filePath; + parser = config.parser.definition; + } else if (typeof config.parser === "string") { + if (!slots.parserMap.has(config.parser)) { + return [{ + ruleId: null, + fatal: true, + severity: 2, + message: `Configured parser '${config.parser}' was not found.`, + line: 0, + column: 0 + }]; + } + parserName = config.parser; + parser = slots.parserMap.get(config.parser); + } + // 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)) + .map(envName => getEnv(slots, 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)) { + if (!slots.lastSourceCode) { const parseResult = parse( text, + parser, parserOptions, - parserName, - loadedParserMaps.get(this), options.filename ); @@ -859,29 +1044,27 @@ module.exports = class Linter { return [parseResult.error]; } - lastSourceCodes.set(this, parseResult.sourceCode); + slots.lastSourceCode = 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) - })); + if (!slots.lastSourceCode.scopeManager) { + slots.lastSourceCode = new SourceCode({ + text: slots.lastSourceCode.text, + ast: slots.lastSourceCode.ast, + parserServices: slots.lastSourceCode.parserServices, + visitorKeys: slots.lastSourceCode.visitorKeys, + scopeManager: analyzeScope(slots.lastSourceCode.ast, parserOptions) + }); } } - const sourceCode = lastSourceCodes.get(this); + const sourceCode = slots.lastSourceCode; const commentDirectives = options.allowInlineConfig - ? getDirectiveComments(options.filename, sourceCode.ast, ruleId => ruleMaps.get(this).get(ruleId)) + ? getDirectiveComments(options.filename, sourceCode.ast, ruleId => getRule(slots, ruleId)) : { configuredRules: {}, enabledGlobals: {}, exportedVariables: {}, problems: [], disableDirectives: [] }; // augment global scope with declared global variables @@ -899,11 +1082,12 @@ module.exports = class Linter { lintingProblems = runRules( sourceCode, configuredRules, - ruleId => ruleMaps.get(this).get(ruleId), + ruleId => getRule(slots, ruleId), parserOptions, parserName, settings, - options.filename + options.filename, + options.disableFixes ); } catch (err) { err.message += `\nOccurred while linting ${options.filename}`; @@ -933,28 +1117,122 @@ module.exports = class Linter { /** * 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. + * @param {ConfigData|ConfigArray} config An ESLintConfig instance to configure everything. + * @param {(string|(VerifyOptions&ProcessorOptions))} [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. + * an object, then it has "filename", "allowInlineConfig", and some properties. + * @returns {LintMessage[]} 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; + debug("Verify"); + const options = typeof filenameOrOptions === "string" + ? { filename: filenameOrOptions } + : filenameOrOptions || {}; + + // CLIEngine passes a `ConfigArray` object. + if (config && typeof config.extractConfig === "function") { + return this._verifyWithConfigArray(textOrSourceCode, config, options); + } - return postprocess( - preprocess(textOrSourceCode).map( - textBlock => this._verifyWithoutProcessors(textBlock, config, filenameOrOptions) - ) - ); + /* + * `Linter` doesn't support `overrides` property in configuration. + * So we cannot apply multiple processors. + */ + if (options.preprocess || options.postprocess) { + return this._verifyWithProcessor(textOrSourceCode, config, options); + } + return this._verifyWithoutProcessors(textOrSourceCode, config, options); + } + + /** + * Verify a given code with `ConfigArray`. + * @param {string|SourceCode} textOrSourceCode The source code. + * @param {ConfigArray} configArray The config array. + * @param {VerifyOptions&ProcessorOptions} options The options. + * @returns {LintMessage[]} The found problems. + */ + _verifyWithConfigArray(textOrSourceCode, configArray, options) { + debug("With ConfigArray: %s", options.filename); + + // Store the config array in order to get plugin envs and rules later. + internalSlotsMap.get(this).lastConfigArray = configArray; + + // Extract the final config for this file. + const config = configArray.extractConfig(options.filename); + const processor = + config.processor && + configArray.pluginProcessors.get(config.processor); + + // Verify. + if (processor) { + debug("Apply the processor: %o", config.processor); + const { preprocess, postprocess, supportsAutofix } = processor; + const disableFixes = options.disableFixes || !supportsAutofix; + + return this._verifyWithProcessor( + textOrSourceCode, + config, + { ...options, disableFixes, postprocess, preprocess }, + configArray + ); + } + return this._verifyWithoutProcessors(textOrSourceCode, config, options); + } + + /** + * Verify with a processor. + * @param {string|SourceCode} textOrSourceCode The source code. + * @param {ConfigData|ExtractedConfig} config The config array. + * @param {VerifyOptions&ProcessorOptions} options The options. + * @param {ConfigArray} [configForRecursive] The `CofnigArray` object to apply multiple processors recursively. + * @returns {LintMessage[]} The found problems. + */ + _verifyWithProcessor(textOrSourceCode, config, options, configForRecursive) { + const filename = options.filename || ""; + const filenameToExpose = normalizeFilename(filename); + const text = ensureText(textOrSourceCode); + const preprocess = options.preprocess || (rawText => [rawText]); + const postprocess = options.postprocess || lodash.flatten; + const filterCodeBlock = + options.filterCodeBlock || + (blockFilename => blockFilename.endsWith(".js")); + const originalExtname = path.extname(filename); + const messageLists = preprocess(text, filenameToExpose).map((block, i) => { + debug("A code block was found: %o", block.filename || "(unnamed)"); + + // Keep the legacy behavior. + if (typeof block === "string") { + return this._verifyWithoutProcessors(block, config, options); + } + + const blockText = block.text; + const blockName = path.join(filename, `${i}_${block.filename}`); + + // Skip this block if filtered. + if (!filterCodeBlock(blockName, blockText)) { + debug("This code block was skipped."); + return []; + } + + // Resolve configuration again if the file extension was changed. + if (configForRecursive && path.extname(blockName) !== originalExtname) { + debug("Resolving configuration again because the file extension was changed."); + return this._verifyWithConfigArray( + blockText, + configForRecursive, + { ...options, filename: blockName } + ); + } + + // Does lint. + return this._verifyWithoutProcessors( + blockText, + config, + { ...options, filename: blockName } + ); + }); + + return postprocess(messageLists, filenameToExpose); } /** @@ -962,22 +1240,22 @@ module.exports = class Linter { * @returns {SourceCode} The SourceCode object. */ getSourceCode() { - return lastSourceCodes.get(this); + return internalSlotsMap.get(this).lastSourceCode; } /** * 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 + * @param {Function | Rule} ruleModule Function from context to object mapping AST node types to event handlers * @returns {void} */ defineRule(ruleId, ruleModule) { - ruleMaps.get(this).define(ruleId, ruleModule); + internalSlotsMap.get(this).ruleMap.define(ruleId, ruleModule); } /** * Defines many new linting rules. - * @param {Object} rulesToDefine map from unique rule identifier to rule + * @param {Record} rulesToDefine map from unique rule identifier to rule * @returns {void} */ defineRules(rulesToDefine) { @@ -988,38 +1266,37 @@ module.exports = class Linter { /** * Gets an object with all loaded rules. - * @returns {Map} All loaded rules + * @returns {Map} All loaded rules */ getRules() { - return ruleMaps.get(this).getAllLoadedRules(); + const { lastConfigArray, ruleMap } = internalSlotsMap.get(this); + + return new Map(function *() { + yield* ruleMap; + + if (lastConfigArray) { + yield* lastConfigArray.pluginRules; + } + }()); } /** * Define a new parser module - * @param {any} parserId Name of the parser - * @param {any} parserModule The parser object + * @param {string} parserId Name of the parser + * @param {Parser} parserModule The parser object * @returns {void} */ defineParser(parserId, parserModule) { - loadedParserMaps.get(this).set(parserId, parserModule); + internalSlotsMap.get(this).parserMap.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 + * @param {ConfigData|ConfigArray} config The ESLint config object to use. + * @param {VerifyOptions&ProcessorOptions&FixOptions} options The ESLint options object to use. + * @returns {{fixed:boolean,messages:LintMessage[],output:string}} The result of the fix operation as returned from the * SourceCodeFixer. */ verifyAndFix(text, config, options) { @@ -1082,4 +1359,17 @@ module.exports = class Linter { return fixedResult; } +} + +module.exports = { + Linter, + + /** + * Get the internal slots of a given Linter instance for tests. + * @param {Linter} instance The Linter instance to get. + * @returns {LinterInternalSlots} The internal slots. + */ + getLinterInternalSlots(instance) { + return internalSlotsMap.get(instance); + } }; diff --git a/tools/node_modules/eslint/lib/util/node-event-generator.js b/tools/node_modules/eslint/lib/linter/node-event-generator.js similarity index 99% rename from tools/node_modules/eslint/lib/util/node-event-generator.js rename to tools/node_modules/eslint/lib/linter/node-event-generator.js index 4193cc827581a9..cea89262e5cf4c 100644 --- a/tools/node_modules/eslint/lib/util/node-event-generator.js +++ b/tools/node_modules/eslint/lib/linter/node-event-generator.js @@ -206,7 +206,7 @@ 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`.) + * (See lib/linter/safe-emitter.js for more details on `SafeEmitter`.) * @returns {NodeEventGenerator} new instance */ constructor(emitter) { diff --git a/tools/node_modules/eslint/lib/util/report-translator.js b/tools/node_modules/eslint/lib/linter/report-translator.js similarity index 98% rename from tools/node_modules/eslint/lib/util/report-translator.js rename to tools/node_modules/eslint/lib/linter/report-translator.js index 3dfdca0e4944d3..8c9ed007a25f0d 100644 --- a/tools/node_modules/eslint/lib/util/report-translator.js +++ b/tools/node_modules/eslint/lib/linter/report-translator.js @@ -227,7 +227,7 @@ function createProblem(options) { /** * 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 {{ruleId: string, severity: number, sourceCode: SourceCode, messageIds: Object, disableFixes: boolean}} 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 */ @@ -275,7 +275,7 @@ module.exports = function createReportTranslator(metadata) { message: interpolate(computedMessage, descriptor.data), messageId: descriptor.messageId, loc: normalizeReportLoc(descriptor), - fix: normalizeFixes(descriptor, metadata.sourceCode) + fix: metadata.disableFixes ? null : normalizeFixes(descriptor, metadata.sourceCode) }); }; }; diff --git a/tools/node_modules/eslint/lib/util/rule-fixer.js b/tools/node_modules/eslint/lib/linter/rule-fixer.js similarity index 100% rename from tools/node_modules/eslint/lib/util/rule-fixer.js rename to tools/node_modules/eslint/lib/linter/rule-fixer.js diff --git a/tools/node_modules/eslint/lib/linter/rules.js b/tools/node_modules/eslint/lib/linter/rules.js new file mode 100644 index 00000000000000..a153266efb3f4d --- /dev/null +++ b/tools/node_modules/eslint/lib/linter/rules.js @@ -0,0 +1,77 @@ +/** + * @fileoverview Defines a storage for rules. + * @author Nicholas C. Zakas + * @author aladdin-add + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const builtInRules = require("../rules"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * 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); + } + + /** + * 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 (typeof this._rules[ruleId] === "string") { + this.define(ruleId, require(this._rules[ruleId])); + } + if (this._rules[ruleId]) { + return this._rules[ruleId]; + } + if (builtInRules.has(ruleId)) { + return builtInRules.get(ruleId); + } + + return null; + } + + *[Symbol.iterator]() { + yield* builtInRules; + + for (const ruleId of Object.keys(this._rules)) { + yield [ruleId, this.get(ruleId)]; + } + } +} + +module.exports = Rules; diff --git a/tools/node_modules/eslint/lib/util/safe-emitter.js b/tools/node_modules/eslint/lib/linter/safe-emitter.js similarity index 100% rename from tools/node_modules/eslint/lib/util/safe-emitter.js rename to tools/node_modules/eslint/lib/linter/safe-emitter.js diff --git a/tools/node_modules/eslint/lib/util/source-code-fixer.js b/tools/node_modules/eslint/lib/linter/source-code-fixer.js similarity index 100% rename from tools/node_modules/eslint/lib/util/source-code-fixer.js rename to tools/node_modules/eslint/lib/linter/source-code-fixer.js diff --git a/tools/node_modules/eslint/lib/util/timing.js b/tools/node_modules/eslint/lib/linter/timing.js similarity index 98% rename from tools/node_modules/eslint/lib/util/timing.js rename to tools/node_modules/eslint/lib/linter/timing.js index 102a5233dc2ec1..8396d9215b54dc 100644 --- a/tools/node_modules/eslint/lib/util/timing.js +++ b/tools/node_modules/eslint/lib/linter/timing.js @@ -48,7 +48,7 @@ const ALIGN = [alignLeft, alignRight, alignRight]; /** * display the data * @param {Object} data Data object to be displayed - * @returns {string} modified string + * @returns {void} prints modified string with console.log * @private */ function display(data) { diff --git a/tools/node_modules/eslint/lib/options.js b/tools/node_modules/eslint/lib/options.js index ee7357a296aa05..be4c09b8eabb5b 100644 --- a/tools/node_modules/eslint/lib/options.js +++ b/tools/node_modules/eslint/lib/options.js @@ -64,6 +64,11 @@ module.exports = optionator({ type: "Object", description: "Specify parser options" }, + { + option: "resolve-plugins-relative-to", + type: "path::String", + description: "A folder where plugins should be resolved from, CWD by default" + }, { heading: "Specifying rules and plugins" }, diff --git a/tools/node_modules/eslint/lib/rule-tester/index.js b/tools/node_modules/eslint/lib/rule-tester/index.js new file mode 100644 index 00000000000000..f52d14027c58ff --- /dev/null +++ b/tools/node_modules/eslint/lib/rule-tester/index.js @@ -0,0 +1,5 @@ +"use strict"; + +module.exports = { + RuleTester: require("./rule-tester") +}; diff --git a/tools/node_modules/eslint/lib/testers/rule-tester.js b/tools/node_modules/eslint/lib/rule-tester/rule-tester.js similarity index 93% rename from tools/node_modules/eslint/lib/testers/rule-tester.js rename to tools/node_modules/eslint/lib/rule-tester/rule-tester.js index f1d915531323a0..671de56064c7fc 100644 --- a/tools/node_modules/eslint/lib/testers/rule-tester.js +++ b/tools/node_modules/eslint/lib/rule-tester/rule-tester.js @@ -40,15 +40,15 @@ // Requirements //------------------------------------------------------------------------------ -const lodash = require("lodash"), +const assert = require("assert"), + path = require("path"), 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"); + lodash = require("lodash"), + { getRuleOptionsSchema, validate } = require("../shared/config-validator"), + { Linter, SourceCodeFixer, interpolate } = require("../linter"); + +const ajv = require("../shared/ajv")({ strictDefaults: true }); //------------------------------------------------------------------------------ // Private Members @@ -305,8 +305,6 @@ class RuleTester { 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 @@ -349,7 +347,7 @@ class RuleTester { config.rules[ruleName] = 1; } - const schema = validator.getRuleOptionsSchema(rule); + const schema = getRuleOptionsSchema(rule); /* * Setup AST getters. @@ -365,6 +363,11 @@ class RuleTester { } })); + if (typeof config.parser === "string") { + assert(path.isAbsolute(config.parser), "Parsers provided as strings to RuleTester must be absolute paths"); + linter.defineParser(config.parser, require(config.parser)); + } + if (schema) { ajv.validateSchema(schema); @@ -377,9 +380,21 @@ class RuleTester { throw new Error([`Schema for rule ${ruleName} is invalid:`, errors]); } + + /* + * `ajv.validateSchema` checks for errors in the structure of the schema (by comparing the schema against a "meta-schema"), + * and it reports those errors individually. However, there are other types of schema errors that only occur when compiling + * the schema (e.g. using invalid defaults in a schema), and only one of these errors can be reported at a time. As a result, + * the schema is compiled here separately from checking for `validateSchema` errors. + */ + try { + ajv.compile(schema); + } catch (err) { + throw new Error(`Schema for rule ${ruleName} is invalid: ${err.message}`); + } } - validator.validate(config, ruleMap.get.bind(ruleMap), new Environments(), "rule-tester"); + validate(config, "rule-tester", id => (id === ruleName ? rule : null)); return { messages: linter.verify(code, config, filename, true), 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/array-bracket-newline.js b/tools/node_modules/eslint/lib/rules/array-bracket-newline.js index a458e69f761687..f6be2e8dd02c82 100644 --- a/tools/node_modules/eslint/lib/rules/array-bracket-newline.js +++ b/tools/node_modules/eslint/lib/rules/array-bracket-newline.js @@ -5,7 +5,7 @@ "use strict"; -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/array-bracket-spacing.js b/tools/node_modules/eslint/lib/rules/array-bracket-spacing.js index 4bead37a12f51e..0a51d350cd79ea 100644 --- a/tools/node_modules/eslint/lib/rules/array-bracket-spacing.js +++ b/tools/node_modules/eslint/lib/rules/array-bracket-spacing.js @@ -4,7 +4,7 @@ */ "use strict"; -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/array-callback-return.js b/tools/node_modules/eslint/lib/rules/array-callback-return.js index 1c2f05629048b5..bd1f3a37aad29d 100644 --- a/tools/node_modules/eslint/lib/rules/array-callback-return.js +++ b/tools/node_modules/eslint/lib/rules/array-callback-return.js @@ -11,7 +11,7 @@ const lodash = require("lodash"); -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Helpers diff --git a/tools/node_modules/eslint/lib/rules/array-element-newline.js b/tools/node_modules/eslint/lib/rules/array-element-newline.js index dadb26fdd226de..c3d026ad6965b6 100644 --- a/tools/node_modules/eslint/lib/rules/array-element-newline.js +++ b/tools/node_modules/eslint/lib/rules/array-element-newline.js @@ -5,7 +5,7 @@ "use strict"; -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/arrow-body-style.js b/tools/node_modules/eslint/lib/rules/arrow-body-style.js index b1fed8c15d5b59..6d84c7adfb1187 100644 --- a/tools/node_modules/eslint/lib/rules/arrow-body-style.js +++ b/tools/node_modules/eslint/lib/rules/arrow-body-style.js @@ -8,7 +8,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/arrow-parens.js b/tools/node_modules/eslint/lib/rules/arrow-parens.js index 217a9b60e13cbb..387bcfec0c09cf 100644 --- a/tools/node_modules/eslint/lib/rules/arrow-parens.js +++ b/tools/node_modules/eslint/lib/rules/arrow-parens.js @@ -8,7 +8,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/arrow-spacing.js b/tools/node_modules/eslint/lib/rules/arrow-spacing.js index 95acb78772584b..e5110c6c87d43f 100644 --- a/tools/node_modules/eslint/lib/rules/arrow-spacing.js +++ b/tools/node_modules/eslint/lib/rules/arrow-spacing.js @@ -8,7 +8,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/block-spacing.js b/tools/node_modules/eslint/lib/rules/block-spacing.js index 864bfc0c5c09de..e843148e5d151a 100644 --- a/tools/node_modules/eslint/lib/rules/block-spacing.js +++ b/tools/node_modules/eslint/lib/rules/block-spacing.js @@ -5,7 +5,7 @@ "use strict"; -const util = require("../util/ast-utils"); +const util = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/brace-style.js b/tools/node_modules/eslint/lib/rules/brace-style.js index 17a5c7fdf9a37f..07223d10d4a3b4 100644 --- a/tools/node_modules/eslint/lib/rules/brace-style.js +++ b/tools/node_modules/eslint/lib/rules/brace-style.js @@ -5,7 +5,7 @@ "use strict"; -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/camelcase.js b/tools/node_modules/eslint/lib/rules/camelcase.js index 4647cc17e59bb5..cdc16fab9f9460 100644 --- a/tools/node_modules/eslint/lib/rules/camelcase.js +++ b/tools/node_modules/eslint/lib/rules/camelcase.js @@ -90,7 +90,7 @@ module.exports = { */ function isAllowed(name) { return allow.findIndex( - entry => name === entry || name.match(new RegExp(entry)) // eslint-disable-line require-unicode-regexp + entry => name === entry || name.match(new RegExp(entry, "u")) ) !== -1; } diff --git a/tools/node_modules/eslint/lib/rules/capitalized-comments.js b/tools/node_modules/eslint/lib/rules/capitalized-comments.js index 137be9e9337a88..47477743598ac8 100644 --- a/tools/node_modules/eslint/lib/rules/capitalized-comments.js +++ b/tools/node_modules/eslint/lib/rules/capitalized-comments.js @@ -8,8 +8,8 @@ // Requirements //------------------------------------------------------------------------------ -const LETTER_PATTERN = require("../util/patterns/letters"); -const astUtils = require("../util/ast-utils"); +const LETTER_PATTERN = require("./utils/patterns/letters"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Helpers @@ -91,7 +91,7 @@ function createRegExpForIgnorePatterns(normalizedOptions) { const ignorePatternStr = normalizedOptions[key].ignorePattern; if (ignorePatternStr) { - const regExp = RegExp(`^\\s*(?:${ignorePatternStr})`); // eslint-disable-line require-unicode-regexp + const regExp = RegExp(`^\\s*(?:${ignorePatternStr})`, "u"); normalizedOptions[key].ignorePatternRegExp = regExp; } diff --git a/tools/node_modules/eslint/lib/rules/comma-dangle.js b/tools/node_modules/eslint/lib/rules/comma-dangle.js index 96799b30796349..9cd6660d5d1e7f 100644 --- a/tools/node_modules/eslint/lib/rules/comma-dangle.js +++ b/tools/node_modules/eslint/lib/rules/comma-dangle.js @@ -10,7 +10,7 @@ //------------------------------------------------------------------------------ const lodash = require("lodash"); -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Helpers @@ -21,7 +21,7 @@ const DEFAULT_OPTIONS = Object.freeze({ objects: "never", imports: "never", exports: "never", - functions: "ignore" + functions: "never" }); /** diff --git a/tools/node_modules/eslint/lib/rules/comma-spacing.js b/tools/node_modules/eslint/lib/rules/comma-spacing.js index a9f89676a4a3cd..79a556a8857d1f 100644 --- a/tools/node_modules/eslint/lib/rules/comma-spacing.js +++ b/tools/node_modules/eslint/lib/rules/comma-spacing.js @@ -4,7 +4,7 @@ */ "use strict"; -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/comma-style.js b/tools/node_modules/eslint/lib/rules/comma-style.js index 78438a858dbb12..bc22f05dd3892c 100644 --- a/tools/node_modules/eslint/lib/rules/comma-style.js +++ b/tools/node_modules/eslint/lib/rules/comma-style.js @@ -5,7 +5,7 @@ "use strict"; -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/complexity.js b/tools/node_modules/eslint/lib/rules/complexity.js index 56e17ddf2fbbb3..91180e989540ce 100644 --- a/tools/node_modules/eslint/lib/rules/complexity.js +++ b/tools/node_modules/eslint/lib/rules/complexity.js @@ -12,7 +12,7 @@ const lodash = require("lodash"); -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition @@ -55,7 +55,7 @@ module.exports = { ], messages: { - complex: "{{name}} has a complexity of {{complexity}}." + complex: "{{name}} has a complexity of {{complexity}}. Maximum allowed is {{max}}." } }, @@ -102,7 +102,7 @@ module.exports = { context.report({ node, messageId: "complex", - data: { name, complexity } + data: { name, complexity, max: THRESHOLD } }); } } diff --git a/tools/node_modules/eslint/lib/rules/computed-property-spacing.js b/tools/node_modules/eslint/lib/rules/computed-property-spacing.js index 188d863d0d0f83..91b7d28963f2e5 100644 --- a/tools/node_modules/eslint/lib/rules/computed-property-spacing.js +++ b/tools/node_modules/eslint/lib/rules/computed-property-spacing.js @@ -4,7 +4,7 @@ */ "use strict"; -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/consistent-return.js b/tools/node_modules/eslint/lib/rules/consistent-return.js index 68f9f9d8fbcad4..16f0070bc7c3be 100644 --- a/tools/node_modules/eslint/lib/rules/consistent-return.js +++ b/tools/node_modules/eslint/lib/rules/consistent-return.js @@ -10,7 +10,7 @@ const lodash = require("lodash"); -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Helpers diff --git a/tools/node_modules/eslint/lib/rules/curly.js b/tools/node_modules/eslint/lib/rules/curly.js index 6803eb6cd3b66b..8eaaddc25c6ff7 100644 --- a/tools/node_modules/eslint/lib/rules/curly.js +++ b/tools/node_modules/eslint/lib/rules/curly.js @@ -8,7 +8,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition @@ -103,6 +103,20 @@ module.exports = { return first.loc.start.line === last.loc.end.line; } + /** + * Determines if the given node is a lexical declaration (let, const, function, or class) + * @param {ASTNode} node The node to check + * @returns {boolean} True if the node is a lexical declaration + * @private + */ + function isLexicalDeclaration(node) { + if (node.type === "VariableDeclaration") { + return node.kind === "const" || node.kind === "let"; + } + + return node.type === "FunctionDeclaration" || node.type === "ClassDeclaration"; + } + /** * Checks if the given token is an `else` token or not. * @@ -238,8 +252,13 @@ module.exports = { } else if (multiOrNest) { if (hasBlock && body.body.length === 1 && isOneLiner(body.body[0])) { const leadingComments = sourceCode.getCommentsBefore(body.body[0]); + const isLexDef = isLexicalDeclaration(body.body[0]); - expected = leadingComments.length > 0; + if (isLexDef) { + expected = true; + } else { + expected = leadingComments.length > 0; + } } else if (!isOneLiner(body)) { expected = true; } diff --git a/tools/node_modules/eslint/lib/rules/default-case.js b/tools/node_modules/eslint/lib/rules/default-case.js index c8d0af3926fa15..821e0d72bd1cba 100644 --- a/tools/node_modules/eslint/lib/rules/default-case.js +++ b/tools/node_modules/eslint/lib/rules/default-case.js @@ -39,7 +39,7 @@ module.exports = { create(context) { const options = context.options[0] || {}; const commentPattern = options.commentPattern - ? new RegExp(options.commentPattern) // eslint-disable-line require-unicode-regexp + ? new RegExp(options.commentPattern, "u") : DEFAULT_COMMENT_PATTERN; const sourceCode = context.getSourceCode(); diff --git a/tools/node_modules/eslint/lib/rules/dot-location.js b/tools/node_modules/eslint/lib/rules/dot-location.js index 0eefec2eaffee0..b9857ae2394ed8 100644 --- a/tools/node_modules/eslint/lib/rules/dot-location.js +++ b/tools/node_modules/eslint/lib/rules/dot-location.js @@ -5,7 +5,7 @@ "use strict"; -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/dot-notation.js b/tools/node_modules/eslint/lib/rules/dot-notation.js index e25ab12b771cc5..61184ddcd1a14c 100644 --- a/tools/node_modules/eslint/lib/rules/dot-notation.js +++ b/tools/node_modules/eslint/lib/rules/dot-notation.js @@ -8,14 +8,14 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ const validIdentifier = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/u; -const keywords = require("../util/keywords"); +const keywords = require("./utils/keywords"); module.exports = { meta: { @@ -61,7 +61,7 @@ module.exports = { let allowPattern; if (options.allowPattern) { - allowPattern = new RegExp(options.allowPattern); // eslint-disable-line require-unicode-regexp + allowPattern = new RegExp(options.allowPattern, "u"); } /** diff --git a/tools/node_modules/eslint/lib/rules/eqeqeq.js b/tools/node_modules/eslint/lib/rules/eqeqeq.js index 3e8a392cf6983e..58ff9030dbbd3c 100644 --- a/tools/node_modules/eslint/lib/rules/eqeqeq.js +++ b/tools/node_modules/eslint/lib/rules/eqeqeq.js @@ -9,7 +9,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/func-call-spacing.js b/tools/node_modules/eslint/lib/rules/func-call-spacing.js index 22375685134803..f9c8e780577a6b 100644 --- a/tools/node_modules/eslint/lib/rules/func-call-spacing.js +++ b/tools/node_modules/eslint/lib/rules/func-call-spacing.js @@ -9,7 +9,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/func-name-matching.js b/tools/node_modules/eslint/lib/rules/func-name-matching.js index 5560c692083843..3c4ee510dbca71 100644 --- a/tools/node_modules/eslint/lib/rules/func-name-matching.js +++ b/tools/node_modules/eslint/lib/rules/func-name-matching.js @@ -9,7 +9,7 @@ // Requirements //-------------------------------------------------------------------------- -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); const esutils = require("esutils"); //-------------------------------------------------------------------------- diff --git a/tools/node_modules/eslint/lib/rules/func-names.js b/tools/node_modules/eslint/lib/rules/func-names.js index 4ccbae0f0cb849..01beb9e2ed3f42 100644 --- a/tools/node_modules/eslint/lib/rules/func-names.js +++ b/tools/node_modules/eslint/lib/rules/func-names.js @@ -9,7 +9,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); /** * Checks whether or not a given variable is a function name. diff --git a/tools/node_modules/eslint/lib/rules/function-paren-newline.js b/tools/node_modules/eslint/lib/rules/function-paren-newline.js index 37256484f4a16e..0a0b57a372a354 100644 --- a/tools/node_modules/eslint/lib/rules/function-paren-newline.js +++ b/tools/node_modules/eslint/lib/rules/function-paren-newline.js @@ -8,7 +8,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition @@ -31,7 +31,7 @@ module.exports = { { oneOf: [ { - enum: ["always", "never", "consistent", "multiline"] + enum: ["always", "never", "consistent", "multiline", "multiline-arguments"] }, { type: "object", @@ -50,6 +50,7 @@ module.exports = { messages: { expectedBefore: "Expected newline before ')'.", expectedAfter: "Expected newline after '('.", + expectedBetween: "Expected newline between arguments/params.", unexpectedBefore: "Unexpected newline before '('.", unexpectedAfter: "Unexpected newline after ')'." } @@ -59,6 +60,7 @@ module.exports = { const sourceCode = context.getSourceCode(); const rawOption = context.options[0] || "multiline"; const multilineOption = rawOption === "multiline"; + const multilineArgumentsOption = rawOption === "multiline-arguments"; const consistentOption = rawOption === "consistent"; let minItems; @@ -83,7 +85,10 @@ module.exports = { * @returns {boolean} `true` if there should be newlines inside the function parens */ function shouldHaveNewlines(elements, hasLeftNewline) { - if (multilineOption) { + if (multilineArgumentsOption && elements.length === 1) { + return hasLeftNewline; + } + if (multilineOption || multilineArgumentsOption) { return elements.some((element, index) => index !== elements.length - 1 && element.loc.end.line !== elements[index + 1].loc.start.line); } if (consistentOption) { @@ -93,7 +98,7 @@ module.exports = { } /** - * Validates a list of arguments or parameters + * Validates parens * @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} @@ -148,6 +153,33 @@ module.exports = { } } + /** + * 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 validateArguments(parens, elements) { + const leftParen = parens.leftParen; + const tokenAfterLeftParen = sourceCode.getTokenAfter(leftParen); + const hasLeftNewline = !astUtils.isTokenOnSameLine(leftParen, tokenAfterLeftParen); + const needsNewlines = shouldHaveNewlines(elements, hasLeftNewline); + + for (let i = 0; i <= elements.length - 2; i++) { + const currentElement = elements[i]; + const nextElement = elements[i + 1]; + const hasNewLine = currentElement.loc.end.line !== nextElement.loc.start.line; + + if (!hasNewLine && needsNewlines) { + context.report({ + node: currentElement, + messageId: "expectedBetween", + fix: fixer => fixer.insertTextBefore(nextElement, "\n") + }); + } + } + } + /** * Gets the left paren and right paren tokens of a node. * @param {ASTNode} node The node with parens @@ -215,6 +247,10 @@ module.exports = { if (parens) { validateParens(parens, astUtils.isFunction(node) ? node.params : node.arguments); + + if (multilineArgumentsOption) { + validateArguments(parens, astUtils.isFunction(node) ? node.params : node.arguments); + } } } diff --git a/tools/node_modules/eslint/lib/rules/getter-return.js b/tools/node_modules/eslint/lib/rules/getter-return.js index c6035eed0428b7..6549555646e355 100644 --- a/tools/node_modules/eslint/lib/rules/getter-return.js +++ b/tools/node_modules/eslint/lib/rules/getter-return.js @@ -9,7 +9,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Helpers diff --git a/tools/node_modules/eslint/lib/rules/handle-callback-err.js b/tools/node_modules/eslint/lib/rules/handle-callback-err.js index 4d08e4fec1bf19..640946699e7bea 100644 --- a/tools/node_modules/eslint/lib/rules/handle-callback-err.js +++ b/tools/node_modules/eslint/lib/rules/handle-callback-err.js @@ -52,7 +52,7 @@ module.exports = { */ function matchesConfiguredErrorName(name) { if (isPattern(errorArgument)) { - const regexp = new RegExp(errorArgument); // eslint-disable-line require-unicode-regexp + const regexp = new RegExp(errorArgument, "u"); return regexp.test(name); } diff --git a/tools/node_modules/eslint/lib/rules/id-match.js b/tools/node_modules/eslint/lib/rules/id-match.js index 48c1087674d2f2..b97a497fd4f884 100644 --- a/tools/node_modules/eslint/lib/rules/id-match.js +++ b/tools/node_modules/eslint/lib/rules/id-match.js @@ -53,7 +53,7 @@ module.exports = { // Options //-------------------------------------------------------------------------- const pattern = context.options[0] || "^.+$", - regexp = new RegExp(pattern); // eslint-disable-line require-unicode-regexp + regexp = new RegExp(pattern, "u"); const options = context.options[1] || {}, properties = !!options.properties, diff --git a/tools/node_modules/eslint/lib/rules/implicit-arrow-linebreak.js b/tools/node_modules/eslint/lib/rules/implicit-arrow-linebreak.js index 6fc1268e7534ee..409145e7dc1329 100644 --- a/tools/node_modules/eslint/lib/rules/implicit-arrow-linebreak.js +++ b/tools/node_modules/eslint/lib/rules/implicit-arrow-linebreak.js @@ -4,7 +4,7 @@ */ "use strict"; -const { isCommentToken, isNotOpeningParenToken } = require("../util/ast-utils"); +const { isCommentToken, isNotOpeningParenToken } = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/indent-legacy.js b/tools/node_modules/eslint/lib/rules/indent-legacy.js index 93e963a1c043f8..fb84b732ea307e 100644 --- a/tools/node_modules/eslint/lib/rules/indent-legacy.js +++ b/tools/node_modules/eslint/lib/rules/indent-legacy.js @@ -12,7 +12,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/indent.js b/tools/node_modules/eslint/lib/rules/indent.js index cd018d91d66b59..345c69e81c1e3b 100644 --- a/tools/node_modules/eslint/lib/rules/indent.js +++ b/tools/node_modules/eslint/lib/rules/indent.js @@ -13,7 +13,7 @@ //------------------------------------------------------------------------------ const lodash = require("lodash"); -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); const createTree = require("functional-red-black-tree"); //------------------------------------------------------------------------------ diff --git a/tools/node_modules/eslint/lib/rules/index.js b/tools/node_modules/eslint/lib/rules/index.js new file mode 100644 index 00000000000000..45045904bb4787 --- /dev/null +++ b/tools/node_modules/eslint/lib/rules/index.js @@ -0,0 +1,281 @@ +/** + * @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"] */ + +const { LazyLoadingRuleMap } = require("./utils/lazy-loading-rule-map"); + +/** @type {Map} */ +module.exports = new LazyLoadingRuleMap(Object.entries({ + "accessor-pairs": () => require("./accessor-pairs"), + "array-bracket-newline": () => require("./array-bracket-newline"), + "array-bracket-spacing": () => require("./array-bracket-spacing"), + "array-callback-return": () => require("./array-callback-return"), + "array-element-newline": () => require("./array-element-newline"), + "arrow-body-style": () => require("./arrow-body-style"), + "arrow-parens": () => require("./arrow-parens"), + "arrow-spacing": () => require("./arrow-spacing"), + "block-scoped-var": () => require("./block-scoped-var"), + "block-spacing": () => require("./block-spacing"), + "brace-style": () => require("./brace-style"), + "callback-return": () => require("./callback-return"), + camelcase: () => require("./camelcase"), + "capitalized-comments": () => require("./capitalized-comments"), + "class-methods-use-this": () => require("./class-methods-use-this"), + "comma-dangle": () => require("./comma-dangle"), + "comma-spacing": () => require("./comma-spacing"), + "comma-style": () => require("./comma-style"), + complexity: () => require("./complexity"), + "computed-property-spacing": () => require("./computed-property-spacing"), + "consistent-return": () => require("./consistent-return"), + "consistent-this": () => require("./consistent-this"), + "constructor-super": () => require("./constructor-super"), + curly: () => require("./curly"), + "default-case": () => require("./default-case"), + "dot-location": () => require("./dot-location"), + "dot-notation": () => require("./dot-notation"), + "eol-last": () => require("./eol-last"), + eqeqeq: () => require("./eqeqeq"), + "for-direction": () => require("./for-direction"), + "func-call-spacing": () => require("./func-call-spacing"), + "func-name-matching": () => require("./func-name-matching"), + "func-names": () => require("./func-names"), + "func-style": () => require("./func-style"), + "function-paren-newline": () => require("./function-paren-newline"), + "generator-star-spacing": () => require("./generator-star-spacing"), + "getter-return": () => require("./getter-return"), + "global-require": () => require("./global-require"), + "guard-for-in": () => require("./guard-for-in"), + "handle-callback-err": () => require("./handle-callback-err"), + "id-blacklist": () => require("./id-blacklist"), + "id-length": () => require("./id-length"), + "id-match": () => require("./id-match"), + "implicit-arrow-linebreak": () => require("./implicit-arrow-linebreak"), + indent: () => require("./indent"), + "indent-legacy": () => require("./indent-legacy"), + "init-declarations": () => require("./init-declarations"), + "jsx-quotes": () => require("./jsx-quotes"), + "key-spacing": () => require("./key-spacing"), + "keyword-spacing": () => require("./keyword-spacing"), + "line-comment-position": () => require("./line-comment-position"), + "linebreak-style": () => require("./linebreak-style"), + "lines-around-comment": () => require("./lines-around-comment"), + "lines-around-directive": () => require("./lines-around-directive"), + "lines-between-class-members": () => require("./lines-between-class-members"), + "max-classes-per-file": () => require("./max-classes-per-file"), + "max-depth": () => require("./max-depth"), + "max-len": () => require("./max-len"), + "max-lines": () => require("./max-lines"), + "max-lines-per-function": () => require("./max-lines-per-function"), + "max-nested-callbacks": () => require("./max-nested-callbacks"), + "max-params": () => require("./max-params"), + "max-statements": () => require("./max-statements"), + "max-statements-per-line": () => require("./max-statements-per-line"), + "multiline-comment-style": () => require("./multiline-comment-style"), + "multiline-ternary": () => require("./multiline-ternary"), + "new-cap": () => require("./new-cap"), + "new-parens": () => require("./new-parens"), + "newline-after-var": () => require("./newline-after-var"), + "newline-before-return": () => require("./newline-before-return"), + "newline-per-chained-call": () => require("./newline-per-chained-call"), + "no-alert": () => require("./no-alert"), + "no-array-constructor": () => require("./no-array-constructor"), + "no-async-promise-executor": () => require("./no-async-promise-executor"), + "no-await-in-loop": () => require("./no-await-in-loop"), + "no-bitwise": () => require("./no-bitwise"), + "no-buffer-constructor": () => require("./no-buffer-constructor"), + "no-caller": () => require("./no-caller"), + "no-case-declarations": () => require("./no-case-declarations"), + "no-catch-shadow": () => require("./no-catch-shadow"), + "no-class-assign": () => require("./no-class-assign"), + "no-compare-neg-zero": () => require("./no-compare-neg-zero"), + "no-cond-assign": () => require("./no-cond-assign"), + "no-confusing-arrow": () => require("./no-confusing-arrow"), + "no-console": () => require("./no-console"), + "no-const-assign": () => require("./no-const-assign"), + "no-constant-condition": () => require("./no-constant-condition"), + "no-continue": () => require("./no-continue"), + "no-control-regex": () => require("./no-control-regex"), + "no-debugger": () => require("./no-debugger"), + "no-delete-var": () => require("./no-delete-var"), + "no-div-regex": () => require("./no-div-regex"), + "no-dupe-args": () => require("./no-dupe-args"), + "no-dupe-class-members": () => require("./no-dupe-class-members"), + "no-dupe-keys": () => require("./no-dupe-keys"), + "no-duplicate-case": () => require("./no-duplicate-case"), + "no-duplicate-imports": () => require("./no-duplicate-imports"), + "no-else-return": () => require("./no-else-return"), + "no-empty": () => require("./no-empty"), + "no-empty-character-class": () => require("./no-empty-character-class"), + "no-empty-function": () => require("./no-empty-function"), + "no-empty-pattern": () => require("./no-empty-pattern"), + "no-eq-null": () => require("./no-eq-null"), + "no-eval": () => require("./no-eval"), + "no-ex-assign": () => require("./no-ex-assign"), + "no-extend-native": () => require("./no-extend-native"), + "no-extra-bind": () => require("./no-extra-bind"), + "no-extra-boolean-cast": () => require("./no-extra-boolean-cast"), + "no-extra-label": () => require("./no-extra-label"), + "no-extra-parens": () => require("./no-extra-parens"), + "no-extra-semi": () => require("./no-extra-semi"), + "no-fallthrough": () => require("./no-fallthrough"), + "no-floating-decimal": () => require("./no-floating-decimal"), + "no-func-assign": () => require("./no-func-assign"), + "no-global-assign": () => require("./no-global-assign"), + "no-implicit-coercion": () => require("./no-implicit-coercion"), + "no-implicit-globals": () => require("./no-implicit-globals"), + "no-implied-eval": () => require("./no-implied-eval"), + "no-inline-comments": () => require("./no-inline-comments"), + "no-inner-declarations": () => require("./no-inner-declarations"), + "no-invalid-regexp": () => require("./no-invalid-regexp"), + "no-invalid-this": () => require("./no-invalid-this"), + "no-irregular-whitespace": () => require("./no-irregular-whitespace"), + "no-iterator": () => require("./no-iterator"), + "no-label-var": () => require("./no-label-var"), + "no-labels": () => require("./no-labels"), + "no-lone-blocks": () => require("./no-lone-blocks"), + "no-lonely-if": () => require("./no-lonely-if"), + "no-loop-func": () => require("./no-loop-func"), + "no-magic-numbers": () => require("./no-magic-numbers"), + "no-misleading-character-class": () => require("./no-misleading-character-class"), + "no-mixed-operators": () => require("./no-mixed-operators"), + "no-mixed-requires": () => require("./no-mixed-requires"), + "no-mixed-spaces-and-tabs": () => require("./no-mixed-spaces-and-tabs"), + "no-multi-assign": () => require("./no-multi-assign"), + "no-multi-spaces": () => require("./no-multi-spaces"), + "no-multi-str": () => require("./no-multi-str"), + "no-multiple-empty-lines": () => require("./no-multiple-empty-lines"), + "no-native-reassign": () => require("./no-native-reassign"), + "no-negated-condition": () => require("./no-negated-condition"), + "no-negated-in-lhs": () => require("./no-negated-in-lhs"), + "no-nested-ternary": () => require("./no-nested-ternary"), + "no-new": () => require("./no-new"), + "no-new-func": () => require("./no-new-func"), + "no-new-object": () => require("./no-new-object"), + "no-new-require": () => require("./no-new-require"), + "no-new-symbol": () => require("./no-new-symbol"), + "no-new-wrappers": () => require("./no-new-wrappers"), + "no-obj-calls": () => require("./no-obj-calls"), + "no-octal": () => require("./no-octal"), + "no-octal-escape": () => require("./no-octal-escape"), + "no-param-reassign": () => require("./no-param-reassign"), + "no-path-concat": () => require("./no-path-concat"), + "no-plusplus": () => require("./no-plusplus"), + "no-process-env": () => require("./no-process-env"), + "no-process-exit": () => require("./no-process-exit"), + "no-proto": () => require("./no-proto"), + "no-prototype-builtins": () => require("./no-prototype-builtins"), + "no-redeclare": () => require("./no-redeclare"), + "no-regex-spaces": () => require("./no-regex-spaces"), + "no-restricted-globals": () => require("./no-restricted-globals"), + "no-restricted-imports": () => require("./no-restricted-imports"), + "no-restricted-modules": () => require("./no-restricted-modules"), + "no-restricted-properties": () => require("./no-restricted-properties"), + "no-restricted-syntax": () => require("./no-restricted-syntax"), + "no-return-assign": () => require("./no-return-assign"), + "no-return-await": () => require("./no-return-await"), + "no-script-url": () => require("./no-script-url"), + "no-self-assign": () => require("./no-self-assign"), + "no-self-compare": () => require("./no-self-compare"), + "no-sequences": () => require("./no-sequences"), + "no-shadow": () => require("./no-shadow"), + "no-shadow-restricted-names": () => require("./no-shadow-restricted-names"), + "no-spaced-func": () => require("./no-spaced-func"), + "no-sparse-arrays": () => require("./no-sparse-arrays"), + "no-sync": () => require("./no-sync"), + "no-tabs": () => require("./no-tabs"), + "no-template-curly-in-string": () => require("./no-template-curly-in-string"), + "no-ternary": () => require("./no-ternary"), + "no-this-before-super": () => require("./no-this-before-super"), + "no-throw-literal": () => require("./no-throw-literal"), + "no-trailing-spaces": () => require("./no-trailing-spaces"), + "no-undef": () => require("./no-undef"), + "no-undef-init": () => require("./no-undef-init"), + "no-undefined": () => require("./no-undefined"), + "no-underscore-dangle": () => require("./no-underscore-dangle"), + "no-unexpected-multiline": () => require("./no-unexpected-multiline"), + "no-unmodified-loop-condition": () => require("./no-unmodified-loop-condition"), + "no-unneeded-ternary": () => require("./no-unneeded-ternary"), + "no-unreachable": () => require("./no-unreachable"), + "no-unsafe-finally": () => require("./no-unsafe-finally"), + "no-unsafe-negation": () => require("./no-unsafe-negation"), + "no-unused-expressions": () => require("./no-unused-expressions"), + "no-unused-labels": () => require("./no-unused-labels"), + "no-unused-vars": () => require("./no-unused-vars"), + "no-use-before-define": () => require("./no-use-before-define"), + "no-useless-call": () => require("./no-useless-call"), + "no-useless-catch": () => require("./no-useless-catch"), + "no-useless-computed-key": () => require("./no-useless-computed-key"), + "no-useless-concat": () => require("./no-useless-concat"), + "no-useless-constructor": () => require("./no-useless-constructor"), + "no-useless-escape": () => require("./no-useless-escape"), + "no-useless-rename": () => require("./no-useless-rename"), + "no-useless-return": () => require("./no-useless-return"), + "no-var": () => require("./no-var"), + "no-void": () => require("./no-void"), + "no-warning-comments": () => require("./no-warning-comments"), + "no-whitespace-before-property": () => require("./no-whitespace-before-property"), + "no-with": () => require("./no-with"), + "nonblock-statement-body-position": () => require("./nonblock-statement-body-position"), + "object-curly-newline": () => require("./object-curly-newline"), + "object-curly-spacing": () => require("./object-curly-spacing"), + "object-property-newline": () => require("./object-property-newline"), + "object-shorthand": () => require("./object-shorthand"), + "one-var": () => require("./one-var"), + "one-var-declaration-per-line": () => require("./one-var-declaration-per-line"), + "operator-assignment": () => require("./operator-assignment"), + "operator-linebreak": () => require("./operator-linebreak"), + "padded-blocks": () => require("./padded-blocks"), + "padding-line-between-statements": () => require("./padding-line-between-statements"), + "prefer-arrow-callback": () => require("./prefer-arrow-callback"), + "prefer-const": () => require("./prefer-const"), + "prefer-destructuring": () => require("./prefer-destructuring"), + "prefer-named-capture-group": () => require("./prefer-named-capture-group"), + "prefer-numeric-literals": () => require("./prefer-numeric-literals"), + "prefer-object-spread": () => require("./prefer-object-spread"), + "prefer-promise-reject-errors": () => require("./prefer-promise-reject-errors"), + "prefer-reflect": () => require("./prefer-reflect"), + "prefer-rest-params": () => require("./prefer-rest-params"), + "prefer-spread": () => require("./prefer-spread"), + "prefer-template": () => require("./prefer-template"), + "quote-props": () => require("./quote-props"), + quotes: () => require("./quotes"), + radix: () => require("./radix"), + "require-atomic-updates": () => require("./require-atomic-updates"), + "require-await": () => require("./require-await"), + "require-jsdoc": () => require("./require-jsdoc"), + "require-unicode-regexp": () => require("./require-unicode-regexp"), + "require-yield": () => require("./require-yield"), + "rest-spread-spacing": () => require("./rest-spread-spacing"), + semi: () => require("./semi"), + "semi-spacing": () => require("./semi-spacing"), + "semi-style": () => require("./semi-style"), + "sort-imports": () => require("./sort-imports"), + "sort-keys": () => require("./sort-keys"), + "sort-vars": () => require("./sort-vars"), + "space-before-blocks": () => require("./space-before-blocks"), + "space-before-function-paren": () => require("./space-before-function-paren"), + "space-in-parens": () => require("./space-in-parens"), + "space-infix-ops": () => require("./space-infix-ops"), + "space-unary-ops": () => require("./space-unary-ops"), + "spaced-comment": () => require("./spaced-comment"), + strict: () => require("./strict"), + "switch-colon-spacing": () => require("./switch-colon-spacing"), + "symbol-description": () => require("./symbol-description"), + "template-curly-spacing": () => require("./template-curly-spacing"), + "template-tag-spacing": () => require("./template-tag-spacing"), + "unicode-bom": () => require("./unicode-bom"), + "use-isnan": () => require("./use-isnan"), + "valid-jsdoc": () => require("./valid-jsdoc"), + "valid-typeof": () => require("./valid-typeof"), + "vars-on-top": () => require("./vars-on-top"), + "wrap-iife": () => require("./wrap-iife"), + "wrap-regex": () => require("./wrap-regex"), + "yield-star-spacing": () => require("./yield-star-spacing"), + yoda: () => require("./yoda") +})); diff --git a/tools/node_modules/eslint/lib/rules/jsx-quotes.js b/tools/node_modules/eslint/lib/rules/jsx-quotes.js index 6d709afe35b334..e6764b2e817732 100644 --- a/tools/node_modules/eslint/lib/rules/jsx-quotes.js +++ b/tools/node_modules/eslint/lib/rules/jsx-quotes.js @@ -9,7 +9,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Constants diff --git a/tools/node_modules/eslint/lib/rules/key-spacing.js b/tools/node_modules/eslint/lib/rules/key-spacing.js index 7da7f9aa0240c1..994c35627f7522 100644 --- a/tools/node_modules/eslint/lib/rules/key-spacing.js +++ b/tools/node_modules/eslint/lib/rules/key-spacing.js @@ -8,7 +8,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Helpers diff --git a/tools/node_modules/eslint/lib/rules/keyword-spacing.js b/tools/node_modules/eslint/lib/rules/keyword-spacing.js index 97df9418307e5d..a1bf9910427eae 100644 --- a/tools/node_modules/eslint/lib/rules/keyword-spacing.js +++ b/tools/node_modules/eslint/lib/rules/keyword-spacing.js @@ -9,8 +9,8 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"), - keywords = require("../util/keywords"); +const astUtils = require("./utils/ast-utils"), + keywords = require("./utils/keywords"); //------------------------------------------------------------------------------ // Constants diff --git a/tools/node_modules/eslint/lib/rules/line-comment-position.js b/tools/node_modules/eslint/lib/rules/line-comment-position.js index 0023a1f11f3c48..77ee147cbec988 100644 --- a/tools/node_modules/eslint/lib/rules/line-comment-position.js +++ b/tools/node_modules/eslint/lib/rules/line-comment-position.js @@ -4,7 +4,7 @@ */ "use strict"; -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition @@ -31,8 +31,7 @@ module.exports = { type: "object", properties: { position: { - enum: ["above", "beside"], - default: "above" + enum: ["above", "beside"] }, ignorePattern: { type: "string" @@ -78,7 +77,7 @@ module.exports = { const defaultIgnoreRegExp = astUtils.COMMENTS_IGNORE_PATTERN; const fallThroughRegExp = /^\s*falls?\s?through/u; - const customIgnoreRegExp = new RegExp(ignorePattern); // eslint-disable-line require-unicode-regexp + const customIgnoreRegExp = new RegExp(ignorePattern, "u"); const sourceCode = context.getSourceCode(); //-------------------------------------------------------------------------- diff --git a/tools/node_modules/eslint/lib/rules/linebreak-style.js b/tools/node_modules/eslint/lib/rules/linebreak-style.js index 4523d6f58a1871..97d552ea07c966 100644 --- a/tools/node_modules/eslint/lib/rules/linebreak-style.js +++ b/tools/node_modules/eslint/lib/rules/linebreak-style.js @@ -9,7 +9,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/lines-around-comment.js b/tools/node_modules/eslint/lib/rules/lines-around-comment.js index f2f9e3f9d45e45..5e1b83cdd5d24c 100644 --- a/tools/node_modules/eslint/lib/rules/lines-around-comment.js +++ b/tools/node_modules/eslint/lib/rules/lines-around-comment.js @@ -9,7 +9,7 @@ //------------------------------------------------------------------------------ const lodash = require("lodash"), - astUtils = require("../util/ast-utils"); + astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Helpers @@ -130,7 +130,7 @@ module.exports = { const options = Object.assign({}, context.options[0]); const ignorePattern = options.ignorePattern; const defaultIgnoreRegExp = astUtils.COMMENTS_IGNORE_PATTERN; - const customIgnoreRegExp = new RegExp(ignorePattern); // eslint-disable-line require-unicode-regexp + const customIgnoreRegExp = new RegExp(ignorePattern, "u"); const applyDefaultIgnorePatterns = options.applyDefaultIgnorePatterns !== false; options.beforeBlockComment = typeof options.beforeBlockComment !== "undefined" ? options.beforeBlockComment : true; diff --git a/tools/node_modules/eslint/lib/rules/lines-around-directive.js b/tools/node_modules/eslint/lib/rules/lines-around-directive.js index c2e5fd75aaa07d..39686d98916f80 100644 --- a/tools/node_modules/eslint/lib/rules/lines-around-directive.js +++ b/tools/node_modules/eslint/lib/rules/lines-around-directive.js @@ -6,7 +6,7 @@ "use strict"; -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition 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 index 19ae8a6a292c27..60332a1b3ca366 100644 --- a/tools/node_modules/eslint/lib/rules/lines-between-class-members.js +++ b/tools/node_modules/eslint/lib/rules/lines-between-class-members.js @@ -4,7 +4,7 @@ */ "use strict"; -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition 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 index ae7be904f907f5..bb48a546e95c60 100644 --- a/tools/node_modules/eslint/lib/rules/max-classes-per-file.js +++ b/tools/node_modules/eslint/lib/rules/max-classes-per-file.js @@ -32,7 +32,7 @@ module.exports = { ], messages: { - maximumExceeded: "Number of classes per file must not exceed {{ max }}." + maximumExceeded: "File has too many classes ({{ classCount }}). Maximum allowed is {{ max }}." } }, create(context) { @@ -51,6 +51,7 @@ module.exports = { node, messageId: "maximumExceeded", data: { + classCount, max: maxClasses } }); diff --git a/tools/node_modules/eslint/lib/rules/max-depth.js b/tools/node_modules/eslint/lib/rules/max-depth.js index de684dd9239bf7..5c5296bec00b19 100644 --- a/tools/node_modules/eslint/lib/rules/max-depth.js +++ b/tools/node_modules/eslint/lib/rules/max-depth.js @@ -45,7 +45,7 @@ module.exports = { } ], messages: { - tooDeeply: "Blocks are nested too deeply ({{depth}})." + tooDeeply: "Blocks are nested too deeply ({{depth}}). Maximum allowed is {{maxDepth}}." } }, @@ -97,7 +97,7 @@ module.exports = { const len = ++functionStack[functionStack.length - 1]; if (len > maxDepth) { - context.report({ node, messageId: "tooDeeply", data: { depth: len } }); + context.report({ node, messageId: "tooDeeply", data: { depth: len, maxDepth } }); } } diff --git a/tools/node_modules/eslint/lib/rules/max-len.js b/tools/node_modules/eslint/lib/rules/max-len.js index 6e7dd6f1ac119f..70e4ae867f66ff 100644 --- a/tools/node_modules/eslint/lib/rules/max-len.js +++ b/tools/node_modules/eslint/lib/rules/max-len.js @@ -14,8 +14,7 @@ const OPTIONS_SCHEMA = { properties: { code: { type: "integer", - minimum: 0, - default: 80 + minimum: 0 }, comments: { type: "integer", @@ -23,35 +22,28 @@ const OPTIONS_SCHEMA = { }, tabWidth: { type: "integer", - minimum: 0, - default: 4 + minimum: 0 }, ignorePattern: { type: "string" }, ignoreComments: { - type: "boolean", - default: false + type: "boolean" }, ignoreStrings: { - type: "boolean", - default: false + type: "boolean" }, ignoreUrls: { - type: "boolean", - default: false + type: "boolean" }, ignoreTemplateLiterals: { - type: "boolean", - default: false + type: "boolean" }, ignoreRegExpLiterals: { - type: "boolean", - default: false + type: "boolean" }, ignoreTrailingComments: { - type: "boolean", - default: false + type: "boolean" } }, additionalProperties: false @@ -88,8 +80,8 @@ module.exports = { OPTIONS_SCHEMA ], messages: { - max: "Line {{lineNumber}} exceeds the maximum line length of {{maxLength}}.", - maxComment: "Line {{lineNumber}} exceeds the maximum comment line length of {{maxCommentLength}}." + max: "This line has a length of {{lineLength}}. Maximum allowed is {{maxLength}}.", + maxComment: "This line has a comment length of {{lineLength}}. Maximum allowed is {{maxCommentLength}}." } }, @@ -141,19 +133,19 @@ module.exports = { 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, + const maxLength = typeof options.code === "number" ? options.code : 80, + tabWidth = typeof options.tabWidth === "number" ? options.tabWidth : 4, + ignoreComments = !!options.ignoreComments, + ignoreStrings = !!options.ignoreStrings, + ignoreTemplateLiterals = !!options.ignoreTemplateLiterals, + ignoreRegExpLiterals = !!options.ignoreRegExpLiterals, + ignoreTrailingComments = !!options.ignoreTrailingComments || !!options.ignoreComments, + ignoreUrls = !!options.ignoreUrls, maxCommentLength = options.comments; let ignorePattern = options.ignorePattern || null; if (ignorePattern) { - ignorePattern = new RegExp(ignorePattern); // eslint-disable-line require-unicode-regexp + ignorePattern = new RegExp(ignorePattern, "u"); } //-------------------------------------------------------------------------- @@ -354,7 +346,7 @@ module.exports = { loc: { line: lineNumber, column: 0 }, messageId: "maxComment", data: { - lineNumber: i + 1, + lineLength, maxCommentLength } }); @@ -365,7 +357,7 @@ module.exports = { loc: { line: lineNumber, column: 0 }, messageId: "max", data: { - lineNumber: i + 1, + lineLength, maxLength } }); 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 index 3b2f656fb76857..0cfc1f8da9e65e 100644 --- a/tools/node_modules/eslint/lib/rules/max-lines-per-function.js +++ b/tools/node_modules/eslint/lib/rules/max-lines-per-function.js @@ -8,7 +8,9 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); + +const lodash = require("lodash"); //------------------------------------------------------------------------------ // Constants @@ -19,20 +21,16 @@ const OPTIONS_SCHEMA = { properties: { max: { type: "integer", - minimum: 0, - default: 50 + minimum: 0 }, skipComments: { - type: "boolean", - default: false + type: "boolean" }, skipBlankLines: { - type: "boolean", - default: false + type: "boolean" }, IIFEs: { - type: "boolean", - default: false + type: "boolean" } }, additionalProperties: false @@ -101,10 +99,10 @@ module.exports = { let IIFEs = false; if (typeof option === "object") { - maxLines = option.max; - skipComments = option.skipComments; - skipBlankLines = option.skipBlankLines; - IIFEs = option.IIFEs; + maxLines = typeof option.max === "number" ? option.max : 50; + skipComments = !!option.skipComments; + skipBlankLines = !!option.skipBlankLines; + IIFEs = !!option.IIFEs; } else if (typeof option === "number") { maxLines = option; } @@ -196,7 +194,7 @@ module.exports = { } if (lineCount > maxLines) { - const name = astUtils.getFunctionNameWithKind(funcNode); + const name = lodash.upperFirst(astUtils.getFunctionNameWithKind(funcNode)); context.report({ node, diff --git a/tools/node_modules/eslint/lib/rules/max-lines.js b/tools/node_modules/eslint/lib/rules/max-lines.js index 4e5f23b5d05660..299377bc2dddfc 100644 --- a/tools/node_modules/eslint/lib/rules/max-lines.js +++ b/tools/node_modules/eslint/lib/rules/max-lines.js @@ -9,7 +9,7 @@ //------------------------------------------------------------------------------ const lodash = require("lodash"); -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition @@ -53,7 +53,7 @@ module.exports = { } ], messages: { - exceed: "File must be at most {{max}} lines long. It's {{actual}} lines long." + exceed: "File has too many lines ({{actual}}). Maximum allowed is {{max}}." } }, diff --git a/tools/node_modules/eslint/lib/rules/max-params.js b/tools/node_modules/eslint/lib/rules/max-params.js index e1de3ef6f13abe..4eebe2d95a31e3 100644 --- a/tools/node_modules/eslint/lib/rules/max-params.js +++ b/tools/node_modules/eslint/lib/rules/max-params.js @@ -11,7 +11,7 @@ const lodash = require("lodash"); -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition 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 index 597847f88f8ba4..e9212001a34156 100644 --- a/tools/node_modules/eslint/lib/rules/max-statements-per-line.js +++ b/tools/node_modules/eslint/lib/rules/max-statements-per-line.js @@ -8,7 +8,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/max-statements.js b/tools/node_modules/eslint/lib/rules/max-statements.js index 7dc3fd50cfc2e2..437b393a5082f4 100644 --- a/tools/node_modules/eslint/lib/rules/max-statements.js +++ b/tools/node_modules/eslint/lib/rules/max-statements.js @@ -11,7 +11,7 @@ const lodash = require("lodash"); -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/multiline-comment-style.js b/tools/node_modules/eslint/lib/rules/multiline-comment-style.js index ece1035eaa9f84..e4470c20f43f51 100644 --- a/tools/node_modules/eslint/lib/rules/multiline-comment-style.js +++ b/tools/node_modules/eslint/lib/rules/multiline-comment-style.js @@ -4,7 +4,7 @@ */ "use strict"; -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/multiline-ternary.js b/tools/node_modules/eslint/lib/rules/multiline-ternary.js index 83378dcd86e3e5..3b98d0b3cf12dc 100644 --- a/tools/node_modules/eslint/lib/rules/multiline-ternary.js +++ b/tools/node_modules/eslint/lib/rules/multiline-ternary.js @@ -5,7 +5,7 @@ "use strict"; -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/new-cap.js b/tools/node_modules/eslint/lib/rules/new-cap.js index 9e88981ce55b67..dcae238d9b9efd 100644 --- a/tools/node_modules/eslint/lib/rules/new-cap.js +++ b/tools/node_modules/eslint/lib/rules/new-cap.js @@ -136,10 +136,10 @@ module.exports = { const skipProperties = config.properties === false; const newIsCapExceptions = checkArray(config, "newIsCapExceptions", []).reduce(invert, {}); - const newIsCapExceptionPattern = config.newIsCapExceptionPattern ? new RegExp(config.newIsCapExceptionPattern) : null; // eslint-disable-line require-unicode-regexp + const newIsCapExceptionPattern = config.newIsCapExceptionPattern ? new RegExp(config.newIsCapExceptionPattern, "u") : null; const capIsNewExceptions = calculateCapIsNewExceptions(config); - const capIsNewExceptionPattern = config.capIsNewExceptionPattern ? new RegExp(config.capIsNewExceptionPattern) : null; // eslint-disable-line require-unicode-regexp + const capIsNewExceptionPattern = config.capIsNewExceptionPattern ? new RegExp(config.capIsNewExceptionPattern, "u") : null; const listeners = {}; diff --git a/tools/node_modules/eslint/lib/rules/new-parens.js b/tools/node_modules/eslint/lib/rules/new-parens.js index edd3c1e1c2ef47..4b9958fe6cb2fe 100644 --- a/tools/node_modules/eslint/lib/rules/new-parens.js +++ b/tools/node_modules/eslint/lib/rules/new-parens.js @@ -9,7 +9,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Helpers @@ -24,38 +24,70 @@ module.exports = { type: "layout", docs: { - description: "require parentheses when invoking a constructor with no arguments", + description: "enforce or disallow parentheses when invoking a constructor with no arguments", category: "Stylistic Issues", recommended: false, url: "https://eslint.org/docs/rules/new-parens" }, fixable: "code", - schema: [], + schema: { + anyOf: [ + { + type: "array", + items: [ + { + enum: ["always", "never"] + } + ], + minItems: 0, + maxItems: 1 + } + ] + }, messages: { - missing: "Missing '()' invoking a constructor." + missing: "Missing '()' invoking a constructor.", + unnecessary: "Unnecessary '()' invoking a constructor with no arguments." } }, create(context) { + const options = context.options; + const always = options[0] !== "never"; // Default is always + const sourceCode = context.getSourceCode(); return { NewExpression(node) { if (node.arguments.length !== 0) { - return; // shortcut: if there are arguments, there have to be parens + return; // 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, "()") - }); + if (always) { + if (!hasParens) { + context.report({ + node, + messageId: "missing", + fix: fixer => fixer.insertTextAfter(node, "()") + }); + } + } else { + if (hasParens) { + context.report({ + node, + messageId: "unnecessary", + fix: fixer => [ + fixer.remove(sourceCode.getTokenBefore(lastToken)), + fixer.remove(lastToken), + fixer.insertTextBefore(node, "("), + 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 index 036cefc22cab25..8f244149c5574a 100644 --- a/tools/node_modules/eslint/lib/rules/newline-after-var.js +++ b/tools/node_modules/eslint/lib/rules/newline-after-var.js @@ -10,7 +10,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition 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 index 90b540c484d495..4aee76da108989 100644 --- a/tools/node_modules/eslint/lib/rules/newline-per-chained-call.js +++ b/tools/node_modules/eslint/lib/rules/newline-per-chained-call.js @@ -6,7 +6,7 @@ "use strict"; -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/no-alert.js b/tools/node_modules/eslint/lib/rules/no-alert.js index 609bb0b7729244..287cd2c35701f0 100644 --- a/tools/node_modules/eslint/lib/rules/no-alert.js +++ b/tools/node_modules/eslint/lib/rules/no-alert.js @@ -8,7 +8,7 @@ // Requirements //------------------------------------------------------------------------------ -const getPropertyName = require("../util/ast-utils").getStaticPropertyName; +const getPropertyName = require("./utils/ast-utils").getStaticPropertyName; //------------------------------------------------------------------------------ // Helpers 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 index af15509ed4d394..553311e5804508 100644 --- a/tools/node_modules/eslint/lib/rules/no-async-promise-executor.js +++ b/tools/node_modules/eslint/lib/rules/no-async-promise-executor.js @@ -15,7 +15,7 @@ module.exports = { docs: { description: "disallow using an async function as a Promise executor", category: "Possible Errors", - recommended: false, + recommended: true, url: "https://eslint.org/docs/rules/no-async-promise-executor" }, diff --git a/tools/node_modules/eslint/lib/rules/no-catch-shadow.js b/tools/node_modules/eslint/lib/rules/no-catch-shadow.js index 60a0493b3431a8..4917af84e43211 100644 --- a/tools/node_modules/eslint/lib/rules/no-catch-shadow.js +++ b/tools/node_modules/eslint/lib/rules/no-catch-shadow.js @@ -10,7 +10,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/no-class-assign.js b/tools/node_modules/eslint/lib/rules/no-class-assign.js index 7bc65df1ba6004..986bdd7c1c3e01 100644 --- a/tools/node_modules/eslint/lib/rules/no-class-assign.js +++ b/tools/node_modules/eslint/lib/rules/no-class-assign.js @@ -5,7 +5,7 @@ "use strict"; -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/no-cond-assign.js b/tools/node_modules/eslint/lib/rules/no-cond-assign.js index aed3e4a7a9b642..67dcd28b2087b5 100644 --- a/tools/node_modules/eslint/lib/rules/no-cond-assign.js +++ b/tools/node_modules/eslint/lib/rules/no-cond-assign.js @@ -4,7 +4,7 @@ */ "use strict"; -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); const NODE_DESCRIPTIONS = { DoWhileStatement: "a 'do...while' statement", @@ -86,7 +86,7 @@ module.exports = { nextToken = sourceCode.getTokenAfter(node, 1); return astUtils.isParenthesised(sourceCode, node) && - astUtils.isOpeningParenToken(previousToken) && previousToken.range[1] <= node.range[0] && + previousToken && astUtils.isOpeningParenToken(previousToken) && previousToken.range[1] <= node.range[0] && astUtils.isClosingParenToken(nextToken) && nextToken.range[0] >= node.range[1]; } diff --git a/tools/node_modules/eslint/lib/rules/no-confusing-arrow.js b/tools/node_modules/eslint/lib/rules/no-confusing-arrow.js index 79df9a5138759a..895b9499dde051 100644 --- a/tools/node_modules/eslint/lib/rules/no-confusing-arrow.js +++ b/tools/node_modules/eslint/lib/rules/no-confusing-arrow.js @@ -6,7 +6,7 @@ "use strict"; -const astUtils = require("../util/ast-utils.js"); +const astUtils = require("./utils/ast-utils.js"); //------------------------------------------------------------------------------ // Helpers @@ -41,7 +41,7 @@ module.exports = { schema: [{ type: "object", properties: { - allowParens: { type: "boolean", default: false } + allowParens: { type: "boolean", default: true } }, additionalProperties: false }], @@ -53,8 +53,10 @@ module.exports = { create(context) { const config = context.options[0] || {}; + const allowParens = config.allowParens || (config.allowParens === void 0); const sourceCode = context.getSourceCode(); + /** * Reports if an arrow function contains an ambiguous conditional. * @param {ASTNode} node - A node to check and report. @@ -63,14 +65,14 @@ module.exports = { function checkArrowFunc(node) { const body = node.body; - if (isConditional(body) && !(config.allowParens && astUtils.isParenthesised(sourceCode, body))) { + if (isConditional(body) && !(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 allowParens && fixer.replaceText(node.body, `(${sourceCode.getText(node.body)})`); } }); } diff --git a/tools/node_modules/eslint/lib/rules/no-console.js b/tools/node_modules/eslint/lib/rules/no-console.js index d3a2e34475168f..e4b5ce1ea44739 100644 --- a/tools/node_modules/eslint/lib/rules/no-console.js +++ b/tools/node_modules/eslint/lib/rules/no-console.js @@ -9,7 +9,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition @@ -22,7 +22,7 @@ module.exports = { docs: { description: "disallow the use of `console`", category: "Possible Errors", - recommended: true, + recommended: false, url: "https://eslint.org/docs/rules/no-console" }, diff --git a/tools/node_modules/eslint/lib/rules/no-const-assign.js b/tools/node_modules/eslint/lib/rules/no-const-assign.js index 32f8154cc23eae..9f4c91fa305c16 100644 --- a/tools/node_modules/eslint/lib/rules/no-const-assign.js +++ b/tools/node_modules/eslint/lib/rules/no-const-assign.js @@ -5,7 +5,7 @@ "use strict"; -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/no-div-regex.js b/tools/node_modules/eslint/lib/rules/no-div-regex.js index 408e006528b584..0ccabdcc6988b4 100644 --- a/tools/node_modules/eslint/lib/rules/no-div-regex.js +++ b/tools/node_modules/eslint/lib/rules/no-div-regex.js @@ -20,6 +20,8 @@ module.exports = { url: "https://eslint.org/docs/rules/no-div-regex" }, + fixable: "code", + schema: [], messages: { @@ -36,7 +38,13 @@ module.exports = { const token = sourceCode.getFirstToken(node); if (token.type === "RegularExpression" && token.value[1] === "=") { - context.report({ node, messageId: "unexpected" }); + context.report({ + node, + messageId: "unexpected", + fix(fixer) { + return fixer.replaceTextRange([token.range[0] + 1, token.range[0] + 2], "[=]"); + } + }); } } }; diff --git a/tools/node_modules/eslint/lib/rules/no-dupe-keys.js b/tools/node_modules/eslint/lib/rules/no-dupe-keys.js index c0ccf73b8d3664..d0751b4a2da226 100644 --- a/tools/node_modules/eslint/lib/rules/no-dupe-keys.js +++ b/tools/node_modules/eslint/lib/rules/no-dupe-keys.js @@ -9,7 +9,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Helpers diff --git a/tools/node_modules/eslint/lib/rules/no-else-return.js b/tools/node_modules/eslint/lib/rules/no-else-return.js index 17f355eeb0c081..2f3fcf808f456a 100644 --- a/tools/node_modules/eslint/lib/rules/no-else-return.js +++ b/tools/node_modules/eslint/lib/rules/no-else-return.js @@ -9,8 +9,8 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); -const FixTracker = require("../util/fix-tracker"); +const astUtils = require("./utils/ast-utils"); +const FixTracker = require("./utils/fix-tracker"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/no-empty-function.js b/tools/node_modules/eslint/lib/rules/no-empty-function.js index a443796e4e2861..149b1477dc1bd9 100644 --- a/tools/node_modules/eslint/lib/rules/no-empty-function.js +++ b/tools/node_modules/eslint/lib/rules/no-empty-function.js @@ -9,7 +9,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Helpers diff --git a/tools/node_modules/eslint/lib/rules/no-empty.js b/tools/node_modules/eslint/lib/rules/no-empty.js index 2d55dee66596a3..45bf03c13aee5f 100644 --- a/tools/node_modules/eslint/lib/rules/no-empty.js +++ b/tools/node_modules/eslint/lib/rules/no-empty.js @@ -8,7 +8,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/no-eval.js b/tools/node_modules/eslint/lib/rules/no-eval.js index d4b79468f194a4..d580f369259e2d 100644 --- a/tools/node_modules/eslint/lib/rules/no-eval.js +++ b/tools/node_modules/eslint/lib/rules/no-eval.js @@ -9,7 +9,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Helpers diff --git a/tools/node_modules/eslint/lib/rules/no-ex-assign.js b/tools/node_modules/eslint/lib/rules/no-ex-assign.js index 4cc179a6e8f00f..21d3220799b876 100644 --- a/tools/node_modules/eslint/lib/rules/no-ex-assign.js +++ b/tools/node_modules/eslint/lib/rules/no-ex-assign.js @@ -5,7 +5,7 @@ "use strict"; -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/no-extend-native.js b/tools/node_modules/eslint/lib/rules/no-extend-native.js index 13895f0d06bb1b..7ab25ab4895476 100644 --- a/tools/node_modules/eslint/lib/rules/no-extend-native.js +++ b/tools/node_modules/eslint/lib/rules/no-extend-native.js @@ -9,7 +9,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); const globals = require("globals"); //------------------------------------------------------------------------------ diff --git a/tools/node_modules/eslint/lib/rules/no-extra-bind.js b/tools/node_modules/eslint/lib/rules/no-extra-bind.js index abbe1868e89837..5380cf217f4f15 100644 --- a/tools/node_modules/eslint/lib/rules/no-extra-bind.js +++ b/tools/node_modules/eslint/lib/rules/no-extra-bind.js @@ -8,7 +8,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Helpers 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 index 615603177a5a76..8dd526477d4bd1 100644 --- a/tools/node_modules/eslint/lib/rules/no-extra-boolean-cast.js +++ b/tools/node_modules/eslint/lib/rules/no-extra-boolean-cast.js @@ -9,7 +9,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/no-extra-label.js b/tools/node_modules/eslint/lib/rules/no-extra-label.js index f8acf7b2834fde..a4a98af5853b98 100644 --- a/tools/node_modules/eslint/lib/rules/no-extra-label.js +++ b/tools/node_modules/eslint/lib/rules/no-extra-label.js @@ -9,7 +9,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/no-extra-parens.js b/tools/node_modules/eslint/lib/rules/no-extra-parens.js index 400ce0c76131d3..98fc49654cb951 100644 --- a/tools/node_modules/eslint/lib/rules/no-extra-parens.js +++ b/tools/node_modules/eslint/lib/rules/no-extra-parens.js @@ -8,7 +8,7 @@ // Rule Definition //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils.js"); +const astUtils = require("./utils/ast-utils.js"); module.exports = { meta: { diff --git a/tools/node_modules/eslint/lib/rules/no-extra-semi.js b/tools/node_modules/eslint/lib/rules/no-extra-semi.js index d87a181672f851..e99dd67b35b8fc 100644 --- a/tools/node_modules/eslint/lib/rules/no-extra-semi.js +++ b/tools/node_modules/eslint/lib/rules/no-extra-semi.js @@ -9,8 +9,8 @@ // Requirements //------------------------------------------------------------------------------ -const FixTracker = require("../util/fix-tracker"); -const astUtils = require("../util/ast-utils"); +const FixTracker = require("./utils/fix-tracker"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/no-fallthrough.js b/tools/node_modules/eslint/lib/rules/no-fallthrough.js index 241e07258e10f9..c6a71b6c8c63b2 100644 --- a/tools/node_modules/eslint/lib/rules/no-fallthrough.js +++ b/tools/node_modules/eslint/lib/rules/no-fallthrough.js @@ -95,7 +95,7 @@ module.exports = { let fallthroughCommentPattern = null; if (options.commentPattern) { - fallthroughCommentPattern = new RegExp(options.commentPattern); // eslint-disable-line require-unicode-regexp + fallthroughCommentPattern = new RegExp(options.commentPattern, "u"); } else { fallthroughCommentPattern = DEFAULT_FALLTHROUGH_COMMENT; } diff --git a/tools/node_modules/eslint/lib/rules/no-floating-decimal.js b/tools/node_modules/eslint/lib/rules/no-floating-decimal.js index de5a521525fdaa..b1d883212e2076 100644 --- a/tools/node_modules/eslint/lib/rules/no-floating-decimal.js +++ b/tools/node_modules/eslint/lib/rules/no-floating-decimal.js @@ -9,7 +9,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/no-func-assign.js b/tools/node_modules/eslint/lib/rules/no-func-assign.js index ae96ab01f43057..d2b4109fa33964 100644 --- a/tools/node_modules/eslint/lib/rules/no-func-assign.js +++ b/tools/node_modules/eslint/lib/rules/no-func-assign.js @@ -5,7 +5,7 @@ "use strict"; -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/no-implicit-coercion.js b/tools/node_modules/eslint/lib/rules/no-implicit-coercion.js index 6483af0229f151..7d463ac2bdc107 100644 --- a/tools/node_modules/eslint/lib/rules/no-implicit-coercion.js +++ b/tools/node_modules/eslint/lib/rules/no-implicit-coercion.js @@ -5,7 +5,7 @@ "use strict"; -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Helpers diff --git a/tools/node_modules/eslint/lib/rules/no-inline-comments.js b/tools/node_modules/eslint/lib/rules/no-inline-comments.js index c282d16e75411a..b35db114100a34 100644 --- a/tools/node_modules/eslint/lib/rules/no-inline-comments.js +++ b/tools/node_modules/eslint/lib/rules/no-inline-comments.js @@ -4,7 +4,7 @@ */ "use strict"; -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/no-invalid-this.js b/tools/node_modules/eslint/lib/rules/no-invalid-this.js index e9be4445260bdb..30ae3fdc31a58f 100644 --- a/tools/node_modules/eslint/lib/rules/no-invalid-this.js +++ b/tools/node_modules/eslint/lib/rules/no-invalid-this.js @@ -9,7 +9,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/no-irregular-whitespace.js b/tools/node_modules/eslint/lib/rules/no-irregular-whitespace.js index de6d518bd50bc2..f339fa6c8f34c9 100644 --- a/tools/node_modules/eslint/lib/rules/no-irregular-whitespace.js +++ b/tools/node_modules/eslint/lib/rules/no-irregular-whitespace.js @@ -10,7 +10,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Constants diff --git a/tools/node_modules/eslint/lib/rules/no-label-var.js b/tools/node_modules/eslint/lib/rules/no-label-var.js index fdba2defc350c6..a9fd042a390225 100644 --- a/tools/node_modules/eslint/lib/rules/no-label-var.js +++ b/tools/node_modules/eslint/lib/rules/no-label-var.js @@ -9,7 +9,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/no-labels.js b/tools/node_modules/eslint/lib/rules/no-labels.js index 29580bd236bbd8..8168dc06c17f91 100644 --- a/tools/node_modules/eslint/lib/rules/no-labels.js +++ b/tools/node_modules/eslint/lib/rules/no-labels.js @@ -8,7 +8,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/no-loop-func.js b/tools/node_modules/eslint/lib/rules/no-loop-func.js index e6063806a5dec2..f4531f3a7da5e7 100644 --- a/tools/node_modules/eslint/lib/rules/no-loop-func.js +++ b/tools/node_modules/eslint/lib/rules/no-loop-func.js @@ -157,13 +157,17 @@ module.exports = { type: "suggestion", docs: { - description: "disallow `function` declarations and expressions inside loop statements", + description: "disallow function declarations that contain unsafe references inside loop statements", category: "Best Practices", recommended: false, url: "https://eslint.org/docs/rules/no-loop-func" }, - schema: [] + schema: [], + + messages: { + unsafeRefs: "Function declared in a loop contains unsafe references to variable(s) {{ varNames }}." + } }, create(context) { @@ -185,11 +189,14 @@ module.exports = { } 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." }); + const unsafeRefs = references.filter(r => !isSafe(loopNode, r)).map(r => r.identifier.name); + + if (unsafeRefs.length > 0) { + context.report({ + node, + messageId: "unsafeRefs", + data: { varNames: `'${unsafeRefs.join("', '")}'` } + }); } } 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 index 4fa650ed52725a..d7c394f463b6a6 100644 --- a/tools/node_modules/eslint/lib/rules/no-misleading-character-class.js +++ b/tools/node_modules/eslint/lib/rules/no-misleading-character-class.js @@ -5,7 +5,7 @@ const { CALL, CONSTRUCT, ReferenceTracker, getStringIfConstant } = require("eslint-utils"); const { RegExpParser, visitRegExpAST } = require("regexpp"); -const { isCombiningCharacter, isEmojiModifier, isRegionalIndicatorSymbol, isSurrogatePair } = require("../util/unicode"); +const { isCombiningCharacter, isEmojiModifier, isRegionalIndicatorSymbol, isSurrogatePair } = require("./utils/unicode"); //------------------------------------------------------------------------------ // Helpers @@ -106,7 +106,7 @@ module.exports = { docs: { description: "disallow characters which are made with multiple code points in character class syntax", category: "Possible Errors", - recommended: false, + recommended: true, url: "https://eslint.org/docs/rules/no-misleading-character-class" }, diff --git a/tools/node_modules/eslint/lib/rules/no-mixed-operators.js b/tools/node_modules/eslint/lib/rules/no-mixed-operators.js index 83f27fb0076915..21e1d95c684552 100644 --- a/tools/node_modules/eslint/lib/rules/no-mixed-operators.js +++ b/tools/node_modules/eslint/lib/rules/no-mixed-operators.js @@ -9,7 +9,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils.js"); +const astUtils = require("./utils/ast-utils.js"); //------------------------------------------------------------------------------ // Helpers diff --git a/tools/node_modules/eslint/lib/rules/no-multi-spaces.js b/tools/node_modules/eslint/lib/rules/no-multi-spaces.js index c5fb07403421af..64a04c5cc58354 100644 --- a/tools/node_modules/eslint/lib/rules/no-multi-spaces.js +++ b/tools/node_modules/eslint/lib/rules/no-multi-spaces.js @@ -5,7 +5,7 @@ "use strict"; -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/no-multi-str.js b/tools/node_modules/eslint/lib/rules/no-multi-str.js index 844842392df7d3..f6832f3341777f 100644 --- a/tools/node_modules/eslint/lib/rules/no-multi-str.js +++ b/tools/node_modules/eslint/lib/rules/no-multi-str.js @@ -9,7 +9,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/no-prototype-builtins.js b/tools/node_modules/eslint/lib/rules/no-prototype-builtins.js index 171395306725eb..87a760156e3693 100644 --- a/tools/node_modules/eslint/lib/rules/no-prototype-builtins.js +++ b/tools/node_modules/eslint/lib/rules/no-prototype-builtins.js @@ -15,7 +15,7 @@ module.exports = { docs: { description: "disallow calling some `Object.prototype` methods directly on objects", category: "Possible Errors", - recommended: false, + recommended: true, url: "https://eslint.org/docs/rules/no-prototype-builtins" }, diff --git a/tools/node_modules/eslint/lib/rules/no-redeclare.js b/tools/node_modules/eslint/lib/rules/no-redeclare.js index 4d689cc6138716..9de2f4ed730364 100644 --- a/tools/node_modules/eslint/lib/rules/no-redeclare.js +++ b/tools/node_modules/eslint/lib/rules/no-redeclare.js @@ -5,6 +5,12 @@ "use strict"; +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ @@ -20,11 +26,17 @@ module.exports = { url: "https://eslint.org/docs/rules/no-redeclare" }, + messages: { + redeclared: "'{{id}}' is already defined.", + redeclaredAsBuiltin: "'{{id}}' is already defined as a built-in global variable.", + redeclaredBySyntax: "'{{id}}' is already defined by a variable declaration." + }, + schema: [ { type: "object", properties: { - builtinGlobals: { type: "boolean", default: false } + builtinGlobals: { type: "boolean", default: true } }, additionalProperties: false } @@ -33,72 +45,128 @@ module.exports = { create(context) { const options = { - builtinGlobals: context.options[0] && context.options[0].builtinGlobals + builtinGlobals: Boolean( + context.options.length === 0 || + context.options[0].builtinGlobals + ) }; + const sourceCode = context.getSourceCode(); /** - * Find variables in a given scope and flag redeclared ones. - * @param {Scope} scope - An eslint-scope scope object. - * @returns {void} - * @private + * Iterate declarations of a given variable. + * @param {escope.variable} variable The variable object to iterate declarations. + * @returns {IterableIterator<{type:string,node:ASTNode,loc:SourceLocation}>} The declarations. */ - function findVariablesInScope(scope) { - scope.variables.forEach(variable => { - const hasBuiltin = options.builtinGlobals && "writeable" in variable; - const count = (hasBuiltin ? 1 : 0) + variable.identifiers.length; + function *iterateDeclarations(variable) { + if (options.builtinGlobals && ( + variable.eslintImplicitGlobalSetting === "readonly" || + variable.eslintImplicitGlobalSetting === "writable" + )) { + yield { type: "builtin" }; + } - if (count >= 2) { - variable.identifiers.sort((a, b) => a.range[1] - b.range[1]); + for (const id of variable.identifiers) { + yield { type: "syntax", node: id, loc: id.loc }; + } - 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 } }); - } + if (variable.eslintExplicitGlobalComments) { + for (const comment of variable.eslintExplicitGlobalComments) { + yield { + type: "comment", + node: comment, + loc: astUtils.getNameLocationInGlobalDirectiveComment( + sourceCode, + comment, + variable.name + ) + }; } - }); - + } } /** - * Find variables in the current scope. - * @param {ASTNode} node - The Program node. + * Find variables in a given scope and flag redeclared ones. + * @param {Scope} scope - An eslint-scope scope object. * @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); + function findVariablesInScope(scope) { + for (const variable of scope.variables) { + const [ + declaration, + ...extraDeclarations + ] = iterateDeclarations(variable); + + if (extraDeclarations.length === 0) { + continue; + } + + /* + * If the type of a declaration is different from the type of + * the first declaration, it shows the location of the first + * declaration. + */ + const detailMessageId = declaration.type === "builtin" + ? "redeclaredAsBuiltin" + : "redeclaredBySyntax"; + const data = { id: variable.name }; + + // Report extra declarations. + for (const { type, node, loc } of extraDeclarations) { + const messageId = type === declaration.type + ? "redeclared" + : detailMessageId; + + context.report({ node, loc, messageId, data }); + } } } /** * Find variables in the current scope. + * @param {ASTNode} node The node of the current scope. * @returns {void} * @private */ - function checkForBlock() { - findVariablesInScope(context.getScope()); - } + function checkForBlock(node) { + const scope = context.getScope(); - if (context.parserOptions.ecmaVersion >= 6) { - return { - Program: checkForGlobal, - BlockStatement: checkForBlock, - SwitchStatement: checkForBlock - }; + /* + * In ES5, some node type such as `BlockStatement` doesn't have that scope. + * `scope.block` is a different node in such a case. + */ + if (scope.block === node) { + findVariablesInScope(scope); + } } + return { - Program: checkForGlobal, + Program() { + const scope = context.getScope(); + + findVariablesInScope(scope); + + // Node.js or ES modules has a special scope. + if ( + scope.type === "global" && + scope.childScopes[0] && + + // The special scope's block is the Program node. + scope.block === scope.childScopes[0].block + ) { + findVariablesInScope(scope.childScopes[0]); + } + }, + FunctionDeclaration: checkForBlock, FunctionExpression: checkForBlock, - ArrowFunctionExpression: checkForBlock - }; + ArrowFunctionExpression: checkForBlock, + BlockStatement: checkForBlock, + ForStatement: checkForBlock, + ForInStatement: checkForBlock, + ForOfStatement: checkForBlock, + SwitchStatement: 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 index 75faa11191d2a1..55e79517cef2d7 100644 --- a/tools/node_modules/eslint/lib/rules/no-regex-spaces.js +++ b/tools/node_modules/eslint/lib/rules/no-regex-spaces.js @@ -5,7 +5,7 @@ "use strict"; -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/no-restricted-properties.js b/tools/node_modules/eslint/lib/rules/no-restricted-properties.js index eede6ad1c161dd..bdab22b19c4edc 100644 --- a/tools/node_modules/eslint/lib/rules/no-restricted-properties.js +++ b/tools/node_modules/eslint/lib/rules/no-restricted-properties.js @@ -5,7 +5,7 @@ "use strict"; -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/no-return-assign.js b/tools/node_modules/eslint/lib/rules/no-return-assign.js index c4a79d5fb1cde2..ea6a6bb49fcf6d 100644 --- a/tools/node_modules/eslint/lib/rules/no-return-assign.js +++ b/tools/node_modules/eslint/lib/rules/no-return-assign.js @@ -8,7 +8,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Helpers diff --git a/tools/node_modules/eslint/lib/rules/no-return-await.js b/tools/node_modules/eslint/lib/rules/no-return-await.js index 24cb45ee5a7e52..6652b5932dc1b8 100644 --- a/tools/node_modules/eslint/lib/rules/no-return-await.js +++ b/tools/node_modules/eslint/lib/rules/no-return-await.js @@ -4,7 +4,7 @@ */ "use strict"; -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/no-self-assign.js b/tools/node_modules/eslint/lib/rules/no-self-assign.js index 5b74ca8fbcffd2..79fb50770ef455 100644 --- a/tools/node_modules/eslint/lib/rules/no-self-assign.js +++ b/tools/node_modules/eslint/lib/rules/no-self-assign.js @@ -9,7 +9,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Helpers diff --git a/tools/node_modules/eslint/lib/rules/no-sequences.js b/tools/node_modules/eslint/lib/rules/no-sequences.js index 2570912f348e91..71317c2f7924e4 100644 --- a/tools/node_modules/eslint/lib/rules/no-sequences.js +++ b/tools/node_modules/eslint/lib/rules/no-sequences.js @@ -9,7 +9,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition 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 index f09f3767da4257..9030d523b705d2 100644 --- a/tools/node_modules/eslint/lib/rules/no-shadow-restricted-names.js +++ b/tools/node_modules/eslint/lib/rules/no-shadow-restricted-names.js @@ -28,7 +28,7 @@ module.exports = { docs: { description: "disallow identifiers from shadowing restricted names", category: "Variables", - recommended: false, + recommended: true, url: "https://eslint.org/docs/rules/no-shadow-restricted-names" }, diff --git a/tools/node_modules/eslint/lib/rules/no-shadow.js b/tools/node_modules/eslint/lib/rules/no-shadow.js index 5f617e52a74ba0..1993d60078b662 100644 --- a/tools/node_modules/eslint/lib/rules/no-shadow.js +++ b/tools/node_modules/eslint/lib/rules/no-shadow.js @@ -9,7 +9,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition 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 index bca379bf971b80..b271797240a5ec 100644 --- a/tools/node_modules/eslint/lib/rules/no-this-before-super.js +++ b/tools/node_modules/eslint/lib/rules/no-this-before-super.js @@ -9,7 +9,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Helpers diff --git a/tools/node_modules/eslint/lib/rules/no-throw-literal.js b/tools/node_modules/eslint/lib/rules/no-throw-literal.js index c4a6b86bfb4cc9..29fb3718b4896b 100644 --- a/tools/node_modules/eslint/lib/rules/no-throw-literal.js +++ b/tools/node_modules/eslint/lib/rules/no-throw-literal.js @@ -5,7 +5,7 @@ "use strict"; -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition @@ -22,7 +22,12 @@ module.exports = { url: "https://eslint.org/docs/rules/no-throw-literal" }, - schema: [] + schema: [], + + messages: { + object: "Expected an error object to be thrown.", + undef: "Do not throw undefined." + } }, create(context) { @@ -31,10 +36,10 @@ module.exports = { ThrowStatement(node) { if (!astUtils.couldBeError(node.argument)) { - context.report({ node, message: "Expected an object to be thrown." }); + context.report({ node, messageId: "object" }); } else if (node.argument.type === "Identifier") { if (node.argument.name === "undefined") { - context.report({ node, message: "Do not throw undefined." }); + context.report({ node, messageId: "undef" }); } } diff --git a/tools/node_modules/eslint/lib/rules/no-trailing-spaces.js b/tools/node_modules/eslint/lib/rules/no-trailing-spaces.js index a75ef0ec4c59db..83c01d5e7e2bb3 100644 --- a/tools/node_modules/eslint/lib/rules/no-trailing-spaces.js +++ b/tools/node_modules/eslint/lib/rules/no-trailing-spaces.js @@ -8,7 +8,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/no-undef-init.js b/tools/node_modules/eslint/lib/rules/no-undef-init.js index 67f3944d47e7f4..1390c880fc8621 100644 --- a/tools/node_modules/eslint/lib/rules/no-undef-init.js +++ b/tools/node_modules/eslint/lib/rules/no-undef-init.js @@ -5,7 +5,7 @@ "use strict"; -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/no-unexpected-multiline.js b/tools/node_modules/eslint/lib/rules/no-unexpected-multiline.js index f4a83f0cefa411..8026e1722236ff 100644 --- a/tools/node_modules/eslint/lib/rules/no-unexpected-multiline.js +++ b/tools/node_modules/eslint/lib/rules/no-unexpected-multiline.js @@ -8,7 +8,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition 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 index 5bb54f81d67e31..85292d136ec532 100644 --- a/tools/node_modules/eslint/lib/rules/no-unmodified-loop-condition.js +++ b/tools/node_modules/eslint/lib/rules/no-unmodified-loop-condition.js @@ -9,8 +9,8 @@ // Requirements //------------------------------------------------------------------------------ -const Traverser = require("../util/traverser"), - astUtils = require("../util/ast-utils"); +const Traverser = require("../shared/traverser"), + astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Helpers diff --git a/tools/node_modules/eslint/lib/rules/no-unneeded-ternary.js b/tools/node_modules/eslint/lib/rules/no-unneeded-ternary.js index e75a36430fe8aa..331c9ce94d7fad 100644 --- a/tools/node_modules/eslint/lib/rules/no-unneeded-ternary.js +++ b/tools/node_modules/eslint/lib/rules/no-unneeded-ternary.js @@ -5,7 +5,7 @@ "use strict"; -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); // Operators that always result in a boolean value const BOOLEAN_OPERATORS = new Set(["==", "===", "!=", "!==", ">", ">=", "<", "<=", "in", "instanceof"]); @@ -17,6 +17,7 @@ const OPERATOR_INVERSES = { // Operators like < and >= are not true inverses, since both will return false with NaN. }; +const OR_PRECEDENCE = astUtils.getPrecedence({ type: "LogicalExpression", operator: "||" }); //------------------------------------------------------------------------------ // Rule Definition @@ -141,15 +142,16 @@ module.exports = { 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}`); + const shouldParenthesizeAlternate = ( + astUtils.getPrecedence(node.alternate) < OR_PRECEDENCE && + !astUtils.isParenthesised(sourceCode, node.alternate) + ); + const alternateText = shouldParenthesizeAlternate + ? `(${sourceCode.getText(node.alternate)})` + : astUtils.getParenthesisedText(sourceCode, node.alternate); + const testText = astUtils.getParenthesisedText(sourceCode, node.test); + + return fixer.replaceText(node, `${testText} || ${alternateText}`); } }); } diff --git a/tools/node_modules/eslint/lib/rules/no-unsafe-negation.js b/tools/node_modules/eslint/lib/rules/no-unsafe-negation.js index 3b5b367e42e1ad..f394f674259d1b 100644 --- a/tools/node_modules/eslint/lib/rules/no-unsafe-negation.js +++ b/tools/node_modules/eslint/lib/rules/no-unsafe-negation.js @@ -9,7 +9,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Helpers diff --git a/tools/node_modules/eslint/lib/rules/no-unused-vars.js b/tools/node_modules/eslint/lib/rules/no-unused-vars.js index d4c4c6355c2948..48df3aa3cc1b18 100644 --- a/tools/node_modules/eslint/lib/rules/no-unused-vars.js +++ b/tools/node_modules/eslint/lib/rules/no-unused-vars.js @@ -9,8 +9,7 @@ // Requirements //------------------------------------------------------------------------------ -const lodash = require("lodash"); -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition @@ -88,15 +87,15 @@ module.exports = { config.caughtErrors = firstOption.caughtErrors || config.caughtErrors; if (firstOption.varsIgnorePattern) { - config.varsIgnorePattern = new RegExp(firstOption.varsIgnorePattern); // eslint-disable-line require-unicode-regexp + config.varsIgnorePattern = new RegExp(firstOption.varsIgnorePattern, "u"); } if (firstOption.argsIgnorePattern) { - config.argsIgnorePattern = new RegExp(firstOption.argsIgnorePattern); // eslint-disable-line require-unicode-regexp + config.argsIgnorePattern = new RegExp(firstOption.argsIgnorePattern, "u"); } if (firstOption.caughtErrorsIgnorePattern) { - config.caughtErrorsIgnorePattern = new RegExp(firstOption.caughtErrorsIgnorePattern); // eslint-disable-line require-unicode-regexp + config.caughtErrorsIgnorePattern = new RegExp(firstOption.caughtErrorsIgnorePattern, "u"); } } } @@ -588,39 +587,6 @@ module.exports = { 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,:])`, "gu"); - - // 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 //-------------------------------------------------------------------------- @@ -632,14 +598,8 @@ module.exports = { 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) { + // Report the first declaration. + if (unusedVar.defs.length > 0) { context.report({ node: unusedVar.identifiers[0], message: unusedVar.references.some(ref => ref.isWrite()) @@ -647,6 +607,17 @@ module.exports = { : getDefinedMessage(unusedVar), data: unusedVar }); + + // If there are no regular declaration, report the first `/*globals*/` comment directive. + } else if (unusedVar.eslintExplicitGlobalComments) { + const directiveComment = unusedVar.eslintExplicitGlobalComments[0]; + + context.report({ + node: programNode, + loc: astUtils.getNameLocationInGlobalDirectiveComment(sourceCode, directiveComment, unusedVar.name), + message: getDefinedMessage(unusedVar), + data: unusedVar + }); } } } diff --git a/tools/node_modules/eslint/lib/rules/no-useless-call.js b/tools/node_modules/eslint/lib/rules/no-useless-call.js index 74e8bec08bcf3b..d08b9cb8cb7bb5 100644 --- a/tools/node_modules/eslint/lib/rules/no-useless-call.js +++ b/tools/node_modules/eslint/lib/rules/no-useless-call.js @@ -5,7 +5,7 @@ "use strict"; -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Helpers diff --git a/tools/node_modules/eslint/lib/rules/no-useless-catch.js b/tools/node_modules/eslint/lib/rules/no-useless-catch.js index e4284cfb4f4307..37bf453aecd932 100644 --- a/tools/node_modules/eslint/lib/rules/no-useless-catch.js +++ b/tools/node_modules/eslint/lib/rules/no-useless-catch.js @@ -16,7 +16,7 @@ module.exports = { docs: { description: "disallow unnecessary `catch` clauses", category: "Best Practices", - recommended: false, + recommended: true, url: "https://eslint.org/docs/rules/no-useless-catch" }, 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 index ef1f856f3efc5a..95527832b2d7f0 100644 --- a/tools/node_modules/eslint/lib/rules/no-useless-computed-key.js +++ b/tools/node_modules/eslint/lib/rules/no-useless-computed-key.js @@ -8,7 +8,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/no-useless-concat.js b/tools/node_modules/eslint/lib/rules/no-useless-concat.js index df310119032979..d26003f1e4f4a0 100644 --- a/tools/node_modules/eslint/lib/rules/no-useless-concat.js +++ b/tools/node_modules/eslint/lib/rules/no-useless-concat.js @@ -8,7 +8,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Helpers diff --git a/tools/node_modules/eslint/lib/rules/no-useless-escape.js b/tools/node_modules/eslint/lib/rules/no-useless-escape.js index 82db1f2be44f54..f3764ce91e5614 100644 --- a/tools/node_modules/eslint/lib/rules/no-useless-escape.js +++ b/tools/node_modules/eslint/lib/rules/no-useless-escape.js @@ -5,7 +5,7 @@ "use strict"; -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/no-useless-return.js b/tools/node_modules/eslint/lib/rules/no-useless-return.js index bb11b4b3619c8e..46b5f4b648fc99 100644 --- a/tools/node_modules/eslint/lib/rules/no-useless-return.js +++ b/tools/node_modules/eslint/lib/rules/no-useless-return.js @@ -8,8 +8,8 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"), - FixTracker = require("../util/fix-tracker"); +const astUtils = require("./utils/ast-utils"), + FixTracker = require("./utils/fix-tracker"); //------------------------------------------------------------------------------ // Helpers @@ -255,7 +255,14 @@ module.exports = { if (node.argument) { markReturnStatementsOnCurrentSegmentsAsUsed(); } - if (node.argument || astUtils.isInLoop(node) || isInFinally(node)) { + if ( + node.argument || + astUtils.isInLoop(node) || + isInFinally(node) || + + // Ignore `return` statements in unreachable places (https://github.com/eslint/eslint/issues/11647). + !scopeInfo.codePath.currentSegments.some(s => s.reachable) + ) { return; } diff --git a/tools/node_modules/eslint/lib/rules/no-var.js b/tools/node_modules/eslint/lib/rules/no-var.js index 83681a7aaedf44..e9f191b39f2a78 100644 --- a/tools/node_modules/eslint/lib/rules/no-var.js +++ b/tools/node_modules/eslint/lib/rules/no-var.js @@ -9,7 +9,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Helpers @@ -305,17 +305,16 @@ module.exports = { * @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; + const varToken = sourceCode.getFirstToken(node, { filter: t => t.value === "var" }); + + return canFix(node) + ? fixer.replaceText(varToken, "let") + : null; } }); } diff --git a/tools/node_modules/eslint/lib/rules/no-warning-comments.js b/tools/node_modules/eslint/lib/rules/no-warning-comments.js index 1d1b55460bc055..5a8e0bc7ec221c 100644 --- a/tools/node_modules/eslint/lib/rules/no-warning-comments.js +++ b/tools/node_modules/eslint/lib/rules/no-warning-comments.js @@ -5,7 +5,8 @@ "use strict"; -const astUtils = require("../util/ast-utils"); +const { escapeRegExp } = require("lodash"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition @@ -58,7 +59,7 @@ module.exports = { * @returns {RegExp} The term converted to a RegExp */ function convertToRegExp(term) { - const escaped = term.replace(/[-/\\$^*+?.()|[\]{}]/gu, "\\$&"); + const escaped = escapeRegExp(term); const wordBoundary = "\\b"; const eitherOrWordBoundary = `|${wordBoundary}`; let prefix; @@ -95,7 +96,7 @@ module.exports = { * ^\s*TERM\b. This checks the word boundary * at the beginning of the comment. */ - return new RegExp(prefix + escaped + suffix, "i"); // eslint-disable-line require-unicode-regexp + return new RegExp(prefix + escaped + suffix, "iu"); } /* @@ -103,7 +104,7 @@ module.exports = { * \bTERM\b|\bTERM\b, this checks the entire comment * for the term. */ - return new RegExp(prefix + escaped + suffix + eitherOrWordBoundary + term + wordBoundary, "i"); // eslint-disable-line require-unicode-regexp + return new RegExp(prefix + escaped + suffix + eitherOrWordBoundary + term + wordBoundary, "iu"); } const warningRegExps = warningTerms.map(convertToRegExp); 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 index 1ecc51db67c030..83ff801b2b8a83 100644 --- a/tools/node_modules/eslint/lib/rules/no-whitespace-before-property.js +++ b/tools/node_modules/eslint/lib/rules/no-whitespace-before-property.js @@ -8,7 +8,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/no-with.js b/tools/node_modules/eslint/lib/rules/no-with.js index ecdf22c7d91d6a..5763661584c061 100644 --- a/tools/node_modules/eslint/lib/rules/no-with.js +++ b/tools/node_modules/eslint/lib/rules/no-with.js @@ -16,7 +16,7 @@ module.exports = { docs: { description: "disallow `with` statements", category: "Best Practices", - recommended: false, + recommended: true, url: "https://eslint.org/docs/rules/no-with" }, diff --git a/tools/node_modules/eslint/lib/rules/object-curly-newline.js b/tools/node_modules/eslint/lib/rules/object-curly-newline.js index d1a6bc20f6361e..be9ae23a6f4d40 100644 --- a/tools/node_modules/eslint/lib/rules/object-curly-newline.js +++ b/tools/node_modules/eslint/lib/rules/object-curly-newline.js @@ -9,7 +9,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); const lodash = require("lodash"); //------------------------------------------------------------------------------ diff --git a/tools/node_modules/eslint/lib/rules/object-curly-spacing.js b/tools/node_modules/eslint/lib/rules/object-curly-spacing.js index bde4f14253eeec..079cf5707db77f 100644 --- a/tools/node_modules/eslint/lib/rules/object-curly-spacing.js +++ b/tools/node_modules/eslint/lib/rules/object-curly-spacing.js @@ -4,7 +4,7 @@ */ "use strict"; -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition @@ -82,7 +82,7 @@ module.exports = { token: token.value }, fix(fixer) { - const nextToken = context.getSourceCode().getTokenAfter(token); + const nextToken = context.getSourceCode().getTokenAfter(token, { includeComments: true }); return fixer.removeRange([token.range[1], nextToken.range[0]]); } @@ -104,7 +104,7 @@ module.exports = { token: token.value }, fix(fixer) { - const previousToken = context.getSourceCode().getTokenBefore(token); + const previousToken = context.getSourceCode().getTokenBefore(token, { includeComments: true }); return fixer.removeRange([previousToken.range[1], token.range[0]]); } @@ -225,8 +225,8 @@ module.exports = { const first = sourceCode.getFirstToken(node), last = getClosingBraceOfObject(node), - second = sourceCode.getTokenAfter(first), - penultimate = sourceCode.getTokenBefore(last); + second = sourceCode.getTokenAfter(first, { includeComments: true }), + penultimate = sourceCode.getTokenBefore(last, { includeComments: true }); validateBraceSpacing(node, first, second, penultimate, last); } @@ -253,8 +253,8 @@ module.exports = { const first = sourceCode.getTokenBefore(firstSpecifier), last = sourceCode.getTokenAfter(lastSpecifier, astUtils.isNotCommaToken), - second = sourceCode.getTokenAfter(first), - penultimate = sourceCode.getTokenBefore(last); + second = sourceCode.getTokenAfter(first, { includeComments: true }), + penultimate = sourceCode.getTokenBefore(last, { includeComments: true }); validateBraceSpacing(node, first, second, penultimate, last); } @@ -273,8 +273,8 @@ module.exports = { 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); + second = sourceCode.getTokenAfter(first, { includeComments: true }), + penultimate = sourceCode.getTokenBefore(last, { includeComments: true }); validateBraceSpacing(node, first, second, penultimate, last); } diff --git a/tools/node_modules/eslint/lib/rules/object-shorthand.js b/tools/node_modules/eslint/lib/rules/object-shorthand.js index 31010f0e7386db..bff7c717a0d0df 100644 --- a/tools/node_modules/eslint/lib/rules/object-shorthand.js +++ b/tools/node_modules/eslint/lib/rules/object-shorthand.js @@ -17,7 +17,7 @@ const OPTIONS = { //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition @@ -113,6 +113,8 @@ module.exports = { // Helpers //-------------------------------------------------------------------------- + const CTOR_PREFIX_REGEX = /[^_$0-9]/u; + /** * Determines if the first character of the name is a capital letter. * @param {string} name The name of the node to evaluate. @@ -120,7 +122,14 @@ module.exports = { * @private */ function isConstructor(name) { - const firstChar = name.charAt(0); + const match = CTOR_PREFIX_REGEX.exec(name); + + // Not a constructor if name has no characters apart from '_', '$' and digits e.g. '_', '$$', '_8' + if (!match) { + return false; + } + + const firstChar = name.charAt(match.index); return firstChar === firstChar.toUpperCase(); } diff --git a/tools/node_modules/eslint/lib/rules/one-var.js b/tools/node_modules/eslint/lib/rules/one-var.js index 0571cd338b72db..e79461ce46c5be 100644 --- a/tools/node_modules/eslint/lib/rules/one-var.js +++ b/tools/node_modules/eslint/lib/rules/one-var.js @@ -32,8 +32,7 @@ module.exports = { type: "object", properties: { separateRequires: { - type: "boolean", - default: false + type: "boolean" }, var: { enum: ["always", "never", "consecutive"] @@ -77,7 +76,7 @@ module.exports = { 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.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 }; diff --git a/tools/node_modules/eslint/lib/rules/operator-assignment.js b/tools/node_modules/eslint/lib/rules/operator-assignment.js index 94e85927344ce1..63982cf39202fa 100644 --- a/tools/node_modules/eslint/lib/rules/operator-assignment.js +++ b/tools/node_modules/eslint/lib/rules/operator-assignment.js @@ -8,7 +8,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Helpers diff --git a/tools/node_modules/eslint/lib/rules/operator-linebreak.js b/tools/node_modules/eslint/lib/rules/operator-linebreak.js index cd6e996b1b10bd..bce0ef56a0cc6c 100644 --- a/tools/node_modules/eslint/lib/rules/operator-linebreak.js +++ b/tools/node_modules/eslint/lib/rules/operator-linebreak.js @@ -9,7 +9,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/padded-blocks.js b/tools/node_modules/eslint/lib/rules/padded-blocks.js index e4dd37f4cdb42e..d5bd5499c6e167 100644 --- a/tools/node_modules/eslint/lib/rules/padded-blocks.js +++ b/tools/node_modules/eslint/lib/rules/padded-blocks.js @@ -9,7 +9,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition 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 index 7d37870a481ee6..d98cb1f247fbb7 100644 --- a/tools/node_modules/eslint/lib/rules/padding-line-between-statements.js +++ b/tools/node_modules/eslint/lib/rules/padding-line-between-statements.js @@ -9,7 +9,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Helpers diff --git a/tools/node_modules/eslint/lib/rules/prefer-const.js b/tools/node_modules/eslint/lib/rules/prefer-const.js index c4180faeb9421c..68c07da4ed99e7 100644 --- a/tools/node_modules/eslint/lib/rules/prefer-const.js +++ b/tools/node_modules/eslint/lib/rules/prefer-const.js @@ -5,7 +5,7 @@ "use strict"; -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Helpers diff --git a/tools/node_modules/eslint/lib/rules/prefer-object-spread.js b/tools/node_modules/eslint/lib/rules/prefer-object-spread.js index c5fca98efeb646..214f950c64212e 100644 --- a/tools/node_modules/eslint/lib/rules/prefer-object-spread.js +++ b/tools/node_modules/eslint/lib/rules/prefer-object-spread.js @@ -12,7 +12,7 @@ const { isOpeningParenToken, isClosingParenToken, isParenthesised -} = require("../util/ast-utils"); +} = require("./utils/ast-utils"); const ANY_SPACE = /\s/u; 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 index 275e705f6d5ca7..e142a96b55c78f 100644 --- a/tools/node_modules/eslint/lib/rules/prefer-promise-reject-errors.js +++ b/tools/node_modules/eslint/lib/rules/prefer-promise-reject-errors.js @@ -4,7 +4,7 @@ */ "use strict"; -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/prefer-spread.js b/tools/node_modules/eslint/lib/rules/prefer-spread.js index 5f3a477329b700..9368c972c086ba 100644 --- a/tools/node_modules/eslint/lib/rules/prefer-spread.js +++ b/tools/node_modules/eslint/lib/rules/prefer-spread.js @@ -5,7 +5,7 @@ "use strict"; -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Helpers diff --git a/tools/node_modules/eslint/lib/rules/prefer-template.js b/tools/node_modules/eslint/lib/rules/prefer-template.js index d8dd5dd86e0292..f73ac34f837034 100644 --- a/tools/node_modules/eslint/lib/rules/prefer-template.js +++ b/tools/node_modules/eslint/lib/rules/prefer-template.js @@ -9,7 +9,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Helpers diff --git a/tools/node_modules/eslint/lib/rules/quote-props.js b/tools/node_modules/eslint/lib/rules/quote-props.js index 7184bd34d35fd1..79493b2499eb31 100644 --- a/tools/node_modules/eslint/lib/rules/quote-props.js +++ b/tools/node_modules/eslint/lib/rules/quote-props.js @@ -9,7 +9,7 @@ //------------------------------------------------------------------------------ const espree = require("espree"), - keywords = require("../util/keywords"); + keywords = require("./utils/keywords"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/quotes.js b/tools/node_modules/eslint/lib/rules/quotes.js index 4556b245d302d4..28b20af29f49fe 100644 --- a/tools/node_modules/eslint/lib/rules/quotes.js +++ b/tools/node_modules/eslint/lib/rules/quotes.js @@ -9,7 +9,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Constants diff --git a/tools/node_modules/eslint/lib/rules/radix.js b/tools/node_modules/eslint/lib/rules/radix.js index 5d3805d0a70679..b7b296f45155ff 100644 --- a/tools/node_modules/eslint/lib/rules/radix.js +++ b/tools/node_modules/eslint/lib/rules/radix.js @@ -9,7 +9,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Helpers diff --git a/tools/node_modules/eslint/lib/rules/require-atomic-updates.js b/tools/node_modules/eslint/lib/rules/require-atomic-updates.js index e8dbe17b88dcd8..09d7670d81984c 100644 --- a/tools/node_modules/eslint/lib/rules/require-atomic-updates.js +++ b/tools/node_modules/eslint/lib/rules/require-atomic-updates.js @@ -1,10 +1,119 @@ /** * @fileoverview disallow assignments that can lead to race conditions due to usage of `await` or `yield` * @author Teddy Katz + * @author Toru Nagashima */ "use strict"; -const astUtils = require("../util/ast-utils"); +/** + * Make the map from identifiers to each reference. + * @param {escope.Scope} scope The scope to get references. + * @param {Map} [outReferenceMap] The map from identifier nodes to each reference object. + * @returns {Map} `referenceMap`. + */ +function createReferenceMap(scope, outReferenceMap = new Map()) { + for (const reference of scope.references) { + outReferenceMap.set(reference.identifier, reference); + } + for (const childScope of scope.childScopes) { + if (childScope.type !== "function") { + createReferenceMap(childScope, outReferenceMap); + } + } + + return outReferenceMap; +} + +/** + * Checks if an expression is a variable that can only be observed within the given function. + * @param {escope.Variable} variable The variable to check + * @returns {boolean} `true` if the variable is local to the given function, and is never referenced in a closure. + */ +function isLocalVariableWithoutEscape(variable) { + const functionScope = variable.scope.variableScope; + + return variable.references.every(reference => + reference.from.variableScope === functionScope); +} + +class SegmentInfo { + constructor() { + this.info = new WeakMap(); + } + + /** + * Initialize the segment information. + * @param {PathSegment} segment The segment to initialize. + * @returns {void} + */ + initialize(segment) { + const outdatedReadVariables = new Set(); + const freshReadVariables = new Set(); + + for (const prevSegment of segment.prevSegments) { + const info = this.info.get(prevSegment); + + if (info) { + info.outdatedReadVariables.forEach(Set.prototype.add, outdatedReadVariables); + info.freshReadVariables.forEach(Set.prototype.add, freshReadVariables); + } + } + + this.info.set(segment, { outdatedReadVariables, freshReadVariables }); + } + + /** + * Mark a given variable as read on given segments. + * @param {PathSegment[]} segments The segments that it read the variable on. + * @param {escope.Variable} variable The variable to be read. + * @returns {void} + */ + markAsRead(segments, variable) { + for (const segment of segments) { + const info = this.info.get(segment); + + if (info) { + info.freshReadVariables.add(variable); + } + } + } + + /** + * Move `freshReadVariables` to `outdatedReadVariables`. + * @param {PathSegment[]} segments The segments to process. + * @returns {void} + */ + makeOutdated(segments) { + const vars = new Set(); + + for (const segment of segments) { + const info = this.info.get(segment); + + if (info) { + info.freshReadVariables.forEach(Set.prototype.add, info.outdatedReadVariables); + info.freshReadVariables.forEach(Set.prototype.add, vars); + info.freshReadVariables.clear(); + } + } + } + + /** + * Check if a given variable is outdated on the current segments. + * @param {PathSegment[]} segments The current segments. + * @param {escope.Variable} variable The variable to check. + * @returns {boolean} `true` if the variable is outdated on the segments. + */ + isOutdated(segments, variable) { + for (const segment of segments) { + const info = this.info.get(segment); + + if (info && info.outdatedReadVariables.has(variable)) { + return true; + } + } + return false; + } +} //------------------------------------------------------------------------------ // Rule Definition @@ -17,7 +126,7 @@ module.exports = { docs: { description: "disallow assignments that can lead to race conditions due to usage of `await` or `yield`", category: "Possible Errors", - recommended: false, + recommended: true, url: "https://eslint.org/docs/rules/require-atomic-updates" }, @@ -31,268 +140,163 @@ module.exports = { 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); - } + const globalScope = context.getScope(); + const dummyVariables = new Map(); + const assignmentReferences = new Map(); + const segmentInfo = new SegmentInfo(); + let stack = null; /** - * 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. + * Get the variable of a given reference. + * If it's not defined, returns a dummy object. + * @param {escope.Reference} reference The reference to get. + * @returns {escope.Variable} The variable of the reference. */ - function isLocalVariableWithoutEscape(expression, surroundingFunction) { - if (expression.type !== "Identifier") { - return false; + function getVariable(reference) { + if (reference.resolved) { + return reference.resolved; } - const variable = resolveVariable(expression); + // Get or create a dummy. + const name = reference.identifier.name; + let variable = dummyVariables.get(name); if (!variable) { - return false; + variable = { + name, + scope: globalScope, + references: [] + }; + dummyVariables.set(name, variable); } + variable.references.push(reference); - return variable.references.every(reference => identifierToSurroundingFunctionMap.get(reference.identifier) === surroundingFunction) && - variable.defs.every(def => identifierToSurroundingFunctionMap.get(def.name) === surroundingFunction); + return variable; } /** - * Reports an AssignmentExpression node that has a non-atomic update - * @param {ASTNode} assignmentExpression The assignment that is potentially unsafe - * @returns {void} + * Get `reference.writeExpr` of a given reference. + * If it's the read reference of MemberExpression in LHS, returns RHS in order to address `a.b = await a` + * @param {escope.Reference} reference The reference to get. + * @returns {Expression|null} The `reference.writeExpr`. */ - 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) - }); + function getWriteExpr(reference) { + if (reference.writeExpr) { + return reference.writeExpr; } + let node = reference.identifier; - merge(other) { - const initialAssignmentsWithoutReadsCount = this.openAssignmentsWithoutReads.size; - const initialAssignmentsWithReadsCount = this.openAssignmentsWithReads.size; + while (node) { + const t = node.parent.type; - 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); - } + if (t === "AssignmentExpression" && node.parent.left === node) { + return node.parent.right; + } + if (t === "MemberExpression" && node.parent.object === node) { + node = node.parent; + continue; + } - exitAwaitOrYield(node, surroundingFunction) { - return [...this.openAssignmentsWithReads] - .filter(assignment => !isLocalVariableWithoutEscape(assignment.left, surroundingFunction)) - .forEach(assignment => { - if (!alreadyReportedAssignments.has(assignment)) { - reportAssignment(assignment); - alreadyReportedAssignments.add(assignment); - } - }); + break; } - 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); - }); - } + return null; } - /** - * 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); - } - }); + return { + onCodePathStart(codePath) { + const scope = context.getScope(); + const shouldVerify = + scope.type === "function" && + (scope.block.async || scope.block.generator); + + stack = { + upper: stack, + codePath, + referenceMap: shouldVerify ? createReferenceMap(scope) : null + }; + }, + onCodePathEnd() { + stack = stack.upper; + }, - stateBySegmentEnd.set(codePathSegment, currentState); + // Initialize the segment information. + onCodePathSegmentStart(segment) { + segmentInfo.initialize(segment); + }, - codePathSegment.nextSegments.forEach(nextSegment => { - if (stateBySegmentStart.has(nextSegment)) { - if (!stateBySegmentStart.get(nextSegment).merge(currentState)) { + // Handle references to prepare verification. + Identifier(node) { + const { codePath, referenceMap } = stack; + const reference = referenceMap && referenceMap.get(node); - /* - * 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()); + // Ignore if this is not a valid variable reference. + if (!reference) { + return; } - findOutdatedReads( - nextSegment, - surroundingFunction, - { stateBySegmentStart, stateBySegmentEnd } - ); - }); - } + const variable = getVariable(reference); + const writeExpr = getWriteExpr(reference); - //---------------------------------------------------------------------- - // Public - //---------------------------------------------------------------------- + // Add a fresh read variable. + if (reference.isRead() && !(writeExpr && writeExpr.parent.operator === "=")) { + segmentInfo.markAsRead(codePath.currentSegments, variable); + } - const currentCodePathSegmentStack = []; - let currentCodePathSegment = null; - const functionStack = []; + /* + * Register the variable to verify after ESLint traversed the `writeExpr` node + * if this reference is an assignment to a variable which is referred from other clausure. + */ + if (writeExpr && + writeExpr.parent.right === writeExpr && // ← exclude variable declarations. + !isLocalVariableWithoutEscape(variable) + ) { + let refs = assignmentReferences.get(writeExpr); + + if (!refs) { + refs = []; + assignmentReferences.set(writeExpr, refs); + } - return { - onCodePathStart() { - currentCodePathSegmentStack.push(currentCodePathSegment); + refs.push(reference); + } }, - onCodePathEnd(codePath, node) { - currentCodePathSegment = currentCodePathSegmentStack.pop(); + /* + * Verify assignments. + * If the reference exists in `outdatedReadVariables` list, report it. + */ + ":expression:exit"(node) { + const { codePath, referenceMap } = stack; - if (astUtils.isFunction(node) && (node.async || node.generator)) { - findOutdatedReads(codePath.initialSegment, node); + // referenceMap exists if this is in a resumable function scope. + if (!referenceMap) { + return; } - }, - - onCodePathSegmentStart(segment) { - currentCodePathSegment = segment; - expressionsByCodePathSegment.set(segment, []); - }, - "AssignmentExpression, Identifier, MemberExpression, AwaitExpression, YieldExpression"(node) { - expressionsByCodePathSegment.get(currentCodePathSegment).push({ entering: true, node }); - }, + // Mark the read variables on this code path as outdated. + if (node.type === "AwaitExpression" || node.type === "YieldExpression") { + segmentInfo.makeOutdated(codePath.currentSegments); + } - "AssignmentExpression, Identifier, MemberExpression, AwaitExpression, YieldExpression:exit"(node) { - expressionsByCodePathSegment.get(currentCodePathSegment).push({ entering: false, node }); - }, + // Verify. + const references = assignmentReferences.get(node); - ":function"(node) { - functionStack.push(node); - }, + if (references) { + assignmentReferences.delete(node); - ":function:exit"() { - functionStack.pop(); - }, + for (const reference of references) { + const variable = getVariable(reference); - Identifier(node) { - if (functionStack.length) { - identifierToSurroundingFunctionMap.set(node, functionStack[functionStack.length - 1]); + if (segmentInfo.isOutdated(codePath.currentSegments, variable)) { + context.report({ + node: node.parent, + messageId: "nonAtomicUpdate", + data: { + value: sourceCode.getText(node.parent.left) + } + }); + } + } } } }; diff --git a/tools/node_modules/eslint/lib/rules/require-await.js b/tools/node_modules/eslint/lib/rules/require-await.js index 5e614c50251fed..298cb951de3b39 100644 --- a/tools/node_modules/eslint/lib/rules/require-await.js +++ b/tools/node_modules/eslint/lib/rules/require-await.js @@ -9,7 +9,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Helpers diff --git a/tools/node_modules/eslint/lib/rules/semi-spacing.js b/tools/node_modules/eslint/lib/rules/semi-spacing.js index 3a6d8a052a343b..083dc26199f7bd 100644 --- a/tools/node_modules/eslint/lib/rules/semi-spacing.js +++ b/tools/node_modules/eslint/lib/rules/semi-spacing.js @@ -5,7 +5,7 @@ "use strict"; -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/semi-style.js b/tools/node_modules/eslint/lib/rules/semi-style.js index dd76b68f82beac..da3c4a38742b88 100644 --- a/tools/node_modules/eslint/lib/rules/semi-style.js +++ b/tools/node_modules/eslint/lib/rules/semi-style.js @@ -9,7 +9,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/semi.js b/tools/node_modules/eslint/lib/rules/semi.js index 3a6df39c771ee5..a159e19d347dcf 100644 --- a/tools/node_modules/eslint/lib/rules/semi.js +++ b/tools/node_modules/eslint/lib/rules/semi.js @@ -8,8 +8,8 @@ // Requirements //------------------------------------------------------------------------------ -const FixTracker = require("../util/fix-tracker"); -const astUtils = require("../util/ast-utils"); +const FixTracker = require("./utils/fix-tracker"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/sort-keys.js b/tools/node_modules/eslint/lib/rules/sort-keys.js index fd5dd8a13bce84..23a39108181c99 100644 --- a/tools/node_modules/eslint/lib/rules/sort-keys.js +++ b/tools/node_modules/eslint/lib/rules/sort-keys.js @@ -9,7 +9,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"), +const astUtils = require("./utils/ast-utils"), naturalCompare = require("natural-compare"); //------------------------------------------------------------------------------ diff --git a/tools/node_modules/eslint/lib/rules/space-before-blocks.js b/tools/node_modules/eslint/lib/rules/space-before-blocks.js index 872338effc29b3..527366aaccf089 100644 --- a/tools/node_modules/eslint/lib/rules/space-before-blocks.js +++ b/tools/node_modules/eslint/lib/rules/space-before-blocks.js @@ -5,7 +5,7 @@ "use strict"; -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition 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 index 64ba72bf9ead29..ca20dbc4abf94a 100644 --- a/tools/node_modules/eslint/lib/rules/space-before-function-paren.js +++ b/tools/node_modules/eslint/lib/rules/space-before-function-paren.js @@ -8,7 +8,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/space-in-parens.js b/tools/node_modules/eslint/lib/rules/space-in-parens.js index 3068662632172e..4f97b1aa896f5a 100644 --- a/tools/node_modules/eslint/lib/rules/space-in-parens.js +++ b/tools/node_modules/eslint/lib/rules/space-in-parens.js @@ -4,7 +4,7 @@ */ "use strict"; -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/space-unary-ops.js b/tools/node_modules/eslint/lib/rules/space-unary-ops.js index 779697b5b39b08..f417eea58d8eb6 100644 --- a/tools/node_modules/eslint/lib/rules/space-unary-ops.js +++ b/tools/node_modules/eslint/lib/rules/space-unary-ops.js @@ -8,7 +8,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/spaced-comment.js b/tools/node_modules/eslint/lib/rules/spaced-comment.js index 6e469ef9403a8d..731bd212e3e786 100644 --- a/tools/node_modules/eslint/lib/rules/spaced-comment.js +++ b/tools/node_modules/eslint/lib/rules/spaced-comment.js @@ -5,7 +5,7 @@ "use strict"; const lodash = require("lodash"); -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Helpers @@ -126,7 +126,7 @@ function createAlwaysStylePattern(markers, exceptions) { pattern += "?"; // or nothing. pattern += createExceptionsPattern(exceptions); - return new RegExp(pattern); // eslint-disable-line require-unicode-regexp + return new RegExp(pattern, "u"); } /** @@ -142,7 +142,7 @@ function createAlwaysStylePattern(markers, exceptions) { function createNeverStylePattern(markers) { const pattern = `^(${markers.map(escape).join("|")})?[ \t]+`; - return new RegExp(pattern); // eslint-disable-line require-unicode-regexp + return new RegExp(pattern, "u"); } //------------------------------------------------------------------------------ @@ -250,9 +250,9 @@ module.exports = { // 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), // eslint-disable-line require-unicode-regexp + endRegex: balanced && requireSpace ? new RegExp(`${createExceptionsPattern(exceptions)}$`, "u") : new RegExp(endNeverPattern, "u"), hasExceptions: exceptions.length > 0, - markers: new RegExp(`^(${markers.map(escape).join("|")})`) // eslint-disable-line require-unicode-regexp + markers: new RegExp(`^(${markers.map(escape).join("|")})`, "u") }; return rule; diff --git a/tools/node_modules/eslint/lib/rules/strict.js b/tools/node_modules/eslint/lib/rules/strict.js index a826731260b376..b93a6a1a17adb5 100644 --- a/tools/node_modules/eslint/lib/rules/strict.js +++ b/tools/node_modules/eslint/lib/rules/strict.js @@ -9,7 +9,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Helpers diff --git a/tools/node_modules/eslint/lib/rules/switch-colon-spacing.js b/tools/node_modules/eslint/lib/rules/switch-colon-spacing.js index 40154862d19215..c90641573c6010 100644 --- a/tools/node_modules/eslint/lib/rules/switch-colon-spacing.js +++ b/tools/node_modules/eslint/lib/rules/switch-colon-spacing.js @@ -9,7 +9,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/symbol-description.js b/tools/node_modules/eslint/lib/rules/symbol-description.js index f2e7e16b7a5874..3fd5a359671f6a 100644 --- a/tools/node_modules/eslint/lib/rules/symbol-description.js +++ b/tools/node_modules/eslint/lib/rules/symbol-description.js @@ -9,7 +9,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/template-curly-spacing.js b/tools/node_modules/eslint/lib/rules/template-curly-spacing.js index e255a890ec4793..2794b45cf78548 100644 --- a/tools/node_modules/eslint/lib/rules/template-curly-spacing.js +++ b/tools/node_modules/eslint/lib/rules/template-curly-spacing.js @@ -9,7 +9,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Helpers diff --git a/tools/node_modules/eslint/lib/util/ast-utils.js b/tools/node_modules/eslint/lib/rules/utils/ast-utils.js similarity index 97% rename from tools/node_modules/eslint/lib/util/ast-utils.js rename to tools/node_modules/eslint/lib/rules/utils/ast-utils.js index 85205a75d2490c..1aef4c162d40de 100644 --- a/tools/node_modules/eslint/lib/util/ast-utils.js +++ b/tools/node_modules/eslint/lib/rules/utils/ast-utils.js @@ -11,6 +11,13 @@ const esutils = require("esutils"); const espree = require("espree"); +const lodash = require("lodash"); +const { + breakableTypePattern, + createGlobalLinebreakMatcher, + lineBreakPattern, + shebangPattern +} = require("../../shared/ast-utils"); //------------------------------------------------------------------------------ // Helpers @@ -21,14 +28,11 @@ const anyLoopPattern = /^(?:DoWhile|For|ForIn|ForOf|While)Statement$/u; const arrayOrTypedArrayPattern = /Array$/u; const arrayMethodPattern = /^(?:every|filter|find|findIndex|forEach|map|some)$/u; const bindOrCallOrApplyPattern = /^(?:bind|call|apply)$/u; -const breakableTypePattern = /^(?:(?:Do)?While|For(?:In|Of)?|Switch)Statement$/u; const thisTagPattern = /^[\s*]*@this/mu; const COMMENTS_IGNORE_PATTERN = /^\s*(?:eslint|jshint\s+|jslint\s+|istanbul\s+|globals?\s+|exported\s+|jscs)/u; const LINEBREAKS = new Set(["\r\n", "\r", "\n", "\u2028", "\u2029"]); -const LINEBREAK_MATCHER = /\r\n|[\r\n\u2028\u2029]/u; -const SHEBANG_MATCHER = /^#!([^\r\n]+)/u; // A set of node types that can contain a list of statements const STATEMENT_LIST_PARENTS = new Set(["Program", "BlockStatement", "SwitchCase"]); @@ -392,15 +396,6 @@ function getOpeningParenOfParams(node, sourceCode) { : 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, "gu"); -} - /** * Checks whether or not the tokens of two given nodes are same. * @param {ASTNode} left - A node 1 to compare. @@ -433,8 +428,8 @@ function equalTokens(left, right, sourceCode) { module.exports = { COMMENTS_IGNORE_PATTERN, LINEBREAKS, - LINEBREAK_MATCHER, - SHEBANG_MATCHER, + LINEBREAK_MATCHER: lineBreakPattern, + SHEBANG_MATCHER: shebangPattern, STATEMENT_LIST_PARENTS, /** @@ -512,19 +507,6 @@ module.exports = { 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. @@ -1342,5 +1324,29 @@ module.exports = { } return false; + }, + + /** + * Get the `loc` object of a given name in a `/*globals` directive comment. + * @param {SourceCode} sourceCode The source code to convert index to loc. + * @param {Comment} comment The `/*globals` directive comment which include the name. + * @param {string} name The name to find. + * @returns {SourceLocation} The `loc` object. + */ + getNameLocationInGlobalDirectiveComment(sourceCode, comment, name) { + const namePattern = new RegExp(`[\\s,]${lodash.escapeRegExp(name)}(?:$|[\\s,:])`, "gu"); + + // To ignore the first text "global". + namePattern.lastIndex = comment.value.indexOf("global") + 6; + + // Search a given variable name. + const match = namePattern.exec(comment.value); + + // Convert the index to loc. + return sourceCode.getLocFromIndex( + comment.range[0] + + "/*".length + + (match ? match.index + 1 : 0) + ); } }; diff --git a/tools/node_modules/eslint/lib/util/fix-tracker.js b/tools/node_modules/eslint/lib/rules/utils/fix-tracker.js similarity index 98% rename from tools/node_modules/eslint/lib/util/fix-tracker.js rename to tools/node_modules/eslint/lib/rules/utils/fix-tracker.js index 3c9bf63d257b99..c987a28ca6cb49 100644 --- a/tools/node_modules/eslint/lib/util/fix-tracker.js +++ b/tools/node_modules/eslint/lib/rules/utils/fix-tracker.js @@ -8,7 +8,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./ast-utils"); //------------------------------------------------------------------------------ // Public Interface diff --git a/tools/node_modules/eslint/lib/util/keywords.js b/tools/node_modules/eslint/lib/rules/utils/keywords.js similarity index 100% rename from tools/node_modules/eslint/lib/util/keywords.js rename to tools/node_modules/eslint/lib/rules/utils/keywords.js diff --git a/tools/node_modules/eslint/lib/rules/utils/lazy-loading-rule-map.js b/tools/node_modules/eslint/lib/rules/utils/lazy-loading-rule-map.js new file mode 100644 index 00000000000000..e0caddb9b2821c --- /dev/null +++ b/tools/node_modules/eslint/lib/rules/utils/lazy-loading-rule-map.js @@ -0,0 +1,116 @@ +/** + * @fileoverview `Map` to load rules lazily. + * @author Toru Nagashima + */ +"use strict"; + +const debug = require("debug")("eslint:rules"); + +/** @typedef {import("./types").Rule} Rule */ + +/** + * The `Map` object that loads each rule when it's accessed. + * + * @example + * const rules = new LazyLoadingRuleMap([ + * ["eqeqeq", () => require("eqeqeq")], + * ["semi", () => require("semi")], + * ["no-unused-vars", () => require("no-unused-vars")], + * ]) + * + * rules.get("semi") // call `() => require("semi")` here. + * + * @extends {Map Rule>} + */ +class LazyLoadingRuleMap extends Map { + + /** + * Initialize this map. + * @param {Array<[string, function(): Rule]>} loaders The rule loaders. + */ + constructor(loaders) { + let remaining = loaders.length; + + super( + debug.enabled + ? loaders.map(([ruleId, load]) => { + let cache = null; + + return [ + ruleId, + () => { + if (!cache) { + debug("Loading rule %o (remaining=%d)", ruleId, --remaining); + cache = load(); + } + return cache; + } + ]; + }) + : loaders + ); + + // `super(...iterable)` uses `this.set()`, so disable it here. + Object.defineProperty(LazyLoadingRuleMap.prototype, "set", { + configurable: true, + value: void 0 + }); + } + + /** + * Get a rule. + * Each rule will be loaded on the first access. + * @param {string} ruleId The rule ID to get. + * @returns {Rule|undefined} The rule. + */ + get(ruleId) { + const load = super.get(ruleId); + + return load && load(); + } + + /** + * Iterate rules. + * @returns {IterableIterator} Rules. + */ + *values() { + for (const load of super.values()) { + yield load(); + } + } + + /** + * Iterate rules. + * @returns {IterableIterator<[string, Rule]>} Rules. + */ + *entries() { + for (const [ruleId, load] of super.entries()) { + yield [ruleId, load()]; + } + } + + /** + * Call a function with each rule. + * @param {Function} callbackFn The callback function. + * @param {any} [thisArg] The object to pass to `this` of the callback function. + * @returns {void} + */ + forEach(callbackFn, thisArg) { + for (const [ruleId, load] of super.entries()) { + callbackFn.call(thisArg, load(), ruleId, this); + } + } +} + +// Forbid mutation. +Object.defineProperties(LazyLoadingRuleMap.prototype, { + clear: { configurable: true, value: void 0 }, + delete: { configurable: true, value: void 0 }, + [Symbol.iterator]: { + configurable: true, + writable: true, + value: LazyLoadingRuleMap.prototype.entries + } +}); + +module.exports = { LazyLoadingRuleMap }; diff --git a/tools/node_modules/eslint/lib/util/patterns/letters.js b/tools/node_modules/eslint/lib/rules/utils/patterns/letters.js similarity index 100% rename from tools/node_modules/eslint/lib/util/patterns/letters.js rename to tools/node_modules/eslint/lib/rules/utils/patterns/letters.js diff --git a/tools/node_modules/eslint/lib/util/unicode/index.js b/tools/node_modules/eslint/lib/rules/utils/unicode/index.js similarity index 100% rename from tools/node_modules/eslint/lib/util/unicode/index.js rename to tools/node_modules/eslint/lib/rules/utils/unicode/index.js diff --git a/tools/node_modules/eslint/lib/util/unicode/is-combining-character.js b/tools/node_modules/eslint/lib/rules/utils/unicode/is-combining-character.js similarity index 100% rename from tools/node_modules/eslint/lib/util/unicode/is-combining-character.js rename to tools/node_modules/eslint/lib/rules/utils/unicode/is-combining-character.js diff --git a/tools/node_modules/eslint/lib/util/unicode/is-emoji-modifier.js b/tools/node_modules/eslint/lib/rules/utils/unicode/is-emoji-modifier.js similarity index 100% rename from tools/node_modules/eslint/lib/util/unicode/is-emoji-modifier.js rename to tools/node_modules/eslint/lib/rules/utils/unicode/is-emoji-modifier.js diff --git a/tools/node_modules/eslint/lib/util/unicode/is-regional-indicator-symbol.js b/tools/node_modules/eslint/lib/rules/utils/unicode/is-regional-indicator-symbol.js similarity index 100% rename from tools/node_modules/eslint/lib/util/unicode/is-regional-indicator-symbol.js rename to tools/node_modules/eslint/lib/rules/utils/unicode/is-regional-indicator-symbol.js diff --git a/tools/node_modules/eslint/lib/util/unicode/is-surrogate-pair.js b/tools/node_modules/eslint/lib/rules/utils/unicode/is-surrogate-pair.js similarity index 100% rename from tools/node_modules/eslint/lib/util/unicode/is-surrogate-pair.js rename to tools/node_modules/eslint/lib/rules/utils/unicode/is-surrogate-pair.js diff --git a/tools/node_modules/eslint/lib/rules/valid-jsdoc.js b/tools/node_modules/eslint/lib/rules/valid-jsdoc.js index 3250d9233c7187..9ec6938e35af7d 100644 --- a/tools/node_modules/eslint/lib/rules/valid-jsdoc.js +++ b/tools/node_modules/eslint/lib/rules/valid-jsdoc.js @@ -482,7 +482,7 @@ module.exports = { } if (options.matchDescription) { - const regex = new RegExp(options.matchDescription); // eslint-disable-line require-unicode-regexp + const regex = new RegExp(options.matchDescription, "u"); if (!regex.test(jsdoc.description)) { context.report({ node: jsdocNode, messageId: "unsatisfiedDesc" }); diff --git a/tools/node_modules/eslint/lib/rules/wrap-iife.js b/tools/node_modules/eslint/lib/rules/wrap-iife.js index 0e54157f102f7d..5e590be13e28b5 100644 --- a/tools/node_modules/eslint/lib/rules/wrap-iife.js +++ b/tools/node_modules/eslint/lib/rules/wrap-iife.js @@ -9,7 +9,7 @@ // Requirements //------------------------------------------------------------------------------ -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Rule Definition diff --git a/tools/node_modules/eslint/lib/rules/yoda.js b/tools/node_modules/eslint/lib/rules/yoda.js index 048c670a6459d0..43783c193bd5dd 100644 --- a/tools/node_modules/eslint/lib/rules/yoda.js +++ b/tools/node_modules/eslint/lib/rules/yoda.js @@ -8,7 +8,7 @@ // Requirements //-------------------------------------------------------------------------- -const astUtils = require("../util/ast-utils"); +const astUtils = require("./utils/ast-utils"); //-------------------------------------------------------------------------- // Helpers diff --git a/tools/node_modules/eslint/lib/util/ajv.js b/tools/node_modules/eslint/lib/shared/ajv.js similarity index 57% rename from tools/node_modules/eslint/lib/util/ajv.js rename to tools/node_modules/eslint/lib/shared/ajv.js index ecf0ebd172cd51..3fb0fbdd33c146 100644 --- a/tools/node_modules/eslint/lib/util/ajv.js +++ b/tools/node_modules/eslint/lib/shared/ajv.js @@ -15,17 +15,20 @@ const Ajv = require("ajv"), // Public Interface //------------------------------------------------------------------------------ -const ajv = new Ajv({ - meta: false, - useDefaults: true, - validateSchema: false, - missingRefs: "ignore", - verbose: true, - schemaId: "auto" -}); +module.exports = (additionalOptions = {}) => { + const ajv = new Ajv({ + meta: false, + useDefaults: true, + validateSchema: false, + missingRefs: "ignore", + verbose: true, + schemaId: "auto", + ...additionalOptions + }); -ajv.addMetaSchema(metaSchema); -// eslint-disable-next-line no-underscore-dangle -ajv._opts.defaultMeta = metaSchema.id; + ajv.addMetaSchema(metaSchema); + // eslint-disable-next-line no-underscore-dangle + ajv._opts.defaultMeta = metaSchema.id; -module.exports = ajv; + return ajv; +}; diff --git a/tools/node_modules/eslint/lib/shared/ast-utils.js b/tools/node_modules/eslint/lib/shared/ast-utils.js new file mode 100644 index 00000000000000..4ebd49c3ce6a6b --- /dev/null +++ b/tools/node_modules/eslint/lib/shared/ast-utils.js @@ -0,0 +1,29 @@ +/** + * @fileoverview Common utils for AST. + * + * This file contains only shared items for core and rules. + * If you make a utility for rules, please see `../rules/utils/ast-utils.js`. + * + * @author Toru Nagashima + */ +"use strict"; + +const breakableTypePattern = /^(?:(?:Do)?While|For(?:In|Of)?|Switch)Statement$/u; +const lineBreakPattern = /\r\n|[\r\n\u2028\u2029]/u; +const shebangPattern = /^#!([^\r\n]+)/u; + +/** + * Creates a version of the `lineBreakPattern` 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(lineBreakPattern.source, "gu"); +} + +module.exports = { + breakableTypePattern, + lineBreakPattern, + createGlobalLinebreakMatcher, + shebangPattern +}; diff --git a/tools/node_modules/eslint/lib/shared/config-ops.js b/tools/node_modules/eslint/lib/shared/config-ops.js new file mode 100644 index 00000000000000..d2ffda4b5ffe8a --- /dev/null +++ b/tools/node_modules/eslint/lib/shared/config-ops.js @@ -0,0 +1,130 @@ +/** + * @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"; + +//------------------------------------------------------------------------------ +// 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 = { + + /** + * 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])); + }, + + /** + * 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 + * @throws Error if global value is invalid + */ + normalizeConfigGlobal(configuredValue) { + switch (configuredValue) { + case "off": + return "off"; + + case true: + case "true": + case "writeable": + case "writable": + return "writable"; + + case null: + case false: + case "false": + case "readable": + case "readonly": + return "readonly"; + + default: + throw new Error(`'${configuredValue}' is not a valid configuration for a global (use 'readonly', 'writable', or 'off')`); + } + } +}; diff --git a/tools/node_modules/eslint/lib/config/config-validator.js b/tools/node_modules/eslint/lib/shared/config-validator.js similarity index 67% rename from tools/node_modules/eslint/lib/config/config-validator.js rename to tools/node_modules/eslint/lib/shared/config-validator.js index 386db77750238d..aca6e1fb274fdb 100644 --- a/tools/node_modules/eslint/lib/config/config-validator.js +++ b/tools/node_modules/eslint/lib/shared/config-validator.js @@ -9,13 +9,18 @@ // Requirements //------------------------------------------------------------------------------ -const path = require("path"), - ajv = require("../util/ajv"), +const + path = require("path"), + util = require("util"), lodash = require("lodash"), - configSchema = require("../../conf/config-schema.js"), - util = require("util"); + configSchema = require("../../conf/config-schema"), + BuiltInEnvironments = require("../../conf/environments"), + BuiltInRules = require("../rules"), + ConfigOps = require("./config-ops"); +const ajv = require("./ajv")(); const ruleValidators = new WeakMap(); +const noop = Function.prototype; //------------------------------------------------------------------------------ // Private @@ -24,8 +29,7 @@ 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." + ESLINT_LEGACY_ECMAFEATURES: "The 'ecmaFeatures' config file property is deprecated, and has no effect." }; const severityMap = { error: 2, @@ -39,6 +43,10 @@ const severityMap = { * @returns {Object} JSON Schema for the rule's options. */ function getRuleOptionsSchema(rule) { + if (!rule) { + return null; + } + const schema = rule.schema || rule.meta && rule.meta.schema; // Given a tuple of schemas, insert warning level at the beginning @@ -117,9 +125,6 @@ function validateRuleSchema(rule, localOptions) { * @returns {void} */ function validateRuleOptions(rule, ruleId, options, source = null) { - if (!rule) { - return; - } try { const severity = validateRuleSeverity(options); @@ -140,20 +145,26 @@ function validateRuleOptions(rule, ruleId, options, source = null) { /** * Validates an environment object * @param {Object} environment The environment config object to validate. - * @param {Environments} envContext Env context * @param {string} source The name of the configuration source to report in any errors. + * @param {function(envId:string): Object} [getAdditionalEnv] A map from strings to loaded environments. * @returns {void} */ -function validateEnvironment(environment, envContext, source = null) { +function validateEnvironment( + environment, + source, + getAdditionalEnv = noop +) { // 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`; + Object.keys(environment).forEach(id => { + const env = getAdditionalEnv(id) || BuiltInEnvironments.get(id) || null; + + if (!env) { + const message = `${source}:\n\tEnvironment key "${id}" is unknown\n`; throw new Error(message); } @@ -163,20 +174,60 @@ function validateEnvironment(environment, envContext, source = null) { /** * Validates a rules config object * @param {Object} rulesConfig The rules config object to validate. - * @param {function(string): {create: Function}} ruleMapper A mapper function from strings to loaded rules * @param {string} source The name of the configuration source to report in any errors. + * @param {function(ruleId:string): Object} getAdditionalRule A map from strings to loaded rules * @returns {void} */ -function validateRules(rulesConfig, ruleMapper, source = null) { +function validateRules( + rulesConfig, + source, + getAdditionalRule = noop +) { if (!rulesConfig) { return; } Object.keys(rulesConfig).forEach(id => { - validateRuleOptions(ruleMapper(id), id, rulesConfig[id], source); + const rule = getAdditionalRule(id) || BuiltInRules.get(id) || null; + + validateRuleOptions(rule, id, rulesConfig[id], source); }); } +/** + * Validates a `globals` section of a config file + * @param {Object} globalsConfig The `glboals` section + * @param {string|null} source The name of the configuration source to report in the event of an error. + * @returns {void} + */ +function validateGlobals(globalsConfig, source = null) { + if (!globalsConfig) { + return; + } + + Object.entries(globalsConfig) + .forEach(([configuredGlobal, configuredValue]) => { + try { + ConfigOps.normalizeConfigGlobal(configuredValue); + } catch (err) { + throw new Error(`ESLint configuration of global '${configuredGlobal}' in ${source} is invalid:\n${err.message}`); + } + }); +} + +/** + * Validate `processor` configuration. + * @param {string|undefined} processorName The processor name. + * @param {string} source The name of config file. + * @param {function(id:string): Processor} getProcessor The getter of defined processors. + * @returns {void} + */ +function validateProcessor(processorName, source, getProcessor) { + if (processorName && !getProcessor(processorName)) { + throw new Error(`ESLint configuration of processor in '${source}' is invalid: '${processorName}' was not found.`); + } +} + /** * Formats an array of schema validation errors. * @param {Array} errors An array of error messages to format. @@ -238,33 +289,52 @@ function validateConfigSchema(config, source = null) { 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 {function(string): {create: Function}} ruleMapper A mapper function from rule IDs to defined rules - * @param {Environments} envContext The env context * @param {string} source The name of the configuration source to report in any errors. + * @param {function(ruleId:string): Object} [getAdditionalRule] A map from strings to loaded rules. + * @param {function(envId:string): Object} [getAdditionalEnv] A map from strings to loaded envs. * @returns {void} */ -function validate(config, ruleMapper, envContext, source = null) { +function validate(config, source, getAdditionalRule, getAdditionalEnv) { validateConfigSchema(config, source); - validateRules(config.rules, ruleMapper, source); - validateEnvironment(config.env, envContext, source); + validateRules(config.rules, source, getAdditionalRule); + validateEnvironment(config.env, source, getAdditionalEnv); + validateGlobals(config.globals, source); for (const override of config.overrides || []) { - validateRules(override.rules, ruleMapper, source); - validateEnvironment(override.env, envContext, source); + validateRules(override.rules, source, getAdditionalRule); + validateEnvironment(override.env, source, getAdditionalEnv); + validateGlobals(config.globals, source); + } +} + +const validated = new WeakSet(); + +/** + * Validate config array object. + * @param {ConfigArray} configArray The config array to validate. + * @returns {void} + */ +function validateConfigArray(configArray) { + const getPluginEnv = Map.prototype.get.bind(configArray.pluginEnvironments); + const getPluginProcessor = Map.prototype.get.bind(configArray.pluginProcessors); + const getPluginRule = Map.prototype.get.bind(configArray.pluginRules); + + // Validate. + for (const element of configArray) { + if (validated.has(element)) { + continue; + } + validated.add(element); + + validateEnvironment(element.env, element.name, getPluginEnv); + validateGlobals(element.globals, element.name); + validateProcessor(element.processor, element.name, getPluginProcessor); + validateRules(element.rules, element.name, getPluginRule); } } @@ -275,5 +345,7 @@ function validate(config, ruleMapper, envContext, source = null) { module.exports = { getRuleOptionsSchema, validate, + validateConfigArray, + validateConfigSchema, validateRuleOptions }; diff --git a/tools/node_modules/eslint/lib/util/logging.js b/tools/node_modules/eslint/lib/shared/logging.js similarity index 100% rename from tools/node_modules/eslint/lib/util/logging.js rename to tools/node_modules/eslint/lib/shared/logging.js diff --git a/tools/node_modules/eslint/lib/shared/relative-module-resolver.js b/tools/node_modules/eslint/lib/shared/relative-module-resolver.js new file mode 100644 index 00000000000000..5b25fa111214ed --- /dev/null +++ b/tools/node_modules/eslint/lib/shared/relative-module-resolver.js @@ -0,0 +1,58 @@ +/** + * Utility for resolving a module relative to another module + * @author Teddy Katz + */ + +"use strict"; + +const Module = require("module"); +const path = require("path"); + +// Polyfill Node's `Module.createRequire` if not present. We only support the case where the argument is a filepath, not a URL. +const createRequire = ( + + // Added in v12.2.0 + Module.createRequire || + + // Added in v10.12.0, but deprecated in v12.2.0. + Module.createRequireFromPath || + + // Polyfill - This is not executed on the tests on node@>=10. + /* istanbul ignore next */ + (filename => { + const mod = new Module(filename, null); + + mod.filename = filename; + mod.paths = Module._nodeModulePaths(path.dirname(filename)); // eslint-disable-line no-underscore-dangle + mod._compile("module.exports = require;", filename); // eslint-disable-line no-underscore-dangle + return mod.exports; + }) +); + +module.exports = { + + /** + * Resolves a Node module relative to another module + * @param {string} moduleName The name of a Node module, or a path to a Node module. + * + * @param {string} relativeToPath An absolute path indicating the module that `moduleName` should be resolved relative to. This must be + * a file rather than a directory, but the file need not actually exist. + * @returns {string} The absolute path that would result from calling `require.resolve(moduleName)` in a file located at `relativeToPath` + */ + resolve(moduleName, relativeToPath) { + try { + return createRequire(relativeToPath).resolve(moduleName); + } catch (error) { + if ( + typeof error === "object" && + error !== null && + error.code === "MODULE_NOT_FOUND" && + !error.requireStack && + error.message.includes(moduleName) + ) { + error.message += `\nRequire stack:\n- ${relativeToPath}`; + } + throw error; + } + } +}; diff --git a/tools/node_modules/eslint/lib/util/traverser.js b/tools/node_modules/eslint/lib/shared/traverser.js similarity index 100% rename from tools/node_modules/eslint/lib/util/traverser.js rename to tools/node_modules/eslint/lib/shared/traverser.js diff --git a/tools/node_modules/eslint/lib/shared/types.js b/tools/node_modules/eslint/lib/shared/types.js new file mode 100644 index 00000000000000..d8357799944827 --- /dev/null +++ b/tools/node_modules/eslint/lib/shared/types.js @@ -0,0 +1,130 @@ +/** + * @fileoverview Define common types for input completion. + * @author Toru Nagashima + */ +"use strict"; + +/** @type {any} */ +module.exports = {}; + +/** @typedef {boolean | "off" | "readable" | "readonly" | "writable" | "writeable"} GlobalConf */ +/** @typedef {0 | 1 | 2 | "off" | "warn" | "error"} SeverityConf */ +/** @typedef {SeverityConf | [SeverityConf, ...any[]]} RuleConf */ + +/** + * @typedef {Object} EcmaFeatures + * @property {boolean} [globalReturn] Enabling `return` statements at the top-level. + * @property {boolean} [jsx] Enabling JSX syntax. + * @property {boolean} [impliedStrict] Enabling strict mode always. + */ + +/** + * @typedef {Object} ParserOptions + * @property {EcmaFeatures} [ecmaFeatures] The optional features. + * @property {3|5|6|7|8|9|10|2015|2016|2017|2018|2019} [ecmaVersion] The ECMAScript version (or revision number). + * @property {"script"|"module"} [sourceType] The source code type. + */ + +/** + * @typedef {Object} ConfigData + * @property {Record} [env] The environment settings. + * @property {string | string[]} [extends] The path to other config files or the package name of shareable configs. + * @property {Record} [globals] The global variable settings. + * @property {OverrideConfigData[]} [overrides] The override settings per kind of files. + * @property {string} [parser] The path to a parser or the package name of a parser. + * @property {ParserOptions} [parserOptions] The parser options. + * @property {string[]} [plugins] The plugin specifiers. + * @property {string} [processor] The processor specifier. + * @property {boolean} [root] The root flag. + * @property {Record} [rules] The rule settings. + * @property {Object} [settings] The shared settings. + */ + +/** + * @typedef {Object} OverrideConfigData + * @property {Record} [env] The environment settings. + * @property {string | string[]} [excludedFiles] The glob pattarns for excluded files. + * @property {string | string[]} [extends] The path to other config files or the package name of shareable configs. + * @property {string | string[]} files The glob pattarns for target files. + * @property {Record} [globals] The global variable settings. + * @property {OverrideConfigData[]} [overrides] The override settings per kind of files. + * @property {string} [parser] The path to a parser or the package name of a parser. + * @property {ParserOptions} [parserOptions] The parser options. + * @property {string[]} [plugins] The plugin specifiers. + * @property {string} [processor] The processor specifier. + * @property {Record} [rules] The rule settings. + * @property {Object} [settings] The shared settings. + */ + +/** + * @typedef {Object} ParseResult + * @property {Object} ast The AST. + * @property {ScopeManager} [scopeManager] The scope manager of the AST. + * @property {Record} [services] The services that the parser provides. + * @property {Record} [visitorKeys] The visitor keys of the AST. + */ + +/** + * @typedef {Object} Parser + * @property {(text:string, options:ParserOptions) => Object} parse The definition of global variables. + * @property {(text:string, options:ParserOptions) => ParseResult} [parseForESLint] The parser options that will be enabled under this environment. + */ + +/** + * @typedef {Object} Environment + * @property {Record} [globals] The definition of global variables. + * @property {ParserOptions} [parserOptions] The parser options that will be enabled under this environment. + */ + +/** + * @typedef {Object} LintMessage + * @property {number} column The 1-based column number. + * @property {number} [endColumn] The 1-based column number of the end location. + * @property {number} [endLine] The 1-based line number of the end location. + * @property {boolean} fatal If `true` then this is a fatal error. + * @property {{range:[number,number], text:string}} [fix] Information for autofix. + * @property {number} line The 1-based line number. + * @property {string} message The error message. + * @property {string|null} ruleId The ID of the rule which makes this message. + * @property {0|1|2} severity The severity of this message. + */ + +/** + * @typedef {Object} Processor + * @property {(text:string, filename:string) => Array} [preprocess] The function to extract code blocks. + * @property {(messagesList:LintMessage[][], filename:string) => LintMessage[]} [postprocess] The function to merge messages. + * @property {boolean} [supportsAutofix] If `true` then it means the processor supports autofix. + */ + +/** + * @typedef {Object} RuleMetaDocs + * @property {string} category The category of the rule. + * @property {string} description The description of the rule. + * @property {boolean} recommended If `true` then the rule is included in `eslint:recommended` preset. + * @property {string} url The URL of the rule documentation. + */ + +/** + * @typedef {Object} RuleMeta + * @property {boolean} [deprecated] If `true` then the rule has been deprecated. + * @property {RuleMetaDocs} docs The document information of the rule. + * @property {"code"|"whitespace"} [fixable] The autofix type. + * @property {Record} [messages] The messages the rule reports. + * @property {string[]} [replacedBy] The IDs of the alternative rules. + * @property {Array|Object} schema The option schema of the rule. + * @property {"problem"|"suggestion"|"layout"} type The rule type. + */ + +/** + * @typedef {Object} Rule + * @property {Function} create The factory of the rule. + * @property {RuleMeta} meta The meta data of the rule. + */ + +/** + * @typedef {Object} Plugin + * @property {Record} [configs] The definition of plugin configs. + * @property {Record} [environments] The definition of plugin environments. + * @property {Record} [processors] The definition of plugin processors. + * @property {Record} [rules] The definition of plugin rules. + */ diff --git a/tools/node_modules/eslint/lib/source-code/index.js b/tools/node_modules/eslint/lib/source-code/index.js new file mode 100644 index 00000000000000..76e27869f321ac --- /dev/null +++ b/tools/node_modules/eslint/lib/source-code/index.js @@ -0,0 +1,5 @@ +"use strict"; + +module.exports = { + SourceCode: require("./source-code") +}; diff --git a/tools/node_modules/eslint/lib/util/source-code.js b/tools/node_modules/eslint/lib/source-code/source-code.js similarity index 97% rename from tools/node_modules/eslint/lib/util/source-code.js rename to tools/node_modules/eslint/lib/source-code/source-code.js index 93b05a87d23761..88a9c0a4e431c8 100644 --- a/tools/node_modules/eslint/lib/util/source-code.js +++ b/tools/node_modules/eslint/lib/source-code/source-code.js @@ -8,9 +8,11 @@ // Requirements //------------------------------------------------------------------------------ -const TokenStore = require("../token-store"), - Traverser = require("./traverser"), - astUtils = require("../util/ast-utils"), +const + { isCommentToken } = require("eslint-utils"), + TokenStore = require("./token-store"), + astUtils = require("../shared/ast-utils"), + Traverser = require("../shared/traverser"), lodash = require("lodash"); //------------------------------------------------------------------------------ @@ -149,7 +151,7 @@ class SourceCode extends TokenStore { 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 shebangMatched = this.text.match(astUtils.shebangPattern); const hasShebang = shebangMatched && ast.comments.length && ast.comments[0].value === shebangMatched[1]; if (hasShebang) { @@ -274,7 +276,7 @@ class SourceCode extends TokenStore { ) { comments.trailing = this.getTokens(node, { includeComments: true, - filter: astUtils.isCommentToken + filter: isCommentToken }); } @@ -285,7 +287,7 @@ class SourceCode extends TokenStore { */ let currentToken = this.getTokenBefore(node, { includeComments: true }); - while (currentToken && astUtils.isCommentToken(currentToken)) { + while (currentToken && isCommentToken(currentToken)) { if (node.parent && (currentToken.start < node.parent.start)) { break; } @@ -297,7 +299,7 @@ class SourceCode extends TokenStore { currentToken = this.getTokenAfter(node, { includeComments: true }); - while (currentToken && astUtils.isCommentToken(currentToken)) { + while (currentToken && isCommentToken(currentToken)) { if (node.parent && (currentToken.end > node.parent.end)) { break; } @@ -332,7 +334,7 @@ class SourceCode extends TokenStore { if ( tokenBefore && - astUtils.isCommentToken(tokenBefore) && + isCommentToken(tokenBefore) && tokenBefore.type === "Block" && tokenBefore.value.charAt(0) === "*" && astNode.loc.start.line - tokenBefore.loc.end.line <= 1 diff --git a/tools/node_modules/eslint/lib/token-store/backward-token-comment-cursor.js b/tools/node_modules/eslint/lib/source-code/token-store/backward-token-comment-cursor.js similarity index 100% rename from tools/node_modules/eslint/lib/token-store/backward-token-comment-cursor.js rename to tools/node_modules/eslint/lib/source-code/token-store/backward-token-comment-cursor.js diff --git a/tools/node_modules/eslint/lib/token-store/backward-token-cursor.js b/tools/node_modules/eslint/lib/source-code/token-store/backward-token-cursor.js similarity index 100% rename from tools/node_modules/eslint/lib/token-store/backward-token-cursor.js rename to tools/node_modules/eslint/lib/source-code/token-store/backward-token-cursor.js diff --git a/tools/node_modules/eslint/lib/token-store/cursor.js b/tools/node_modules/eslint/lib/source-code/token-store/cursor.js similarity index 100% rename from tools/node_modules/eslint/lib/token-store/cursor.js rename to tools/node_modules/eslint/lib/source-code/token-store/cursor.js diff --git a/tools/node_modules/eslint/lib/token-store/cursors.js b/tools/node_modules/eslint/lib/source-code/token-store/cursors.js similarity index 100% rename from tools/node_modules/eslint/lib/token-store/cursors.js rename to tools/node_modules/eslint/lib/source-code/token-store/cursors.js diff --git a/tools/node_modules/eslint/lib/token-store/decorative-cursor.js b/tools/node_modules/eslint/lib/source-code/token-store/decorative-cursor.js similarity index 100% rename from tools/node_modules/eslint/lib/token-store/decorative-cursor.js rename to tools/node_modules/eslint/lib/source-code/token-store/decorative-cursor.js diff --git a/tools/node_modules/eslint/lib/token-store/filter-cursor.js b/tools/node_modules/eslint/lib/source-code/token-store/filter-cursor.js similarity index 100% rename from tools/node_modules/eslint/lib/token-store/filter-cursor.js rename to tools/node_modules/eslint/lib/source-code/token-store/filter-cursor.js diff --git a/tools/node_modules/eslint/lib/token-store/forward-token-comment-cursor.js b/tools/node_modules/eslint/lib/source-code/token-store/forward-token-comment-cursor.js similarity index 100% rename from tools/node_modules/eslint/lib/token-store/forward-token-comment-cursor.js rename to tools/node_modules/eslint/lib/source-code/token-store/forward-token-comment-cursor.js diff --git a/tools/node_modules/eslint/lib/token-store/forward-token-cursor.js b/tools/node_modules/eslint/lib/source-code/token-store/forward-token-cursor.js similarity index 100% rename from tools/node_modules/eslint/lib/token-store/forward-token-cursor.js rename to tools/node_modules/eslint/lib/source-code/token-store/forward-token-cursor.js diff --git a/tools/node_modules/eslint/lib/token-store/index.js b/tools/node_modules/eslint/lib/source-code/token-store/index.js similarity index 99% rename from tools/node_modules/eslint/lib/token-store/index.js rename to tools/node_modules/eslint/lib/source-code/token-store/index.js index d59a0bba03b26e..8f9b09e95efe86 100644 --- a/tools/node_modules/eslint/lib/token-store/index.js +++ b/tools/node_modules/eslint/lib/source-code/token-store/index.js @@ -9,11 +9,11 @@ //------------------------------------------------------------------------------ const assert = require("assert"); +const { isCommentToken } = require("eslint-utils"); 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 @@ -184,7 +184,7 @@ function getAdjacentCommentTokensFromCursor(cursor) { const tokens = []; let currentToken = cursor.getOneToken(); - while (currentToken && astUtils.isCommentToken(currentToken)) { + while (currentToken && isCommentToken(currentToken)) { tokens.push(currentToken); currentToken = cursor.getOneToken(); } @@ -627,7 +627,7 @@ module.exports = class TokenStore { getCommentsInside(node) { return this.getTokens(node, { includeComments: true, - filter: astUtils.isCommentToken + filter: isCommentToken }); } }; diff --git a/tools/node_modules/eslint/lib/token-store/limit-cursor.js b/tools/node_modules/eslint/lib/source-code/token-store/limit-cursor.js similarity index 100% rename from tools/node_modules/eslint/lib/token-store/limit-cursor.js rename to tools/node_modules/eslint/lib/source-code/token-store/limit-cursor.js diff --git a/tools/node_modules/eslint/lib/token-store/padded-token-cursor.js b/tools/node_modules/eslint/lib/source-code/token-store/padded-token-cursor.js similarity index 100% rename from tools/node_modules/eslint/lib/token-store/padded-token-cursor.js rename to tools/node_modules/eslint/lib/source-code/token-store/padded-token-cursor.js diff --git a/tools/node_modules/eslint/lib/token-store/skip-cursor.js b/tools/node_modules/eslint/lib/source-code/token-store/skip-cursor.js similarity index 100% rename from tools/node_modules/eslint/lib/token-store/skip-cursor.js rename to tools/node_modules/eslint/lib/source-code/token-store/skip-cursor.js diff --git a/tools/node_modules/eslint/lib/token-store/utils.js b/tools/node_modules/eslint/lib/source-code/token-store/utils.js similarity index 100% rename from tools/node_modules/eslint/lib/token-store/utils.js rename to tools/node_modules/eslint/lib/source-code/token-store/utils.js 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/glob-utils.js b/tools/node_modules/eslint/lib/util/glob-utils.js deleted file mode 100644 index 33cb8e7c885a17..00000000000000 --- a/tools/node_modules/eslint/lib/util/glob-utils.js +++ /dev/null @@ -1,285 +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(/^\./u, "")); - - 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) { - if (pathname === "") { - return ""; - } - - let newPath = pathname; - const resolvedPath = path.resolve(cwd, pathname); - - if (directoryExists(resolvedPath)) { - newPath = pathname.replace(/[/\\]$/u, "") + 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 = /(?:(?:^\.)|(?:[/\\]\.))[^/\\.].*/u; - -/** - * 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 => { - if (pattern === "") { - return [{ - filename: "", - behavior: SILENTLY_IGNORE - }]; - } - - 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 && pathDescriptor.filename !== "")) { - 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/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/path-utils.js b/tools/node_modules/eslint/lib/util/path-utils.js deleted file mode 100644 index c96254df6b8529..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(/\\/gu, "/"); - - 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(/^\//u, ""); - -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = { - convertPathToPosix, - getRelativePath -}; diff --git a/tools/node_modules/eslint/messages/file-not-found.txt b/tools/node_modules/eslint/messages/file-not-found.txt index 97e2d37fa94e71..639498eb5c65d0 100644 --- a/tools/node_modules/eslint/messages/file-not-found.txt +++ b/tools/node_modules/eslint/messages/file-not-found.txt @@ -1,2 +1,2 @@ -No files matching the pattern "<%= pattern %>" were found. +No files matching the pattern "<%= pattern %>"<% if (globDisabled) { %> (with disabling globs)<% } %> 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 index 2f95c41b8c72f4..348f6dcd25f62f 100644 --- a/tools/node_modules/eslint/messages/no-config-found.txt +++ b/tools/node_modules/eslint/messages/no-config-found.txt @@ -2,6 +2,6 @@ ESLint couldn't find a configuration file. To set up a configuration file for th eslint --init -ESLint looked for configuration files in <%= directory %> and its ancestors. If it found none, it then looked in your home directory. +ESLint looked for configuration files in <%= directoryPath %> 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 index 766020b2b8f647..32e9f0ae5de585 100644 --- a/tools/node_modules/eslint/messages/plugin-missing.txt +++ b/tools/node_modules/eslint/messages/plugin-missing.txt @@ -1,11 +1,11 @@ -ESLint couldn't find the plugin "<%- pluginName %>". This can happen for a couple different reasons: +ESLint couldn't find the plugin "<%- pluginName %>". -1. If ESLint is installed globally, then make sure <%- pluginName %> is also installed globally. A globally-installed ESLint cannot find a locally-installed plugin. +(The package "<%- pluginName %>" was not found when loaded as a Node module from the directory "<%- resolvePluginsRelativeTo %>".) -2. If ESLint is installed locally, then it's likely that the plugin isn't installed correctly. Try reinstalling by running the following: +It's likely that the plugin isn't installed correctly. Try reinstalling by running the following: - npm i <%- pluginName %>@latest --save-dev + npm install <%- pluginName %>@latest --save-dev -Path to ESLint package: <%- eslintPath %> +The plugin "<%- pluginName %>" was referenced from the config file in "<%- importerName %>". 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/bail/LICENSE b/tools/node_modules/eslint/node_modules/bail/license similarity index 100% rename from tools/node_modules/eslint/node_modules/bail/LICENSE rename to tools/node_modules/eslint/node_modules/bail/license diff --git a/tools/node_modules/eslint/node_modules/bail/package.json b/tools/node_modules/eslint/node_modules/bail/package.json index 1df1a0946f2a6d..6f30336b9fc6a9 100644 --- a/tools/node_modules/eslint/node_modules/bail/package.json +++ b/tools/node_modules/eslint/node_modules/bail/package.json @@ -2,7 +2,7 @@ "author": { "name": "Titus Wormer", "email": "tituswormer@gmail.com", - "url": "http://wooorm.com" + "url": "https://wooorm.com" }, "bugs": { "url": "https://github.com/wooorm/bail/issues" @@ -12,7 +12,7 @@ { "name": "Titus Wormer", "email": "tituswormer@gmail.com", - "url": "http://wooorm.com" + "url": "https://wooorm.com" } ], "dependencies": {}, @@ -20,13 +20,13 @@ "description": "Throw a given error", "devDependencies": { "browserify": "^16.0.0", - "esmangle": "^1.0.1", - "nyc": "^11.0.0", + "nyc": "^14.0.0", "prettier": "^1.12.0", - "remark-cli": "^5.0.0", + "remark-cli": "^6.0.0", "remark-preset-wooorm": "^4.0.0", "tape": "^4.0.0", - "xo": "^0.20.0" + "tinyify": "^2.5.0", + "xo": "^0.24.0" }, "files": [ "index.js" @@ -66,21 +66,17 @@ }, "scripts": { "build": "npm run build-bundle && npm run build-mangle", - "build-bundle": "browserify index.js --bare -s bail > bail.js", - "build-mangle": "esmangle bail.js > bail.min.js", - "format": "remark . -qfo && prettier --write '**/*.js' && xo --fix", + "build-bundle": "browserify index.js -s bail -o bail.js", + "build-mangle": "browserify index.js -s bail -p tinyify -o bail.min.js", + "format": "remark . -qfo && prettier --write \"**/*.js\" && xo --fix", "test": "npm run format && npm run build && npm run test-coverage", "test-api": "node test", "test-coverage": "nyc --reporter lcov tape test.js" }, - "version": "1.0.3", + "version": "1.0.4", "xo": { "prettier": true, "esnext": false, - "rules": { - "no-var": "off", - "prefer-arrow-callback": "off" - }, "ignores": [ "bail.js" ] diff --git a/tools/node_modules/eslint/node_modules/bail/readme.md b/tools/node_modules/eslint/node_modules/bail/readme.md index abeb41bf39d1df..4b96ada673a8b2 100644 --- a/tools/node_modules/eslint/node_modules/bail/readme.md +++ b/tools/node_modules/eslint/node_modules/bail/readme.md @@ -1,4 +1,9 @@ -# bail [![Build Status][travis-badge]][travis] [![Coverage Status][codecov-badge]][codecov] +# bail + +[![Build][build-badge]][build] +[![Coverage][coverage-badge]][coverage] +[![Downloads][downloads-badge]][downloads] +[![Size][size-badge]][size] :warning: Throw a given error. @@ -50,19 +55,27 @@ Throw a given error. -[travis-badge]: https://img.shields.io/travis/wooorm/bail.svg +[build-badge]: https://img.shields.io/travis/wooorm/bail.svg + +[build]: https://travis-ci.org/wooorm/bail + +[coverage-badge]: https://img.shields.io/codecov/c/github/wooorm/bail.svg + +[coverage]: https://codecov.io/github/wooorm/bail + +[downloads-badge]: https://img.shields.io/npm/dm/bail.svg -[travis]: https://travis-ci.org/wooorm/bail +[downloads]: https://www.npmjs.com/package/bail -[codecov-badge]: https://img.shields.io/codecov/c/github/wooorm/bail.svg +[size-badge]: https://img.shields.io/bundlephobia/minzip/bail.svg -[codecov]: https://codecov.io/github/wooorm/bail +[size]: https://bundlephobia.com/result?p=bail [npm-install]: https://docs.npmjs.com/cli/install -[license]: LICENSE +[license]: license -[author]: http://wooorm.com +[author]: https://wooorm.com [noop]: https://www.npmjs.com/package/noop diff --git a/tools/node_modules/eslint/node_modules/callsites/index.js b/tools/node_modules/eslint/node_modules/callsites/index.js index c408fc8091bd3f..486c2410479cde 100644 --- a/tools/node_modules/eslint/node_modules/callsites/index.js +++ b/tools/node_modules/eslint/node_modules/callsites/index.js @@ -9,4 +9,5 @@ const callsites = () => { }; module.exports = callsites; +// TODO: Remove this for the next major release module.exports.default = callsites; diff --git a/tools/node_modules/eslint/node_modules/callsites/package.json b/tools/node_modules/eslint/node_modules/callsites/package.json index d0b8df24d1859a..b36dc6b150f396 100644 --- a/tools/node_modules/eslint/node_modules/callsites/package.json +++ b/tools/node_modules/eslint/node_modules/callsites/package.json @@ -11,9 +11,9 @@ "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" + "ava": "^1.4.1", + "tsd": "^0.7.2", + "xo": "^0.24.0" }, "engines": { "node": ">=6" @@ -42,7 +42,7 @@ "url": "git+https://github.com/sindresorhus/callsites.git" }, "scripts": { - "test": "xo && ava && tsd-check" + "test": "xo && ava && tsd" }, - "version": "3.0.0" + "version": "3.1.0" } \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/character-entities-legacy/LICENSE b/tools/node_modules/eslint/node_modules/character-entities-legacy/license similarity index 100% rename from tools/node_modules/eslint/node_modules/character-entities-legacy/LICENSE rename to tools/node_modules/eslint/node_modules/character-entities-legacy/license diff --git a/tools/node_modules/eslint/node_modules/character-entities-legacy/package.json b/tools/node_modules/eslint/node_modules/character-entities-legacy/package.json index e0cf18af099a85..f3f595955425da 100644 --- a/tools/node_modules/eslint/node_modules/character-entities-legacy/package.json +++ b/tools/node_modules/eslint/node_modules/character-entities-legacy/package.json @@ -2,7 +2,7 @@ "author": { "name": "Titus Wormer", "email": "tituswormer@gmail.com", - "url": "http://wooorm.com" + "url": "https://wooorm.com" }, "bugs": { "url": "https://github.com/wooorm/character-entities-legacy/issues" @@ -12,7 +12,7 @@ { "name": "Titus Wormer", "email": "tituswormer@gmail.com", - "url": "http://wooorm.com" + "url": "https://wooorm.com" } ], "dependencies": {}, @@ -21,13 +21,13 @@ "devDependencies": { "bail": "^1.0.1", "browserify": "^16.0.0", - "concat-stream": "^1.5.2", - "esmangle": "^1.0.1", + "concat-stream": "^2.0.0", "prettier": "^1.12.0", - "remark-cli": "^5.0.0", + "remark-cli": "^6.0.0", "remark-preset-wooorm": "^4.0.0", "tape": "^4.0.0", - "xo": "^0.20.0" + "tinyify": "^2.5.0", + "xo": "^0.24.0" }, "files": [ "index.json" @@ -64,21 +64,17 @@ }, "scripts": { "build": "npm run build-bundle && npm run build-mangle", - "build-bundle": "browserify index.json --bare -s characterEntitiesLegacy > character-entities-legacy.js", - "build-mangle": "esmangle character-entities-legacy.js > character-entities-legacy.min.js", - "format": "remark . -qfo && prettier --write '**/*.js' && xo --fix", + "build-bundle": "browserify index.json -s characterEntitiesLegacy -o character-entities-legacy.js", + "build-mangle": "browserify index.json -s characterEntitiesLegacy -p tinyify -o character-entities-legacy.min.js", + "format": "remark . -qfo && prettier --write \"**/*.js\" && xo --fix", "generate": "node build", "test": "npm run generate && npm run format && npm run build && npm run test-api", "test-api": "node test" }, - "version": "1.1.2", + "version": "1.1.3", "xo": { "prettier": true, "esnext": false, - "rules": { - "no-var": "off", - "prefer-arrow-callback": "off" - }, "ignores": [ "character-entities-legacy.js" ] diff --git a/tools/node_modules/eslint/node_modules/character-entities-legacy/readme.md b/tools/node_modules/eslint/node_modules/character-entities-legacy/readme.md index 430c234c9f0c43..c505e24cf845dd 100644 --- a/tools/node_modules/eslint/node_modules/character-entities-legacy/readme.md +++ b/tools/node_modules/eslint/node_modules/character-entities-legacy/readme.md @@ -1,4 +1,8 @@ -# character-entities-legacy [![Build Status][travis-badge]][travis] +# character-entities-legacy + +[![Build][build-badge]][build] +[![Downloads][downloads-badge]][downloads] +[![Size][size-badge]][size] HTML legacy character entity information: for legacy reasons some character entities are not required to have a trailing semicolon: @@ -50,14 +54,22 @@ See [whatwg/html][html]. -[travis-badge]: https://img.shields.io/travis/wooorm/character-entities-legacy.svg +[build-badge]: https://img.shields.io/travis/wooorm/character-entities-legacy.svg + +[build]: https://travis-ci.org/wooorm/character-entities-legacy + +[downloads-badge]: https://img.shields.io/npm/dm/character-entities-legacy.svg + +[downloads]: https://www.npmjs.com/package/character-entities-legacy + +[size-badge]: https://img.shields.io/bundlephobia/minzip/character-entities-legacy.svg -[travis]: https://travis-ci.org/wooorm/character-entities-legacy +[size]: https://bundlephobia.com/result?p=character-entities-legacy [npm]: https://docs.npmjs.com/cli/install -[license]: LICENSE +[license]: license -[author]: http://wooorm.com +[author]: https://wooorm.com [html]: https://raw.githubusercontent.com/whatwg/html/master/json-entities-legacy.inc diff --git a/tools/node_modules/eslint/node_modules/character-entities/LICENSE b/tools/node_modules/eslint/node_modules/character-entities/license similarity index 100% rename from tools/node_modules/eslint/node_modules/character-entities/LICENSE rename to tools/node_modules/eslint/node_modules/character-entities/license diff --git a/tools/node_modules/eslint/node_modules/character-entities/package.json b/tools/node_modules/eslint/node_modules/character-entities/package.json index 6b7b3866a05d08..b231fac4c4b31b 100644 --- a/tools/node_modules/eslint/node_modules/character-entities/package.json +++ b/tools/node_modules/eslint/node_modules/character-entities/package.json @@ -2,7 +2,7 @@ "author": { "name": "Titus Wormer", "email": "tituswormer@gmail.com", - "url": "http://wooorm.com" + "url": "https://wooorm.com" }, "bugs": { "url": "https://github.com/wooorm/character-entities/issues" @@ -12,7 +12,7 @@ { "name": "Titus Wormer", "email": "tituswormer@gmail.com", - "url": "http://wooorm.com" + "url": "https://wooorm.com" } ], "dependencies": {}, @@ -21,13 +21,13 @@ "devDependencies": { "bail": "^1.0.1", "browserify": "^16.0.0", - "concat-stream": "^1.5.2", - "esmangle": "^1.0.1", + "concat-stream": "^2.0.0", "prettier": "^1.12.0", - "remark-cli": "^5.0.0", + "remark-cli": "^6.0.0", "remark-preset-wooorm": "^4.0.0", "tape": "^4.0.0", - "xo": "^0.20.0" + "tinyify": "^2.5.0", + "xo": "^0.24.0" }, "files": [ "index.json" @@ -64,22 +64,18 @@ }, "scripts": { "build": "npm run build-bundle && npm run build-mangle", - "build-bundle": "browserify index.json --bare -s characterEntities > character-entities.js", - "build-mangle": "esmangle character-entities.js > character-entities.min.js", - "format": "remark . -qfo && prettier --write '**/*.js' && xo --fix", + "build-bundle": "browserify index.json -s characterEntities -o character-entities.js", + "build-mangle": "browserify index.json -s characterEntities -p tinyify -o character-entities.min.js", + "format": "remark . -qfo && prettier --write \"**/*.js\" && xo --fix", "generate": "node build", "lint": "xo", "test": "npm run generate && npm run format && npm run build && npm run test-api", "test-api": "node test" }, - "version": "1.2.2", + "version": "1.2.3", "xo": { "prettier": true, "esnext": false, - "rules": { - "no-var": "off", - "prefer-arrow-callback": "off" - }, "ignores": [ "character-entities.js" ] diff --git a/tools/node_modules/eslint/node_modules/character-entities/readme.md b/tools/node_modules/eslint/node_modules/character-entities/readme.md index 866ad68bb888ac..078b7145fd4c38 100644 --- a/tools/node_modules/eslint/node_modules/character-entities/readme.md +++ b/tools/node_modules/eslint/node_modules/character-entities/readme.md @@ -1,4 +1,8 @@ -# character-entities [![Build Status][travis-badge]][travis] +# character-entities + +[![Build][build-badge]][build] +[![Downloads][downloads-badge]][downloads] +[![Size][size-badge]][size] HTML character entity information. @@ -47,14 +51,22 @@ See [html.spec.whatwg.org][html]. -[travis-badge]: https://img.shields.io/travis/wooorm/character-entities.svg +[build-badge]: https://img.shields.io/travis/wooorm/character-entities.svg + +[build]: https://travis-ci.org/wooorm/character-entities + +[downloads-badge]: https://img.shields.io/npm/dm/character-entities.svg + +[downloads]: https://www.npmjs.com/package/character-entities + +[size-badge]: https://img.shields.io/bundlephobia/minzip/character-entities.svg -[travis]: https://travis-ci.org/wooorm/character-entities +[size]: https://bundlephobia.com/result?p=character-entities [npm]: https://docs.npmjs.com/cli/install -[license]: LICENSE +[license]: license -[author]: http://wooorm.com +[author]: https://wooorm.com [html]: https://html.spec.whatwg.org/multipage/syntax.html#named-character-references diff --git a/tools/node_modules/eslint/node_modules/character-reference-invalid/LICENSE b/tools/node_modules/eslint/node_modules/character-reference-invalid/license similarity index 100% rename from tools/node_modules/eslint/node_modules/character-reference-invalid/LICENSE rename to tools/node_modules/eslint/node_modules/character-reference-invalid/license diff --git a/tools/node_modules/eslint/node_modules/character-reference-invalid/package.json b/tools/node_modules/eslint/node_modules/character-reference-invalid/package.json index 0d627418480fea..c6a16efb7c0855 100644 --- a/tools/node_modules/eslint/node_modules/character-reference-invalid/package.json +++ b/tools/node_modules/eslint/node_modules/character-reference-invalid/package.json @@ -2,7 +2,7 @@ "author": { "name": "Titus Wormer", "email": "tituswormer@gmail.com", - "url": "http://wooorm.com" + "url": "https://wooorm.com" }, "bugs": { "url": "https://github.com/wooorm/character-reference-invalid/issues" @@ -12,7 +12,7 @@ { "name": "Titus Wormer", "email": "tituswormer@gmail.com", - "url": "http://wooorm.com" + "url": "https://wooorm.com" } ], "dependencies": {}, @@ -21,16 +21,16 @@ "devDependencies": { "bail": "^1.0.1", "browserify": "^16.0.0", - "concat-stream": "^1.6.0", - "esmangle": "^1.0.1", - "hast-util-select": "^1.0.1", + "concat-stream": "^2.0.0", + "hast-util-select": "^3.0.0", "hast-util-to-string": "^1.0.0", - "rehype-parse": "^4.0.0", - "remark-cli": "^5.0.0", + "rehype-parse": "^6.0.0", + "remark-cli": "^6.0.0", "remark-preset-wooorm": "^4.0.0", "tape": "^4.0.0", - "unified": "^6.1.5", - "xo": "^0.20.0" + "tinyify": "^2.5.0", + "unified": "^7.0.0", + "xo": "^0.24.0" }, "files": [ "index.json" @@ -68,22 +68,17 @@ }, "scripts": { "build": "npm run build-bundle && npm run build-mangle", - "build-bundle": "browserify index.json --bare -s characterReferenceInvalid > character-reference-invalid.js", - "build-mangle": "esmangle character-reference-invalid.js > character-reference-invalid.min.js", - "format": "remark . -qfo && prettier --write '**/*.js' && xo --fix", + "build-bundle": "browserify index.json -s characterReferenceInvalid -o character-reference-invalid.js", + "build-mangle": "browserify index.json -s characterReferenceInvalid -p tinyify -o character-reference-invalid.min.js", + "format": "remark . -qfo && prettier --write \"**/*.js\" && xo --fix", "generate": "node build", "test": "npm run generate && npm run format && npm run build && npm run test-api", "test-api": "node test" }, - "version": "1.1.2", + "version": "1.1.3", "xo": { "prettier": true, "esnext": false, - "rules": { - "guard-for-in": "off", - "no-var": "off", - "prefer-arrow-callback": "off" - }, "ignores": [ "character-reference-invalid.js" ] diff --git a/tools/node_modules/eslint/node_modules/character-reference-invalid/readme.md b/tools/node_modules/eslint/node_modules/character-reference-invalid/readme.md index 3b12563ea35e8d..b7cbca58f40d67 100644 --- a/tools/node_modules/eslint/node_modules/character-reference-invalid/readme.md +++ b/tools/node_modules/eslint/node_modules/character-reference-invalid/readme.md @@ -1,4 +1,8 @@ -# character-reference-invalid [![Build Status][travis-badge]][travis] +# character-reference-invalid + +[![Build][build-badge]][build] +[![Downloads][downloads-badge]][downloads] +[![Size][size-badge]][size] HTML invalid numeric character reference information. @@ -49,14 +53,22 @@ See [html.spec.whatwg.org][html]. -[travis-badge]: https://img.shields.io/travis/wooorm/character-reference-invalid.svg +[build-badge]: https://img.shields.io/travis/wooorm/character-reference-invalid.svg + +[build]: https://travis-ci.org/wooorm/character-reference-invalid + +[downloads-badge]: https://img.shields.io/npm/dm/character-reference-invalid.svg + +[downloads]: https://www.npmjs.com/package/character-reference-invalid + +[size-badge]: https://img.shields.io/bundlephobia/minzip/character-reference-invalid.svg -[travis]: https://travis-ci.org/wooorm/character-reference-invalid +[size]: https://bundlephobia.com/result?p=character-reference-invalid [npm]: https://docs.npmjs.com/cli/install -[license]: LICENSE +[license]: license -[author]: http://wooorm.com +[author]: https://wooorm.com [html]: https://html.spec.whatwg.org/multipage/syntax.html#table-charref-overrides diff --git a/tools/node_modules/eslint/node_modules/collapse-white-space/index.js b/tools/node_modules/eslint/node_modules/collapse-white-space/index.js index bdc13aa4ac9e44..93d546695c7ae7 100644 --- a/tools/node_modules/eslint/node_modules/collapse-white-space/index.js +++ b/tools/node_modules/eslint/node_modules/collapse-white-space/index.js @@ -2,7 +2,7 @@ module.exports = collapse -/* collapse(' \t\nbar \nbaz\t'); // ' bar baz ' */ +// `collapse(' \t\nbar \nbaz\t') // ' bar baz '` function collapse(value) { return String(value).replace(/\s+/g, ' ') } diff --git a/tools/node_modules/eslint/node_modules/collapse-white-space/LICENSE b/tools/node_modules/eslint/node_modules/collapse-white-space/license similarity index 100% rename from tools/node_modules/eslint/node_modules/collapse-white-space/LICENSE rename to tools/node_modules/eslint/node_modules/collapse-white-space/license diff --git a/tools/node_modules/eslint/node_modules/collapse-white-space/package.json b/tools/node_modules/eslint/node_modules/collapse-white-space/package.json index 9c929b3837d146..745288f010e358 100644 --- a/tools/node_modules/eslint/node_modules/collapse-white-space/package.json +++ b/tools/node_modules/eslint/node_modules/collapse-white-space/package.json @@ -2,7 +2,7 @@ "author": { "name": "Titus Wormer", "email": "tituswormer@gmail.com", - "url": "http://wooorm.com" + "url": "https://wooorm.com" }, "bugs": { "url": "https://github.com/wooorm/collapse-white-space/issues" @@ -12,7 +12,7 @@ { "name": "Titus Wormer", "email": "tituswormer@gmail.com", - "url": "http://wooorm.com" + "url": "https://wooorm.com" } ], "dependencies": {}, @@ -20,12 +20,13 @@ "description": "Replace multiple white-space characters with a single space", "devDependencies": { "browserify": "^16.0.0", - "esmangle": "^1.0.1", - "nyc": "^11.0.0", - "remark-cli": "^5.0.0", + "nyc": "^14.0.0", + "prettier": "^1.12.0", + "remark-cli": "^6.0.0", "remark-preset-wooorm": "^4.0.0", "tape": "^4.0.0", - "xo": "^0.20.0" + "tinyify": "^2.5.0", + "xo": "^0.24.0" }, "files": [ "index.js" @@ -63,22 +64,17 @@ }, "scripts": { "build": "npm run build-bundle && npm run build-mangle", - "build-bundle": "browserify index.js --bare -s collapseWhiteSpace > collapse-white-space.js", - "build-mangle": "esmangle collapse-white-space.js > collapse-white-space.min.js", - "format": "remark . -qfo && prettier --write '**/*.js' && xo --fix", + "build-bundle": "browserify . -s collapseWhiteSpace -o collapse-white-space.js", + "build-mangle": "browserify . -s collapseWhiteSpace -p tinyify -o collapse-white-space.min.js", + "format": "remark . -qfo && prettier --write \"**/*.js\" && xo --fix", "test": "npm run format && npm run build && npm run test-coverage", "test-api": "node test", "test-coverage": "nyc --reporter lcov tape test.js" }, - "version": "1.0.4", + "version": "1.0.5", "xo": { "prettier": true, "esnext": false, - "rules": { - "capitalized-comments": "off", - "no-var": "off", - "prefer-arrow-callback": "off" - }, "ignores": [ "collapse-white-space.js" ] diff --git a/tools/node_modules/eslint/node_modules/collapse-white-space/readme.md b/tools/node_modules/eslint/node_modules/collapse-white-space/readme.md index 270a3e892c9e31..67304917845991 100644 --- a/tools/node_modules/eslint/node_modules/collapse-white-space/readme.md +++ b/tools/node_modules/eslint/node_modules/collapse-white-space/readme.md @@ -1,4 +1,9 @@ -# collapse-white-space [![Build Status][travis-badge]][travis] [![Coverage Status][codecov-badge]][codecov] +# collapse-white-space + +[![Build][build-badge]][build] +[![Coverage][coverage-badge]][coverage] +[![Downloads][downloads-badge]][downloads] +[![Size][size-badge]][size] Replace multiple white-space characters with a single space. @@ -30,16 +35,24 @@ Replace multiple white-space characters in value with a single space. -[travis-badge]: https://img.shields.io/travis/wooorm/collapse-white-space.svg +[build-badge]: https://img.shields.io/travis/wooorm/collapse-white-space.svg + +[build]: https://travis-ci.org/wooorm/collapse-white-space + +[coverage-badge]: https://img.shields.io/codecov/c/github/wooorm/collapse-white-space.svg + +[coverage]: https://codecov.io/github/wooorm/collapse-white-space + +[downloads-badge]: https://img.shields.io/npm/dm/collapse-white-space.svg -[travis]: https://travis-ci.org/wooorm/collapse-white-space +[downloads]: https://www.npmjs.com/package/collapse-white-space -[codecov-badge]: https://img.shields.io/codecov/c/github/wooorm/collapse-white-space.svg +[size-badge]: https://img.shields.io/bundlephobia/minzip/collapse-white-space.svg -[codecov]: https://codecov.io/github/wooorm/collapse-white-space +[size]: https://bundlephobia.com/result?p=collapse-white-space [npm-install]: https://docs.npmjs.com/cli/install -[license]: LICENSE +[license]: license -[author]: http://wooorm.com +[author]: https://wooorm.com diff --git a/tools/node_modules/eslint/node_modules/espree/lib/espree.js b/tools/node_modules/eslint/node_modules/espree/lib/espree.js index 107affd1d6ca26..6c57a87c65e36a 100644 --- a/tools/node_modules/eslint/node_modules/espree/lib/espree.js +++ b/tools/node_modules/eslint/node_modules/espree/lib/espree.js @@ -10,12 +10,14 @@ const STATE = Symbol("espree's internal state"); const ESPRIMA_FINISH_NODE = Symbol("espree's esprimaFinishNode"); const tokTypes = Object.assign({}, acorn.tokTypes, jsx.tokTypes); + /** * Normalize ECMAScript version from the initial config * @param {number} ecmaVersion ECMAScript version from the initial config + * @throws {Error} throws an error if the ecmaVersion is invalid. * @returns {number} normalized ECMAScript version */ -function normalizeEcmaVersion(ecmaVersion) { +function normalizeEcmaVersion(ecmaVersion = DEFAULT_ECMA_VERSION) { if (typeof ecmaVersion === "number") { let version = ecmaVersion; @@ -35,12 +37,42 @@ function normalizeEcmaVersion(ecmaVersion) { case 10: return version; - default: - throw new Error("Invalid ecmaVersion."); + // no default } - } else { - return DEFAULT_ECMA_VERSION; } + + throw new Error("Invalid ecmaVersion."); +} + +/** + * Normalize sourceType from the initial config + * @param {string} sourceType to normalize + * @throws {Error} throw an error if sourceType is invalid + * @returns {string} normalized sourceType + */ +function normalizeSourceType(sourceType = "script") { + if (sourceType === "script" || sourceType === "module") { + return sourceType; + } + throw new Error("Invalid sourceType."); +} + +/** + * Normalize parserOptions + * @param {Object} options the parser options to normalize + * @throws {Error} throw an error if found invalid option. + * @returns {Object} normalized options + */ +function normalizeOptions(options) { + const ecmaVersion = normalizeEcmaVersion(options.ecmaVersion); + const sourceType = normalizeSourceType(options.sourceType); + const ranges = options.range === true; + const locations = options.loc === true; + + if (sourceType === "module" && ecmaVersion < 6) { + throw new Error("sourceType 'module' is not supported when ecmaVersion < 2015. Consider adding `{ ecmaVersion: 2015 }` to the parser options."); + } + return Object.assign({}, options, { ecmaVersion, sourceType, ranges, locations }); } /** @@ -77,17 +109,16 @@ function convertAcornCommentToEsprimaComment(block, text, start, end, startLoc, } module.exports = () => Parser => class Espree extends Parser { - constructor(options, code) { - if (typeof options !== "object" || options === null) { - options = {}; + constructor(opts, code) { + if (typeof opts !== "object" || opts === null) { + opts = {}; } if (typeof code !== "string" && !(code instanceof String)) { code = String(code); } + const options = normalizeOptions(opts); const ecmaFeatures = options.ecmaFeatures || {}; - const ecmaVersion = normalizeEcmaVersion(options.ecmaVersion); - const isModule = options.sourceType === "module"; const tokenTranslator = options.tokens === true ? new TokenTranslator(tokTypes, code) @@ -95,10 +126,12 @@ module.exports = () => Parser => class Espree extends Parser { // Initialize acorn parser. super({ - ecmaVersion: isModule ? Math.max(6, ecmaVersion) : ecmaVersion, - sourceType: isModule ? "module" : "script", - ranges: options.range === true, - locations: options.loc === true, + + // TODO: use {...options} when spread is supported(Node.js >= 8.3.0). + ecmaVersion: options.ecmaVersion, + sourceType: options.sourceType, + ranges: options.ranges, + locations: options.locations, // Truthy value is true for backward compatibility. allowReturnOutsideFunction: Boolean(ecmaFeatures.globalReturn), diff --git a/tools/node_modules/eslint/node_modules/espree/package.json b/tools/node_modules/eslint/node_modules/espree/package.json index 902e80a99a3c35..0c036081c94799 100644 --- a/tools/node_modules/eslint/node_modules/espree/package.json +++ b/tools/node_modules/eslint/node_modules/espree/package.json @@ -66,5 +66,5 @@ "publish-release": "eslint-publish-release", "test": "npm run-script lint && node Makefile.js test" }, - "version": "5.0.1" + "version": "6.0.0-alpha.0" } \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/glob-parent/LICENSE b/tools/node_modules/eslint/node_modules/glob-parent/LICENSE new file mode 100644 index 00000000000000..734076d8affcff --- /dev/null +++ b/tools/node_modules/eslint/node_modules/glob-parent/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) 2015 Elan Shanker + +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/tools/node_modules/eslint/node_modules/glob-parent/README.md b/tools/node_modules/eslint/node_modules/glob-parent/README.md new file mode 100644 index 00000000000000..3bec5c78e49dd7 --- /dev/null +++ b/tools/node_modules/eslint/node_modules/glob-parent/README.md @@ -0,0 +1,109 @@ +glob-parent [![Build Status](https://travis-ci.org/es128/glob-parent.svg)](https://travis-ci.org/es128/glob-parent) [![Coverage Status](https://img.shields.io/coveralls/es128/glob-parent.svg)](https://coveralls.io/r/es128/glob-parent?branch=master) +====== +Javascript module to extract the non-magic parent path from a glob string. + +[![NPM](https://nodei.co/npm/glob-parent.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/glob-parent/) +[![NPM](https://nodei.co/npm-dl/glob-parent.png?height=3&months=9)](https://nodei.co/npm-dl/glob-parent/) + +Usage +----- +```sh +npm install glob-parent --save +``` + +**Examples** + +```js +var globParent = require('glob-parent'); + +globParent('path/to/*.js'); // 'path/to' +globParent('/root/path/to/*.js'); // '/root/path/to' +globParent('/*.js'); // '/' +globParent('*.js'); // '.' +globParent('**/*.js'); // '.' +globParent('path/{to,from}'); // 'path' +globParent('path/!(to|from)'); // 'path' +globParent('path/?(to|from)'); // 'path' +globParent('path/+(to|from)'); // 'path' +globParent('path/*(to|from)'); // 'path' +globParent('path/@(to|from)'); // 'path' +globParent('path/**/*'); // 'path' + +// if provided a non-glob path, returns the nearest dir +globParent('path/foo/bar.js'); // 'path/foo' +globParent('path/foo/'); // 'path/foo' +globParent('path/foo'); // 'path' (see issue #3 for details) +``` + +## Escaping + +The following characters have special significance in glob patterns and must be escaped if you want them to be treated as regular path characters: + +- `?` (question mark) +- `*` (star) +- `|` (pipe) +- `(` (opening parenthesis) +- `)` (closing parenthesis) +- `{` (opening curly brace) +- `}` (closing curly brace) +- `[` (opening bracket) +- `]` (closing bracket) + +**Example** + +```js +globParent('foo/[bar]/') // 'foo' +globParent('foo/\\[bar]/') // 'foo/[bar]' +``` + +## Limitations + +#### Braces & Brackets +This library attempts a quick and imperfect method of determining which path +parts have glob magic without fully parsing/lexing the pattern. There are some +advanced use cases that can trip it up, such as nested braces where the outer +pair is escaped and the inner one contains a path separator. If you find +yourself in the unlikely circumstance of being affected by this or need to +ensure higher-fidelity glob handling in your library, it is recommended that you +pre-process your input with [expand-braces] and/or [expand-brackets]. + +#### Windows +Backslashes are not valid path separators for globs. If a path with backslashes +is provided anyway, for simple cases, glob-parent will replace the path +separator for you and return the non-glob parent path (now with +forward-slashes, which are still valid as Windows path separators). + +This cannot be used in conjunction with escape characters. + +```js +// BAD +globParent('C:\\Program Files \\(x86\\)\\*.ext') // 'C:/Program Files /(x86/)' + +// GOOD +globParent('C:/Program Files\\(x86\\)/*.ext') // 'C:/Program Files (x86)' +``` + +If you are using escape characters for a pattern without path parts (i.e. +relative to `cwd`), prefix with `./` to avoid confusing glob-parent. + +```js +// BAD +globParent('foo \\[bar]') // 'foo ' +globParent('foo \\[bar]*') // 'foo ' + +// GOOD +globParent('./foo \\[bar]') // 'foo [bar]' +globParent('./foo \\[bar]*') // '.' +``` + + +Change Log +---------- +[See release notes page on GitHub](https://github.com/es128/glob-parent/releases) + +License +------- +[ISC](https://raw.github.com/es128/glob-parent/master/LICENSE) + +[expand-braces]: https://github.com/jonschlinkert/expand-braces +[expand-brackets]: https://github.com/jonschlinkert/expand-brackets diff --git a/tools/node_modules/eslint/node_modules/glob-parent/index.js b/tools/node_modules/eslint/node_modules/glob-parent/index.js new file mode 100644 index 00000000000000..3a14a539f04754 --- /dev/null +++ b/tools/node_modules/eslint/node_modules/glob-parent/index.js @@ -0,0 +1,24 @@ +'use strict'; + +var path = require('path'); +var isglob = require('is-glob'); +var pathDirname = require('path-dirname'); +var isWin32 = require('os').platform() === 'win32'; + +module.exports = function globParent(str) { + // flip windows path separators + if (isWin32 && str.indexOf('/') < 0) str = str.split('\\').join('/'); + + // special case for strings ending in enclosure containing path separator + if (/[\{\[].*[\/]*.*[\}\]]$/.test(str)) str += '/'; + + // preserves full path in case of trailing path separator + str += 'a'; + + // remove path parts that are globby + do {str = pathDirname.posix(str)} + while (isglob(str) || /(^|[^\\])([\{\[]|\([^\)]+$)/.test(str)); + + // remove escape chars and return result + return str.replace(/\\([\*\?\|\[\]\(\)\{\}])/g, '$1'); +}; diff --git a/tools/node_modules/eslint/node_modules/path-is-inside/LICENSE.txt b/tools/node_modules/eslint/node_modules/glob-parent/node_modules/is-glob/LICENSE similarity index 50% rename from tools/node_modules/eslint/node_modules/path-is-inside/LICENSE.txt rename to tools/node_modules/eslint/node_modules/glob-parent/node_modules/is-glob/LICENSE index 0bdbb61c9decb1..39245ac1c60613 100644 --- a/tools/node_modules/eslint/node_modules/path-is-inside/LICENSE.txt +++ b/tools/node_modules/eslint/node_modules/glob-parent/node_modules/is-glob/LICENSE @@ -1,32 +1,6 @@ -Dual licensed under WTFPL and MIT: - ---- - -Copyright © 2013–2016 Domenic Denicola - -This work is free. You can redistribute it and/or modify it under the -terms of the Do What The Fuck You Want To Public License, Version 2, -as published by Sam Hocevar. See below for more details. - - DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE - Version 2, December 2004 - - Copyright (C) 2004 Sam Hocevar - - Everyone is permitted to copy and distribute verbatim or modified - copies of this license document, and changing it is allowed as long - as the name is changed. - - DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. You just DO WHAT THE FUCK YOU WANT TO. - ---- - The MIT License (MIT) -Copyright © 2013–2016 Domenic Denicola +Copyright (c) 2014-2016, Jon Schlinkert. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -35,13 +9,13 @@ 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 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. +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/glob-parent/node_modules/is-glob/README.md b/tools/node_modules/eslint/node_modules/glob-parent/node_modules/is-glob/README.md new file mode 100644 index 00000000000000..e71dc2ceb9856a --- /dev/null +++ b/tools/node_modules/eslint/node_modules/glob-parent/node_modules/is-glob/README.md @@ -0,0 +1,142 @@ +# is-glob [![NPM version](https://img.shields.io/npm/v/is-glob.svg?style=flat)](https://www.npmjs.com/package/is-glob) [![NPM downloads](https://img.shields.io/npm/dm/is-glob.svg?style=flat)](https://npmjs.org/package/is-glob) [![Build Status](https://img.shields.io/travis/jonschlinkert/is-glob.svg?style=flat)](https://travis-ci.org/jonschlinkert/is-glob) + +> Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a better user experience. + +## Install + +Install with [npm](https://www.npmjs.com/): + +```sh +$ npm install --save is-glob +``` + +You might also be interested in [is-valid-glob](https://github.com/jonschlinkert/is-valid-glob) and [has-glob](https://github.com/jonschlinkert/has-glob). + +## Usage + +```js +var isGlob = require('is-glob'); +``` + +**True** + +Patterns that have glob characters or regex patterns will return `true`: + +```js +isGlob('!foo.js'); +isGlob('*.js'); +isGlob('**/abc.js'); +isGlob('abc/*.js'); +isGlob('abc/(aaa|bbb).js'); +isGlob('abc/[a-z].js'); +isGlob('abc/{a,b}.js'); +isGlob('abc/?.js'); +//=> true +``` + +Extglobs + +```js +isGlob('abc/@(a).js'); +isGlob('abc/!(a).js'); +isGlob('abc/+(a).js'); +isGlob('abc/*(a).js'); +isGlob('abc/?(a).js'); +//=> true +``` + +**False** + +Escaped globs or extglobs return `false`: + +```js +isGlob('abc/\\@(a).js'); +isGlob('abc/\\!(a).js'); +isGlob('abc/\\+(a).js'); +isGlob('abc/\\*(a).js'); +isGlob('abc/\\?(a).js'); +isGlob('\\!foo.js'); +isGlob('\\*.js'); +isGlob('\\*\\*/abc.js'); +isGlob('abc/\\*.js'); +isGlob('abc/\\(aaa|bbb).js'); +isGlob('abc/\\[a-z].js'); +isGlob('abc/\\{a,b}.js'); +isGlob('abc/\\?.js'); +//=> false +``` + +Patterns that do not have glob patterns return `false`: + +```js +isGlob('abc.js'); +isGlob('abc/def/ghi.js'); +isGlob('foo.js'); +isGlob('abc/@.js'); +isGlob('abc/+.js'); +isGlob(); +isGlob(null); +//=> false +``` + +Arrays are also `false` (If you want to check if an array has a glob pattern, use [has-glob](https://github.com/jonschlinkert/has-glob)): + +```js +isGlob(['**/*.js']); +isGlob(['foo.js']); +//=> false +``` + +## About + +### Related projects + +* [assemble](https://www.npmjs.com/package/assemble): Get the rocks out of your socks! Assemble makes you fast at creating web projects… [more](https://github.com/assemble/assemble) | [homepage](https://github.com/assemble/assemble "Get the rocks out of your socks! Assemble makes you fast at creating web projects. Assemble is used by thousands of projects for rapid prototyping, creating themes, scaffolds, boilerplates, e-books, UI components, API documentation, blogs, building websit") +* [base](https://www.npmjs.com/package/base): base is the foundation for creating modular, unit testable and highly pluggable node.js applications, starting… [more](https://github.com/node-base/base) | [homepage](https://github.com/node-base/base "base is the foundation for creating modular, unit testable and highly pluggable node.js applications, starting with a handful of common methods, like `set`, `get`, `del` and `use`.") +* [update](https://www.npmjs.com/package/update): Be scalable! Update is a new, open source developer framework and CLI for automating updates… [more](https://github.com/update/update) | [homepage](https://github.com/update/update "Be scalable! Update is a new, open source developer framework and CLI for automating updates of any kind in code projects.") +* [verb](https://www.npmjs.com/package/verb): Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used… [more](https://github.com/verbose/verb) | [homepage](https://github.com/verbose/verb "Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used on hundreds of projects of all sizes to generate everything from API docs to readmes.") + +### Contributing + +Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). + +### Contributors + +| **Commits** | **Contributor**
| +| --- | --- | +| 40 | [jonschlinkert](https://github.com/jonschlinkert) | +| 1 | [tuvistavie](https://github.com/tuvistavie) | + +### Building docs + +_(This document was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme) (a [verb](https://github.com/verbose/verb) generator), please don't edit the readme directly. Any changes to the readme must be made in [.verb.md](.verb.md).)_ + +To generate the readme and API documentation with [verb](https://github.com/verbose/verb): + +```sh +$ npm install -g verb verb-generate-readme && verb +``` + +### Running tests + +Install dev dependencies: + +```sh +$ npm install -d && npm test +``` + +### Author + +**Jon Schlinkert** + +* [github/jonschlinkert](https://github.com/jonschlinkert) +* [twitter/jonschlinkert](http://twitter.com/jonschlinkert) + +### License + +Copyright © 2016, [Jon Schlinkert](https://github.com/jonschlinkert). +Released under the [MIT license](https://github.com/jonschlinkert/is-glob/blob/master/LICENSE). + +*** + +_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.1.31, on October 12, 2016._ \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/glob-parent/node_modules/is-glob/index.js b/tools/node_modules/eslint/node_modules/glob-parent/node_modules/is-glob/index.js new file mode 100644 index 00000000000000..2ecbe2a74ec48b --- /dev/null +++ b/tools/node_modules/eslint/node_modules/glob-parent/node_modules/is-glob/index.js @@ -0,0 +1,25 @@ +/*! + * is-glob + * + * Copyright (c) 2014-2016, Jon Schlinkert. + * Licensed under the MIT License. + */ + +var isExtglob = require('is-extglob'); + +module.exports = function isGlob(str) { + if (typeof str !== 'string' || str === '') { + return false; + } + + if (isExtglob(str)) return true; + + var regex = /(\\).|([*?]|\[.*\]|\{.*\}|\(.*\|.*\)|^!)/; + var match; + + while ((match = regex.exec(str))) { + if (match[2]) return true; + str = str.slice(match.index + match[0].length); + } + return false; +}; diff --git a/tools/node_modules/eslint/node_modules/glob-parent/node_modules/is-glob/package.json b/tools/node_modules/eslint/node_modules/glob-parent/node_modules/is-glob/package.json new file mode 100644 index 00000000000000..e871a90c80aea6 --- /dev/null +++ b/tools/node_modules/eslint/node_modules/glob-parent/node_modules/is-glob/package.json @@ -0,0 +1,96 @@ +{ + "author": { + "name": "Jon Schlinkert", + "url": "https://github.com/jonschlinkert" + }, + "bugs": { + "url": "https://github.com/jonschlinkert/is-glob/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Daniel Perez", + "email": "daniel@claudetech.com", + "url": "http://tuvistavie.com" + }, + { + "name": "Jon Schlinkert", + "email": "jon.schlinkert@sellside.com", + "url": "http://twitter.com/jonschlinkert" + } + ], + "dependencies": { + "is-extglob": "^2.1.0" + }, + "deprecated": false, + "description": "Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a better user experience.", + "devDependencies": { + "gulp-format-md": "^0.1.10", + "mocha": "^3.0.2" + }, + "engines": { + "node": ">=0.10.0" + }, + "files": [ + "index.js" + ], + "homepage": "https://github.com/jonschlinkert/is-glob", + "keywords": [ + "bash", + "braces", + "check", + "exec", + "expression", + "extglob", + "glob", + "globbing", + "globstar", + "is", + "match", + "matches", + "pattern", + "regex", + "regular", + "string", + "test" + ], + "license": "MIT", + "main": "index.js", + "name": "is-glob", + "repository": { + "type": "git", + "url": "git+https://github.com/jonschlinkert/is-glob.git" + }, + "scripts": { + "test": "mocha" + }, + "verb": { + "layout": "default", + "plugins": [ + "gulp-format-md" + ], + "related": { + "list": [ + "assemble", + "base", + "update", + "verb" + ] + }, + "reflinks": [ + "assemble", + "bach", + "base", + "composer", + "gulp", + "has-glob", + "is-valid-glob", + "micromatch", + "npm", + "scaffold", + "verb", + "vinyl" + ] + }, + "version": "3.1.0" +} \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/glob-parent/package.json b/tools/node_modules/eslint/node_modules/glob-parent/package.json new file mode 100644 index 00000000000000..fd6efef9308208 --- /dev/null +++ b/tools/node_modules/eslint/node_modules/glob-parent/package.json @@ -0,0 +1,47 @@ +{ + "author": { + "name": "Elan Shanker", + "url": "https://github.com/es128" + }, + "bugs": { + "url": "https://github.com/es128/glob-parent/issues" + }, + "bundleDependencies": false, + "dependencies": { + "is-glob": "^3.1.0", + "path-dirname": "^1.0.0" + }, + "deprecated": false, + "description": "Strips glob magic from a string to provide the parent directory path", + "devDependencies": { + "coveralls": "^2.11.2", + "istanbul": "^0.3.5", + "mocha": "^2.1.0" + }, + "files": [ + "index.js" + ], + "homepage": "https://github.com/es128/glob-parent", + "keywords": [ + "glob", + "parent", + "strip", + "path", + "dirname", + "directory", + "base", + "wildcard" + ], + "license": "ISC", + "main": "index.js", + "name": "glob-parent", + "repository": { + "type": "git", + "url": "git+https://github.com/es128/glob-parent.git" + }, + "scripts": { + "ci-test": "istanbul cover _mocha && cat ./coverage/lcov.info | coveralls", + "test": "istanbul test node_modules/mocha/bin/_mocha" + }, + "version": "3.1.0" +} \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/glob/LICENSE b/tools/node_modules/eslint/node_modules/glob/LICENSE index 19129e315fe593..42ca266df1d523 100644 --- a/tools/node_modules/eslint/node_modules/glob/LICENSE +++ b/tools/node_modules/eslint/node_modules/glob/LICENSE @@ -13,3 +13,9 @@ 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. + +## Glob Logo + +Glob's logo created by Tanya Brassie , licensed +under a Creative Commons Attribution-ShareAlike 4.0 International License +https://creativecommons.org/licenses/by-sa/4.0/ diff --git a/tools/node_modules/eslint/node_modules/glob/README.md b/tools/node_modules/eslint/node_modules/glob/README.md index baa1d1ba86506a..e71b967ea28809 100644 --- a/tools/node_modules/eslint/node_modules/glob/README.md +++ b/tools/node_modules/eslint/node_modules/glob/README.md @@ -7,7 +7,7 @@ Match files using the patterns the shell uses, like stars and stuff. This is a glob implementation in JavaScript. It uses the `minimatch` library to do its matching. -![](oh-my-glob.gif) +![](logo/glob.png) ## Usage @@ -347,6 +347,11 @@ Users are thus advised not to use a glob result as a guarantee of filesystem state in the face of rapid changes. For the vast majority of operations, this is never a problem. +## Glob Logo +Glob's logo was created by [Tanya Brassie](http://tanyabrassie.com/). Logo files can be found [here](https://github.com/isaacs/node-glob/tree/master/logo). + +The logo is licensed under a [Creative Commons Attribution-ShareAlike 4.0 International License](https://creativecommons.org/licenses/by-sa/4.0/). + ## Contributing Any change to behavior (including bugfixes) must come with a test. diff --git a/tools/node_modules/eslint/node_modules/glob/package.json b/tools/node_modules/eslint/node_modules/glob/package.json index f3927d95aee283..fca34f2f998d21 100644 --- a/tools/node_modules/eslint/node_modules/glob/package.json +++ b/tools/node_modules/eslint/node_modules/glob/package.json @@ -49,5 +49,5 @@ "test": "tap test/*.js --cov", "test-regen": "npm run profclean && TEST_REGEN=1 node test/00-setup.js" }, - "version": "7.1.3" + "version": "7.1.4" } \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/globals/globals.json b/tools/node_modules/eslint/node_modules/globals/globals.json index 65a4c7ec783dc4..6f5ac02f1eace7 100644 --- a/tools/node_modules/eslint/node_modules/globals/globals.json +++ b/tools/node_modules/eslint/node_modules/globals/globals.json @@ -21,6 +21,7 @@ "Float32Array": false, "Float64Array": false, "Function": false, + "globalThis": false, "hasOwnProperty": false, "Infinity": false, "Int16Array": false, diff --git a/tools/node_modules/eslint/node_modules/globals/package.json b/tools/node_modules/eslint/node_modules/globals/package.json index aa91e2f18e6680..ae094f3054063e 100644 --- a/tools/node_modules/eslint/node_modules/globals/package.json +++ b/tools/node_modules/eslint/node_modules/globals/package.json @@ -41,7 +41,7 @@ "scripts": { "test": "xo && ava" }, - "version": "11.11.0", + "version": "11.12.0", "xo": { "ignores": [ "get-browser-globals.js" diff --git a/tools/node_modules/eslint/node_modules/inquirer/LICENSE b/tools/node_modules/eslint/node_modules/inquirer/LICENSE new file mode 100644 index 00000000000000..8aae090e941ff9 --- /dev/null +++ b/tools/node_modules/eslint/node_modules/inquirer/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2012 Simon Boudrias + +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. \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/inquirer/README.md b/tools/node_modules/eslint/node_modules/inquirer/README.md index f24cb74444ddfd..1f03655f7914dc 100644 --- a/tools/node_modules/eslint/node_modules/inquirer/README.md +++ b/tools/node_modules/eslint/node_modules/inquirer/README.md @@ -113,13 +113,13 @@ prompt(questions).then(/* ... */); A question object is a `hash` containing question related values: -- **type**: (String) Type of the prompt. Defaults: `input` - Possible values: `input`, `confirm`, +- **type**: (String) Type of the prompt. Defaults: `input` - Possible values: `input`, `number`, `confirm`, `list`, `rawlist`, `expand`, `checkbox`, `password`, `editor` - **name**: (String) The name to use when storing the answer in the answers hash. If the name contains periods, it will define a path in the answers hash. - **message**: (String|Function) The question to print. If defined as a function, the first parameter will be the current inquirer session answers. Defaults to the value of `name` (followed by a colon). - **default**: (String|Number|Boolean|Array|Function) Default value(s) to use if nothing is entered, or a function that returns the default value(s). If defined as a function, the first parameter will be the current inquirer session answers. - **choices**: (Array|Function) Choices array or a function returning a choices array. If defined as a function, the first parameter will be the current inquirer session answers. - Array values can be simple `strings`, or `objects` containing a `name` (to display in list), a `value` (to save in the answers hash) and a `short` (to display after selection) properties. The choices array can also contain [a `Separator`](#separator). + Array values can be simple `numbers`, `strings`, or `objects` containing a `name` (to display in list), a `value` (to save in the answers hash) and a `short` (to display after selection) properties. The choices array can also contain [a `Separator`](#separator). - **validate**: (Function) Receive the user input and answers hash. Should return `true` if the value is valid, and an error message (`String`) otherwise. If `false` is returned, a default error message is provided. - **filter**: (Function) Receive the user input and return the filtered value to be used inside the program. The value returned will be added to the _Answers_ hash. - **transformer**: (Function) Receive the user input, answers hash and option flags, and return a transformed value to display to the user. The transformation only impacts what is shown while editing. It does not modify the answers hash. @@ -165,6 +165,7 @@ A key/value hash containing the client answers in each prompt. - **Value** (Depends on the prompt) - `confirm`: (Boolean) - `input` : User input (filtered if `filter` is defined) (String) + - `number`: User input (filtered if `filter` is defined) (Number) - `rawlist`, `list` : Selected choice value (or name if no value specified) (String) ### Separator @@ -257,6 +258,12 @@ Take `type`, `name`, `message`[, `default`, `filter`, `validate`, `transformer`] --- +#### Input - `{type: 'number'}` + +Take `type`, `name`, `message`[, `default`, `filter`, `validate`, `transformer`] properties. + +--- + #### Password - `{type: 'password'}` Take `type`, `name`, `message`, `mask`,[, `default`, `filter`, `validate`] properties. @@ -410,6 +417,11 @@ Prompt for fuzzy file/directory selection.

![inquirer-fuzzy-path](https://raw.githubusercontent.com/adelsz/inquirer-fuzzy-path/master/recording.gif) +[**inquirer-emoji**](https://github.com/tannerntannern/inquirer-emoji)
+Prompt for inputting emojis.
+
+![inquirer-emoji](https://github.com/tannerntannern/inquirer-emoji/raw/master/demo.gif) + [**inquirer-chalk-pipe**](https://github.com/LitoMore/inquirer-chalk-pipe)
Prompt for input chalk-pipe style strings

diff --git a/tools/node_modules/eslint/node_modules/inquirer/lib/objects/choice.js b/tools/node_modules/eslint/node_modules/inquirer/lib/objects/choice.js index 634e6bcd1d6636..76f93293329244 100644 --- a/tools/node_modules/eslint/node_modules/inquirer/lib/objects/choice.js +++ b/tools/node_modules/eslint/node_modules/inquirer/lib/objects/choice.js @@ -5,8 +5,8 @@ var _ = require('lodash'); * Choice object * Normalize input as choice object * @constructor - * @param {String|Object} val Choice value. If an object is passed, it should contains - * at least one of `value` or `name` property + * @param {Number|String|Object} val Choice value. If an object is passed, it should contains + * at least one of `value` or `name` property */ module.exports = class Choice { @@ -16,10 +16,10 @@ module.exports = class Choice { return val; } - if (_.isString(val)) { - this.name = val; + if (_.isString(val) || _.isNumber(val)) { + this.name = String(val); this.value = val; - this.short = val; + this.short = String(val); } else { _.extend(this, val, { name: val.name || val.value, diff --git a/tools/node_modules/eslint/node_modules/inquirer/lib/prompts/rawlist.js b/tools/node_modules/eslint/node_modules/inquirer/lib/prompts/rawlist.js index a628b8a746a84d..3c800f6151bc8e 100644 --- a/tools/node_modules/eslint/node_modules/inquirer/lib/prompts/rawlist.js +++ b/tools/node_modules/eslint/node_modules/inquirer/lib/prompts/rawlist.js @@ -92,7 +92,8 @@ class RawListPrompt extends Base { message += chalk.cyan(this.answer); } else { var choicesStr = renderChoices(this.opt.choices, this.selected); - message += this.paginator.paginate(choicesStr, this.selected, this.opt.pageSize); + message += + '\n' + this.paginator.paginate(choicesStr, this.selected, this.opt.pageSize); message += '\n Answer: '; } diff --git a/tools/node_modules/eslint/node_modules/inquirer/package.json b/tools/node_modules/eslint/node_modules/inquirer/package.json index 94d6a254376026..02c7b4a849cc6b 100644 --- a/tools/node_modules/eslint/node_modules/inquirer/package.json +++ b/tools/node_modules/eslint/node_modules/inquirer/package.json @@ -19,7 +19,7 @@ "run-async": "^2.2.0", "rxjs": "^6.4.0", "string-width": "^2.1.0", - "strip-ansi": "^5.0.0", + "strip-ansi": "^5.1.0", "through": "^2.3.6" }, "deprecated": false, @@ -40,7 +40,7 @@ "lib", "README.md" ], - "gitHead": "ad23da64f321689ff19ba354f4fed7f00acb3fbc", + "gitHead": "ee1cc700ad48f10fc304055ec733fb6be6c1d09c", "homepage": "https://github.com/SBoudrias/Inquirer.js#readme", "keywords": [ "command", @@ -63,5 +63,5 @@ "prepublishOnly": "cp ../../README.md .", "test": "nyc mocha test/**/* -r ./test/before" }, - "version": "6.2.2" + "version": "6.3.1" } \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/is-alphabetical/index.js b/tools/node_modules/eslint/node_modules/is-alphabetical/index.js index d65e531a16823f..26d3650ef060cd 100644 --- a/tools/node_modules/eslint/node_modules/is-alphabetical/index.js +++ b/tools/node_modules/eslint/node_modules/is-alphabetical/index.js @@ -2,8 +2,8 @@ module.exports = alphabetical -/* Check if the given character code, or the character - * code at the first character, is alphabetical. */ +// Check if the given character code, or the character code at the first +// character, is alphabetical. function alphabetical(character) { var code = typeof character === 'string' ? character.charCodeAt(0) : character diff --git a/tools/node_modules/eslint/node_modules/is-alphabetical/LICENSE b/tools/node_modules/eslint/node_modules/is-alphabetical/license similarity index 100% rename from tools/node_modules/eslint/node_modules/is-alphabetical/LICENSE rename to tools/node_modules/eslint/node_modules/is-alphabetical/license diff --git a/tools/node_modules/eslint/node_modules/is-alphabetical/package.json b/tools/node_modules/eslint/node_modules/is-alphabetical/package.json index aa9b1df336fed2..b45161352cb743 100644 --- a/tools/node_modules/eslint/node_modules/is-alphabetical/package.json +++ b/tools/node_modules/eslint/node_modules/is-alphabetical/package.json @@ -2,7 +2,7 @@ "author": { "name": "Titus Wormer", "email": "tituswormer@gmail.com", - "url": "http://wooorm.com" + "url": "https://wooorm.com" }, "bugs": { "url": "https://github.com/wooorm/is-alphabetical/issues" @@ -12,7 +12,7 @@ { "name": "Titus Wormer", "email": "tituswormer@gmail.com", - "url": "http://wooorm.com" + "url": "https://wooorm.com" } ], "dependencies": {}, @@ -20,13 +20,13 @@ "description": "Check if a character is alphabetical", "devDependencies": { "browserify": "^16.0.0", - "esmangle": "^1.0.1", - "nyc": "^11.0.0", + "nyc": "^14.0.0", "prettier": "^1.12.1", - "remark-cli": "^5.0.0", + "remark-cli": "^6.0.0", "remark-preset-wooorm": "^4.0.0", "tape": "^4.0.0", - "xo": "^0.20.0" + "tinyify": "^2.5.0", + "xo": "^0.24.0" }, "files": [ "index.js" @@ -66,20 +66,18 @@ }, "scripts": { "build": "npm run build-bundle && npm run build-mangle", - "build-bundle": "browserify index.js --bare -s isAlphabetical > is-alphabetical.js", - "build-mangle": "esmangle < is-alphabetical.js > is-alphabetical.min.js", - "format": "remark . -qfo && prettier --write '**/*.js' && xo --fix", + "build-bundle": "browserify -s isAlphabetical -o is-alphabetical.js", + "build-mangle": "browserify -s isAlphabetical -p tinyify -o is-alphabetical.min.js", + "format": "remark . -qfo && prettier --write \"**/*.js\" && xo --fix", "test": "npm run format && npm run build && npm run test-coverage", "test-api": "node test", "test-coverage": "nyc --reporter lcov tape test.js" }, - "version": "1.0.2", + "version": "1.0.3", "xo": { "prettier": true, "esnext": false, "rules": { - "no-var": "off", - "prefer-arrow-callback": "off", "capitalized-comments": "off" }, "ignores": [ diff --git a/tools/node_modules/eslint/node_modules/is-alphabetical/readme.md b/tools/node_modules/eslint/node_modules/is-alphabetical/readme.md index 42952e9c89b05c..8e837bbfbcc43a 100644 --- a/tools/node_modules/eslint/node_modules/is-alphabetical/readme.md +++ b/tools/node_modules/eslint/node_modules/is-alphabetical/readme.md @@ -1,4 +1,9 @@ -# is-alphabetical [![Build Status][travis-badge]][travis] [![Coverage Status][codecov-badge]][codecov] +# is-alphabetical + +[![Build][build-badge]][build] +[![Coverage][coverage-badge]][coverage] +[![Downloads][downloads-badge]][downloads] +[![Size][size-badge]][size] Check if a character is alphabetical. @@ -42,16 +47,24 @@ code at the first position (`string`), is alphabetical. -[travis-badge]: https://img.shields.io/travis/wooorm/is-alphabetical.svg +[build-badge]: https://img.shields.io/travis/wooorm/is-alphabetical.svg + +[build]: https://travis-ci.org/wooorm/is-alphabetical + +[coverage-badge]: https://img.shields.io/codecov/c/github/wooorm/is-alphabetical.svg + +[coverage]: https://codecov.io/github/wooorm/is-alphabetical + +[downloads-badge]: https://img.shields.io/npm/dm/is-alphabetical.svg -[travis]: https://travis-ci.org/wooorm/is-alphabetical +[downloads]: https://www.npmjs.com/package/is-alphabetical -[codecov-badge]: https://img.shields.io/codecov/c/github/wooorm/is-alphabetical.svg +[size-badge]: https://img.shields.io/bundlephobia/minzip/is-alphabetical.svg -[codecov]: https://codecov.io/github/wooorm/is-alphabetical +[size]: https://bundlephobia.com/result?p=is-alphabetical [npm]: https://docs.npmjs.com/cli/install -[license]: LICENSE +[license]: license -[author]: http://wooorm.com +[author]: https://wooorm.com diff --git a/tools/node_modules/eslint/node_modules/is-alphanumerical/index.js b/tools/node_modules/eslint/node_modules/is-alphanumerical/index.js index 707033ee391f5a..cd5edef3dbf03c 100644 --- a/tools/node_modules/eslint/node_modules/is-alphanumerical/index.js +++ b/tools/node_modules/eslint/node_modules/is-alphanumerical/index.js @@ -5,8 +5,8 @@ var decimal = require('is-decimal') module.exports = alphanumerical -/* Check if the given character code, or the character - * code at the first character, is alphanumerical. */ +// Check if the given character code, or the character code at the first +// character, is alphanumerical. function alphanumerical(character) { return alphabetical(character) || decimal(character) } diff --git a/tools/node_modules/eslint/node_modules/is-alphanumerical/LICENSE b/tools/node_modules/eslint/node_modules/is-alphanumerical/license similarity index 100% rename from tools/node_modules/eslint/node_modules/is-alphanumerical/LICENSE rename to tools/node_modules/eslint/node_modules/is-alphanumerical/license diff --git a/tools/node_modules/eslint/node_modules/is-alphanumerical/package.json b/tools/node_modules/eslint/node_modules/is-alphanumerical/package.json index 891025bbcf9453..4373f03fd0b6bc 100644 --- a/tools/node_modules/eslint/node_modules/is-alphanumerical/package.json +++ b/tools/node_modules/eslint/node_modules/is-alphanumerical/package.json @@ -2,7 +2,7 @@ "author": { "name": "Titus Wormer", "email": "tituswormer@gmail.com", - "url": "http://wooorm.com" + "url": "https://wooorm.com" }, "bugs": { "url": "https://github.com/wooorm/is-alphanumerical/issues" @@ -12,7 +12,7 @@ { "name": "Titus Wormer", "email": "tituswormer@gmail.com", - "url": "http://wooorm.com" + "url": "https://wooorm.com" } ], "dependencies": { @@ -23,13 +23,13 @@ "description": "Check if a character is alphanumerical", "devDependencies": { "browserify": "^16.0.0", - "esmangle": "^1.0.1", - "nyc": "^11.0.0", + "nyc": "^14.0.0", "prettier": "^1.12.1", - "remark-cli": "^5.0.0", + "remark-cli": "^6.0.0", "remark-preset-wooorm": "^4.0.0", "tape": "^4.0.0", - "xo": "^0.20.0" + "tinyify": "^2.5.0", + "xo": "^0.24.0" }, "files": [ "index.js" @@ -71,21 +71,17 @@ }, "scripts": { "build": "npm run build-bundle && npm run build-mangle", - "build-bundle": "browserify index.js --bare -s isAlphanumerical > is-alphanumerical.js", - "build-mangle": "esmangle < is-alphanumerical.js > is-alphanumerical.min.js", - "format": "remark . -qfo && prettier --write '**/*.js' && xo --fix", + "build-bundle": "browserify . -s isAlphanumerical -o is-alphanumerical.js", + "build-mangle": "browserify . -s isAlphanumerical -p tinyify -o is-alphanumerical.min.js", + "format": "remark . -qfo && prettier --write \"**/*.js\" && xo --fix", "test": "npm run format && npm run build && npm run test-coverage", "test-api": "node test", "test-coverage": "nyc --reporter lcov tape test.js" }, - "version": "1.0.2", + "version": "1.0.3", "xo": { "prettier": true, "esnext": false, - "rules": { - "no-var": "off", - "prefer-arrow-callback": "off" - }, "ignores": [ "is-alphanumerical.js" ] diff --git a/tools/node_modules/eslint/node_modules/is-alphanumerical/readme.md b/tools/node_modules/eslint/node_modules/is-alphanumerical/readme.md index d5c2013368bb1c..bcba8ced6a9c9f 100644 --- a/tools/node_modules/eslint/node_modules/is-alphanumerical/readme.md +++ b/tools/node_modules/eslint/node_modules/is-alphanumerical/readme.md @@ -1,4 +1,9 @@ -# is-alphanumerical [![Build Status][travis-badge]][travis] [![Coverage Status][codecov-badge]][codecov] +# is-alphanumerical + +[![Build][build-badge]][build] +[![Coverage][coverage-badge]][coverage] +[![Downloads][downloads-badge]][downloads] +[![Size][size-badge]][size] Check if a character is alphanumerical (`[a-zA-Z0-9]`). @@ -43,16 +48,24 @@ code at the first position (`string`), is alphanumerical. -[travis-badge]: https://img.shields.io/travis/wooorm/is-alphanumerical.svg +[build-badge]: https://img.shields.io/travis/wooorm/is-alphanumerical.svg + +[build]: https://travis-ci.org/wooorm/is-alphanumerical + +[coverage-badge]: https://img.shields.io/codecov/c/github/wooorm/is-alphanumerical.svg + +[coverage]: https://codecov.io/github/wooorm/is-alphanumerical + +[downloads-badge]: https://img.shields.io/npm/dm/is-alphanumerical.svg -[travis]: https://travis-ci.org/wooorm/is-alphanumerical +[downloads]: https://www.npmjs.com/package/is-alphanumerical -[codecov-badge]: https://img.shields.io/codecov/c/github/wooorm/is-alphanumerical.svg +[size-badge]: https://img.shields.io/bundlephobia/minzip/is-alphanumerical.svg -[codecov]: https://codecov.io/github/wooorm/is-alphanumerical +[size]: https://bundlephobia.com/result?p=is-alphanumerical [npm]: https://docs.npmjs.com/cli/install -[license]: LICENSE +[license]: license -[author]: http://wooorm.com +[author]: https://wooorm.com diff --git a/tools/node_modules/eslint/node_modules/is-decimal/index.js b/tools/node_modules/eslint/node_modules/is-decimal/index.js index 0414800d1b90eb..a522104e5cf970 100644 --- a/tools/node_modules/eslint/node_modules/is-decimal/index.js +++ b/tools/node_modules/eslint/node_modules/is-decimal/index.js @@ -2,8 +2,8 @@ module.exports = decimal -/* Check if the given character code, or the character - * code at the first character, is decimal. */ +// Check if the given character code, or the character code at the first +// character, is decimal. function decimal(character) { var code = typeof character === 'string' ? character.charCodeAt(0) : character diff --git a/tools/node_modules/eslint/node_modules/is-decimal/LICENSE b/tools/node_modules/eslint/node_modules/is-decimal/license similarity index 100% rename from tools/node_modules/eslint/node_modules/is-decimal/LICENSE rename to tools/node_modules/eslint/node_modules/is-decimal/license diff --git a/tools/node_modules/eslint/node_modules/is-decimal/package.json b/tools/node_modules/eslint/node_modules/is-decimal/package.json index 6a4727e3649d32..be7491e757265b 100644 --- a/tools/node_modules/eslint/node_modules/is-decimal/package.json +++ b/tools/node_modules/eslint/node_modules/is-decimal/package.json @@ -2,7 +2,7 @@ "author": { "name": "Titus Wormer", "email": "tituswormer@gmail.com", - "url": "http://wooorm.com" + "url": "https://wooorm.com" }, "bugs": { "url": "https://github.com/wooorm/is-decimal/issues" @@ -12,7 +12,7 @@ { "name": "Titus Wormer", "email": "tituswormer@gmail.com", - "url": "http://wooorm.com" + "url": "https://wooorm.com" } ], "dependencies": {}, @@ -20,13 +20,13 @@ "description": "Check if a character is decimal", "devDependencies": { "browserify": "^16.0.0", - "esmangle": "^1.0.1", - "nyc": "^11.0.0", + "nyc": "^14.0.0", "prettier": "^1.12.1", - "remark-cli": "^5.0.0", + "remark-cli": "^6.0.0", "remark-preset-wooorm": "^4.0.0", "tape": "^4.0.0", - "xo": "^0.20.0" + "tinyify": "^2.5.0", + "xo": "^0.24.0" }, "files": [ "index.js" @@ -66,21 +66,17 @@ }, "scripts": { "build": "npm run build-bundle && npm run build-mangle", - "build-bundle": "browserify index.js --bare -s isDecimal > is-decimal.js", - "build-mangle": "esmangle < is-decimal.js > is-decimal.min.js", - "format": "remark . -qfo && prettier --write '**/*.js' && xo --fix", + "build-bundle": "browserify . -s isDecimal -o is-decimal.js", + "build-mangle": "browserify . -s isDecimal -p tinyifgy -o is-decimal.min.js", + "format": "remark . -qfo && prettier --write \"**/*.js\" && xo --fix", "test": "npm run format && npm run build && npm run test-coverage", "test-api": "node test", "test-coverage": "nyc --reporter lcov tape test.js" }, - "version": "1.0.2", + "version": "1.0.3", "xo": { "prettier": true, "esnext": false, - "rules": { - "no-var": "off", - "prefer-arrow-callback": "off" - }, "ignores": [ "is-decimal.js" ] diff --git a/tools/node_modules/eslint/node_modules/is-decimal/readme.md b/tools/node_modules/eslint/node_modules/is-decimal/readme.md index 48464b6a457641..fe2e0238c18757 100644 --- a/tools/node_modules/eslint/node_modules/is-decimal/readme.md +++ b/tools/node_modules/eslint/node_modules/is-decimal/readme.md @@ -1,4 +1,9 @@ -# is-decimal [![Build Status][travis-badge]][travis] [![Coverage Status][codecov-badge]][codecov] +# is-decimal + +[![Build][build-badge]][build] +[![Coverage][coverage-badge]][coverage] +[![Downloads][downloads-badge]][downloads] +[![Size][size-badge]][size] Check if a character is decimal. @@ -41,16 +46,24 @@ code at the first position (`string`), is decimal. -[travis-badge]: https://img.shields.io/travis/wooorm/is-decimal.svg +[build-badge]: https://img.shields.io/travis/wooorm/is-decimal.svg + +[build]: https://travis-ci.org/wooorm/is-decimal + +[coverage-badge]: https://img.shields.io/codecov/c/github/wooorm/is-decimal.svg + +[coverage]: https://codecov.io/github/wooorm/is-decimal + +[downloads-badge]: https://img.shields.io/npm/dm/is-decimal.svg -[travis]: https://travis-ci.org/wooorm/is-decimal +[downloads]: https://www.npmjs.com/package/is-decimal -[codecov-badge]: https://img.shields.io/codecov/c/github/wooorm/is-decimal.svg +[size-badge]: https://img.shields.io/bundlephobia/minzip/is-decimal.svg -[codecov]: https://codecov.io/github/wooorm/is-decimal +[size]: https://bundlephobia.com/result?p=is-decimal [npm]: https://docs.npmjs.com/cli/install -[license]: LICENSE +[license]: license -[author]: http://wooorm.com +[author]: https://wooorm.com diff --git a/tools/node_modules/eslint/node_modules/is-extglob/LICENSE b/tools/node_modules/eslint/node_modules/is-extglob/LICENSE new file mode 100644 index 00000000000000..842218cf09a202 --- /dev/null +++ b/tools/node_modules/eslint/node_modules/is-extglob/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-2016, Jon Schlinkert + +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/is-extglob/README.md b/tools/node_modules/eslint/node_modules/is-extglob/README.md new file mode 100644 index 00000000000000..0416af5c326983 --- /dev/null +++ b/tools/node_modules/eslint/node_modules/is-extglob/README.md @@ -0,0 +1,107 @@ +# is-extglob [![NPM version](https://img.shields.io/npm/v/is-extglob.svg?style=flat)](https://www.npmjs.com/package/is-extglob) [![NPM downloads](https://img.shields.io/npm/dm/is-extglob.svg?style=flat)](https://npmjs.org/package/is-extglob) [![Build Status](https://img.shields.io/travis/jonschlinkert/is-extglob.svg?style=flat)](https://travis-ci.org/jonschlinkert/is-extglob) + +> Returns true if a string has an extglob. + +## Install + +Install with [npm](https://www.npmjs.com/): + +```sh +$ npm install --save is-extglob +``` + +## Usage + +```js +var isExtglob = require('is-extglob'); +``` + +**True** + +```js +isExtglob('?(abc)'); +isExtglob('@(abc)'); +isExtglob('!(abc)'); +isExtglob('*(abc)'); +isExtglob('+(abc)'); +``` + +**False** + +Escaped extglobs: + +```js +isExtglob('\\?(abc)'); +isExtglob('\\@(abc)'); +isExtglob('\\!(abc)'); +isExtglob('\\*(abc)'); +isExtglob('\\+(abc)'); +``` + +Everything else... + +```js +isExtglob('foo.js'); +isExtglob('!foo.js'); +isExtglob('*.js'); +isExtglob('**/abc.js'); +isExtglob('abc/*.js'); +isExtglob('abc/(aaa|bbb).js'); +isExtglob('abc/[a-z].js'); +isExtglob('abc/{a,b}.js'); +isExtglob('abc/?.js'); +isExtglob('abc.js'); +isExtglob('abc/def/ghi.js'); +``` + +## History + +**v2.0** + +Adds support for escaping. Escaped exglobs no longer return true. + +## About + +### Related projects + +* [has-glob](https://www.npmjs.com/package/has-glob): Returns `true` if an array has a glob pattern. | [homepage](https://github.com/jonschlinkert/has-glob "Returns `true` if an array has a glob pattern.") +* [is-glob](https://www.npmjs.com/package/is-glob): Returns `true` if the given string looks like a glob pattern or an extglob pattern… [more](https://github.com/jonschlinkert/is-glob) | [homepage](https://github.com/jonschlinkert/is-glob "Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a bet") +* [micromatch](https://www.npmjs.com/package/micromatch): Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch. | [homepage](https://github.com/jonschlinkert/micromatch "Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch.") + +### Contributing + +Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). + +### Building docs + +_(This document was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme) (a [verb](https://github.com/verbose/verb) generator), please don't edit the readme directly. Any changes to the readme must be made in [.verb.md](.verb.md).)_ + +To generate the readme and API documentation with [verb](https://github.com/verbose/verb): + +```sh +$ npm install -g verb verb-generate-readme && verb +``` + +### Running tests + +Install dev dependencies: + +```sh +$ npm install -d && npm test +``` + +### Author + +**Jon Schlinkert** + +* [github/jonschlinkert](https://github.com/jonschlinkert) +* [twitter/jonschlinkert](http://twitter.com/jonschlinkert) + +### License + +Copyright © 2016, [Jon Schlinkert](https://github.com/jonschlinkert). +Released under the [MIT license](https://github.com/jonschlinkert/is-extglob/blob/master/LICENSE). + +*** + +_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.1.31, on October 12, 2016._ \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/is-extglob/index.js b/tools/node_modules/eslint/node_modules/is-extglob/index.js new file mode 100644 index 00000000000000..c1d986fc512030 --- /dev/null +++ b/tools/node_modules/eslint/node_modules/is-extglob/index.js @@ -0,0 +1,20 @@ +/*! + * is-extglob + * + * Copyright (c) 2014-2016, Jon Schlinkert. + * Licensed under the MIT License. + */ + +module.exports = function isExtglob(str) { + if (typeof str !== 'string' || str === '') { + return false; + } + + var match; + while ((match = /(\\).|([@?!+*]\(.*\))/g.exec(str))) { + if (match[2]) return true; + str = str.slice(match.index + match[0].length); + } + + return false; +}; diff --git a/tools/node_modules/eslint/node_modules/is-extglob/package.json b/tools/node_modules/eslint/node_modules/is-extglob/package.json new file mode 100644 index 00000000000000..3ae794888e29c7 --- /dev/null +++ b/tools/node_modules/eslint/node_modules/is-extglob/package.json @@ -0,0 +1,77 @@ +{ + "author": { + "name": "Jon Schlinkert", + "url": "https://github.com/jonschlinkert" + }, + "bugs": { + "url": "https://github.com/jonschlinkert/is-extglob/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Returns true if a string has an extglob.", + "devDependencies": { + "gulp-format-md": "^0.1.10", + "mocha": "^3.0.2" + }, + "engines": { + "node": ">=0.10.0" + }, + "files": [ + "index.js" + ], + "homepage": "https://github.com/jonschlinkert/is-extglob", + "keywords": [ + "bash", + "braces", + "check", + "exec", + "expression", + "extglob", + "glob", + "globbing", + "globstar", + "is", + "match", + "matches", + "pattern", + "regex", + "regular", + "string", + "test" + ], + "license": "MIT", + "main": "index.js", + "name": "is-extglob", + "repository": { + "type": "git", + "url": "git+https://github.com/jonschlinkert/is-extglob.git" + }, + "scripts": { + "test": "mocha" + }, + "verb": { + "toc": false, + "layout": "default", + "tasks": [ + "readme" + ], + "plugins": [ + "gulp-format-md" + ], + "related": { + "list": [ + "has-glob", + "is-glob", + "micromatch" + ] + }, + "reflinks": [ + "verb", + "verb-generate-readme" + ], + "lint": { + "reflinks": true + } + }, + "version": "2.1.1" +} \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/is-glob/LICENSE b/tools/node_modules/eslint/node_modules/is-glob/LICENSE new file mode 100644 index 00000000000000..3f2eca18f1bc0f --- /dev/null +++ b/tools/node_modules/eslint/node_modules/is-glob/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-2017, Jon Schlinkert. + +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/is-glob/README.md b/tools/node_modules/eslint/node_modules/is-glob/README.md new file mode 100644 index 00000000000000..7723e931f42e15 --- /dev/null +++ b/tools/node_modules/eslint/node_modules/is-glob/README.md @@ -0,0 +1,206 @@ +# is-glob [![NPM version](https://img.shields.io/npm/v/is-glob.svg?style=flat)](https://www.npmjs.com/package/is-glob) [![NPM monthly downloads](https://img.shields.io/npm/dm/is-glob.svg?style=flat)](https://npmjs.org/package/is-glob) [![NPM total downloads](https://img.shields.io/npm/dt/is-glob.svg?style=flat)](https://npmjs.org/package/is-glob) [![Linux Build Status](https://img.shields.io/travis/micromatch/is-glob.svg?style=flat&label=Travis)](https://travis-ci.org/micromatch/is-glob) [![Windows Build Status](https://img.shields.io/appveyor/ci/micromatch/is-glob.svg?style=flat&label=AppVeyor)](https://ci.appveyor.com/project/micromatch/is-glob) + +> Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a better user experience. + +Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. + +## Install + +Install with [npm](https://www.npmjs.com/): + +```sh +$ npm install --save is-glob +``` + +You might also be interested in [is-valid-glob](https://github.com/jonschlinkert/is-valid-glob) and [has-glob](https://github.com/jonschlinkert/has-glob). + +## Usage + +```js +var isGlob = require('is-glob'); +``` + +### Default behavior + +**True** + +Patterns that have glob characters or regex patterns will return `true`: + +```js +isGlob('!foo.js'); +isGlob('*.js'); +isGlob('**/abc.js'); +isGlob('abc/*.js'); +isGlob('abc/(aaa|bbb).js'); +isGlob('abc/[a-z].js'); +isGlob('abc/{a,b}.js'); +//=> true +``` + +Extglobs + +```js +isGlob('abc/@(a).js'); +isGlob('abc/!(a).js'); +isGlob('abc/+(a).js'); +isGlob('abc/*(a).js'); +isGlob('abc/?(a).js'); +//=> true +``` + +**False** + +Escaped globs or extglobs return `false`: + +```js +isGlob('abc/\\@(a).js'); +isGlob('abc/\\!(a).js'); +isGlob('abc/\\+(a).js'); +isGlob('abc/\\*(a).js'); +isGlob('abc/\\?(a).js'); +isGlob('\\!foo.js'); +isGlob('\\*.js'); +isGlob('\\*\\*/abc.js'); +isGlob('abc/\\*.js'); +isGlob('abc/\\(aaa|bbb).js'); +isGlob('abc/\\[a-z].js'); +isGlob('abc/\\{a,b}.js'); +//=> false +``` + +Patterns that do not have glob patterns return `false`: + +```js +isGlob('abc.js'); +isGlob('abc/def/ghi.js'); +isGlob('foo.js'); +isGlob('abc/@.js'); +isGlob('abc/+.js'); +isGlob('abc/?.js'); +isGlob(); +isGlob(null); +//=> false +``` + +Arrays are also `false` (If you want to check if an array has a glob pattern, use [has-glob](https://github.com/jonschlinkert/has-glob)): + +```js +isGlob(['**/*.js']); +isGlob(['foo.js']); +//=> false +``` + +### Option strict + +When `options.strict === false` the behavior is less strict in determining if a pattern is a glob. Meaning that +some patterns that would return `false` may return `true`. This is done so that matching libraries like [micromatch](https://github.com/micromatch/micromatch) have a chance at determining if the pattern is a glob or not. + +**True** + +Patterns that have glob characters or regex patterns will return `true`: + +```js +isGlob('!foo.js', {strict: false}); +isGlob('*.js', {strict: false}); +isGlob('**/abc.js', {strict: false}); +isGlob('abc/*.js', {strict: false}); +isGlob('abc/(aaa|bbb).js', {strict: false}); +isGlob('abc/[a-z].js', {strict: false}); +isGlob('abc/{a,b}.js', {strict: false}); +//=> true +``` + +Extglobs + +```js +isGlob('abc/@(a).js', {strict: false}); +isGlob('abc/!(a).js', {strict: false}); +isGlob('abc/+(a).js', {strict: false}); +isGlob('abc/*(a).js', {strict: false}); +isGlob('abc/?(a).js', {strict: false}); +//=> true +``` + +**False** + +Escaped globs or extglobs return `false`: + +```js +isGlob('\\!foo.js', {strict: false}); +isGlob('\\*.js', {strict: false}); +isGlob('\\*\\*/abc.js', {strict: false}); +isGlob('abc/\\*.js', {strict: false}); +isGlob('abc/\\(aaa|bbb).js', {strict: false}); +isGlob('abc/\\[a-z].js', {strict: false}); +isGlob('abc/\\{a,b}.js', {strict: false}); +//=> false +``` + +## About + +
+Contributing + +Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). + +
+ +
+Running Tests + +Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: + +```sh +$ npm install && npm test +``` + +
+ +
+Building docs + +_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ + +To generate the readme, run the following command: + +```sh +$ npm install -g verbose/verb#dev verb-generate-readme && verb +``` + +
+ +### Related projects + +You might also be interested in these projects: + +* [assemble](https://www.npmjs.com/package/assemble): Get the rocks out of your socks! Assemble makes you fast at creating web projects… [more](https://github.com/assemble/assemble) | [homepage](https://github.com/assemble/assemble "Get the rocks out of your socks! Assemble makes you fast at creating web projects. Assemble is used by thousands of projects for rapid prototyping, creating themes, scaffolds, boilerplates, e-books, UI components, API documentation, blogs, building websit") +* [base](https://www.npmjs.com/package/base): Framework for rapidly creating high quality, server-side node.js applications, using plugins like building blocks | [homepage](https://github.com/node-base/base "Framework for rapidly creating high quality, server-side node.js applications, using plugins like building blocks") +* [update](https://www.npmjs.com/package/update): Be scalable! Update is a new, open source developer framework and CLI for automating updates… [more](https://github.com/update/update) | [homepage](https://github.com/update/update "Be scalable! Update is a new, open source developer framework and CLI for automating updates of any kind in code projects.") +* [verb](https://www.npmjs.com/package/verb): Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used… [more](https://github.com/verbose/verb) | [homepage](https://github.com/verbose/verb "Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used on hundreds of projects of all sizes to generate everything from API docs to readmes.") + +### Contributors + +| **Commits** | **Contributor** | +| --- | --- | +| 47 | [jonschlinkert](https://github.com/jonschlinkert) | +| 5 | [doowb](https://github.com/doowb) | +| 1 | [phated](https://github.com/phated) | +| 1 | [danhper](https://github.com/danhper) | +| 1 | [paulmillr](https://github.com/paulmillr) | + +### Author + +**Jon Schlinkert** + +* [GitHub Profile](https://github.com/jonschlinkert) +* [Twitter Profile](https://twitter.com/jonschlinkert) +* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) + +### License + +Copyright © 2019, [Jon Schlinkert](https://github.com/jonschlinkert). +Released under the [MIT License](LICENSE). + +*** + +_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on March 27, 2019._ \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/is-glob/index.js b/tools/node_modules/eslint/node_modules/is-glob/index.js new file mode 100644 index 00000000000000..55826510ce7672 --- /dev/null +++ b/tools/node_modules/eslint/node_modules/is-glob/index.js @@ -0,0 +1,48 @@ +/*! + * is-glob + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ + +var isExtglob = require('is-extglob'); +var chars = { '{': '}', '(': ')', '[': ']'}; +var strictRegex = /\\(.)|(^!|\*|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\)|\([^|]+\|[^\\)]+\))/; +var relaxedRegex = /\\(.)|(^!|[*?{}()[\]]|\(\?)/; + +module.exports = function isGlob(str, options) { + if (typeof str !== 'string' || str === '') { + return false; + } + + if (isExtglob(str)) { + return true; + } + + var regex = strictRegex; + var match; + + // optionally relax regex + if (options && options.strict === false) { + regex = relaxedRegex; + } + + while ((match = regex.exec(str))) { + if (match[2]) return true; + var idx = match.index + match[0].length; + + // if an open bracket/brace/paren is escaped, + // set the index to the next closing character + var open = match[1]; + var close = open ? chars[open] : null; + if (open && close) { + var n = str.indexOf(close, idx); + if (n !== -1) { + idx = n + 1; + } + } + + str = str.slice(idx); + } + return false; +}; diff --git a/tools/node_modules/eslint/node_modules/is-glob/package.json b/tools/node_modules/eslint/node_modules/is-glob/package.json new file mode 100644 index 00000000000000..d8973094f63003 --- /dev/null +++ b/tools/node_modules/eslint/node_modules/is-glob/package.json @@ -0,0 +1,98 @@ +{ + "author": { + "name": "Jon Schlinkert", + "url": "https://github.com/jonschlinkert" + }, + "bugs": { + "url": "https://github.com/micromatch/is-glob/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Brian Woodward", + "url": "https://twitter.com/doowb" + }, + { + "name": "Daniel Perez", + "url": "https://tuvistavie.com" + }, + { + "name": "Jon Schlinkert", + "url": "http://twitter.com/jonschlinkert" + } + ], + "dependencies": { + "is-extglob": "^2.1.1" + }, + "deprecated": false, + "description": "Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a better user experience.", + "devDependencies": { + "gulp-format-md": "^0.1.10", + "mocha": "^3.0.2" + }, + "engines": { + "node": ">=0.10.0" + }, + "files": [ + "index.js" + ], + "homepage": "https://github.com/micromatch/is-glob", + "keywords": [ + "bash", + "braces", + "check", + "exec", + "expression", + "extglob", + "glob", + "globbing", + "globstar", + "is", + "match", + "matches", + "pattern", + "regex", + "regular", + "string", + "test" + ], + "license": "MIT", + "main": "index.js", + "name": "is-glob", + "repository": { + "type": "git", + "url": "git+https://github.com/micromatch/is-glob.git" + }, + "scripts": { + "test": "mocha" + }, + "verb": { + "layout": "default", + "plugins": [ + "gulp-format-md" + ], + "related": { + "list": [ + "assemble", + "base", + "update", + "verb" + ] + }, + "reflinks": [ + "assemble", + "bach", + "base", + "composer", + "gulp", + "has-glob", + "is-valid-glob", + "micromatch", + "npm", + "scaffold", + "verb", + "vinyl" + ] + }, + "version": "4.0.1" +} \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/is-hexadecimal/index.js b/tools/node_modules/eslint/node_modules/is-hexadecimal/index.js index 40b6a111ffa974..567c9d1c077737 100644 --- a/tools/node_modules/eslint/node_modules/is-hexadecimal/index.js +++ b/tools/node_modules/eslint/node_modules/is-hexadecimal/index.js @@ -2,8 +2,8 @@ module.exports = hexadecimal -/* Check if the given character code, or the character - * code at the first character, is hexadecimal. */ +// Check if the given character code, or the character code at the first +// character, is hexadecimal. function hexadecimal(character) { var code = typeof character === 'string' ? character.charCodeAt(0) : character diff --git a/tools/node_modules/eslint/node_modules/is-hexadecimal/LICENSE b/tools/node_modules/eslint/node_modules/is-hexadecimal/license similarity index 100% rename from tools/node_modules/eslint/node_modules/is-hexadecimal/LICENSE rename to tools/node_modules/eslint/node_modules/is-hexadecimal/license diff --git a/tools/node_modules/eslint/node_modules/is-hexadecimal/package.json b/tools/node_modules/eslint/node_modules/is-hexadecimal/package.json index e4e62748f91880..a1ba478c0072b3 100644 --- a/tools/node_modules/eslint/node_modules/is-hexadecimal/package.json +++ b/tools/node_modules/eslint/node_modules/is-hexadecimal/package.json @@ -2,7 +2,7 @@ "author": { "name": "Titus Wormer", "email": "tituswormer@gmail.com", - "url": "http://wooorm.com" + "url": "https://wooorm.com" }, "bugs": { "url": "https://github.com/wooorm/is-hexadecimal/issues" @@ -12,7 +12,7 @@ { "name": "Titus Wormer", "email": "tituswormer@gmail.com", - "url": "http://wooorm.com" + "url": "https://wooorm.com" } ], "dependencies": {}, @@ -20,13 +20,13 @@ "description": "Check if a character is hexadecimal", "devDependencies": { "browserify": "^16.0.0", - "esmangle": "^1.0.1", - "nyc": "^11.0.0", + "nyc": "^14.0.0", "prettier": "^1.12.1", - "remark-cli": "^5.0.0", + "remark-cli": "^6.0.0", "remark-preset-wooorm": "^4.0.0", "tape": "^4.0.0", - "xo": "^0.20.0" + "tinyify": "^2.5.0", + "xo": "^0.24.0" }, "files": [ "index.js" @@ -66,21 +66,17 @@ }, "scripts": { "build": "npm run build-bundle && npm run build-mangle", - "build-bundle": "browserify index.js --bare -s isHexadecimal > is-hexadecimal.js", - "build-mangle": "esmangle < is-hexadecimal.js > is-hexadecimal.min.js", - "format": "remark . -qfo && prettier --write '**/*.js' && xo --fix", + "build-bundle": "browserify . -s isHexadecimal -o is-hexadecimal.js", + "build-mangle": "browserify . -s isHexadecimal -p tinyify -o is-hexadecimal.min.js", + "format": "remark . -qfo && prettier --write \"**/*.js\" && xo --fix", "test": "npm run format && npm run build && npm run test-coverage", "test-api": "node test", "test-coverage": "nyc --reporter lcov tape test.js" }, - "version": "1.0.2", + "version": "1.0.3", "xo": { "prettier": true, "esnext": false, - "rules": { - "no-var": "off", - "prefer-arrow-callback": "off" - }, "ignores": [ "is-hexadecimal.js" ] diff --git a/tools/node_modules/eslint/node_modules/is-hexadecimal/readme.md b/tools/node_modules/eslint/node_modules/is-hexadecimal/readme.md index 5bcf07a40dbfcd..3fc4883b88891c 100644 --- a/tools/node_modules/eslint/node_modules/is-hexadecimal/readme.md +++ b/tools/node_modules/eslint/node_modules/is-hexadecimal/readme.md @@ -1,4 +1,9 @@ -# is-hexadecimal [![Build Status][travis-badge]][travis] [![Coverage Status][codecov-badge]][codecov] +# is-hexadecimal + +[![Build][build-badge]][build] +[![Coverage][coverage-badge]][coverage] +[![Downloads][downloads-badge]][downloads] +[![Size][size-badge]][size] Check if a character is hexadecimal. @@ -42,16 +47,24 @@ code at the first position (`string`), is hexadecimal. -[travis-badge]: https://img.shields.io/travis/wooorm/is-hexadecimal.svg +[build-badge]: https://img.shields.io/travis/wooorm/is-hexadecimal.svg + +[build]: https://travis-ci.org/wooorm/is-hexadecimal + +[coverage-badge]: https://img.shields.io/codecov/c/github/wooorm/is-hexadecimal.svg + +[coverage]: https://codecov.io/github/wooorm/is-hexadecimal + +[downloads-badge]: https://img.shields.io/npm/dm/is-hexadecimal.svg -[travis]: https://travis-ci.org/wooorm/is-hexadecimal +[downloads]: https://www.npmjs.com/package/is-hexadecimal -[codecov-badge]: https://img.shields.io/codecov/c/github/wooorm/is-hexadecimal.svg +[size-badge]: https://img.shields.io/bundlephobia/minzip/is-hexadecimal.svg -[codecov]: https://codecov.io/github/wooorm/is-hexadecimal +[size]: https://bundlephobia.com/result?p=is-hexadecimal [npm]: https://docs.npmjs.com/cli/install -[license]: LICENSE +[license]: license -[author]: http://wooorm.com +[author]: https://wooorm.com diff --git a/tools/node_modules/eslint/node_modules/is-whitespace-character/index.js b/tools/node_modules/eslint/node_modules/is-whitespace-character/index.js index 93db585d638668..801c19f0d8df82 100644 --- a/tools/node_modules/eslint/node_modules/is-whitespace-character/index.js +++ b/tools/node_modules/eslint/node_modules/is-whitespace-character/index.js @@ -5,8 +5,8 @@ module.exports = whitespace var fromCode = String.fromCharCode var re = /\s/ -/* Check if the given character code, or the character - * code at the first character, is a whitespace character. */ +// Check if the given character code, or the character code at the first +// character, is a whitespace character. function whitespace(character) { return re.test( typeof character === 'number' ? fromCode(character) : character.charAt(0) diff --git a/tools/node_modules/eslint/node_modules/is-whitespace-character/LICENSE b/tools/node_modules/eslint/node_modules/is-whitespace-character/license similarity index 100% rename from tools/node_modules/eslint/node_modules/is-whitespace-character/LICENSE rename to tools/node_modules/eslint/node_modules/is-whitespace-character/license diff --git a/tools/node_modules/eslint/node_modules/is-whitespace-character/package.json b/tools/node_modules/eslint/node_modules/is-whitespace-character/package.json index c6b029edec91f0..6a77d4911b6a47 100644 --- a/tools/node_modules/eslint/node_modules/is-whitespace-character/package.json +++ b/tools/node_modules/eslint/node_modules/is-whitespace-character/package.json @@ -2,7 +2,7 @@ "author": { "name": "Titus Wormer", "email": "tituswormer@gmail.com", - "url": "http://wooorm.com" + "url": "https://wooorm.com" }, "bugs": { "url": "https://github.com/wooorm/is-whitespace-character/issues" @@ -12,7 +12,7 @@ { "name": "Titus Wormer", "email": "tituswormer@gmail.com", - "url": "http://wooorm.com" + "url": "https://wooorm.com" } ], "dependencies": {}, @@ -20,13 +20,13 @@ "description": "Check if a character is a whitespace character", "devDependencies": { "browserify": "^16.0.0", - "esmangle": "^1.0.1", - "nyc": "^11.0.0", + "nyc": "^14.0.0", "prettier": "^1.12.1", - "remark-cli": "^5.0.0", + "remark-cli": "^6.0.0", "remark-preset-wooorm": "^4.0.0", "tape": "^4.0.0", - "xo": "^0.20.0" + "tinyify": "^2.5.0", + "xo": "^0.24.0" }, "files": [ "index.js" @@ -68,21 +68,17 @@ }, "scripts": { "build": "npm run build-bundle && npm run build-mangle", - "build-bundle": "browserify index.js --bare -s isWhitespaceCharacter > is-whitespace-character.js", - "build-mangle": "esmangle < is-whitespace-character.js > is-whitespace-character.min.js", - "format": "remark . -qfo && prettier --write '**/*.js' && xo --fix", + "build-bundle": "browserify . -s isWhitespaceCharacter -o is-whitespace-character.js", + "build-mangle": "browserify . -s isWhitespaceCharacter -p tinyify -o is-whitespace-character.min.js", + "format": "remark . -qfo && prettier --write \"**/*.js\" && xo --fix", "test": "npm run format && npm run build && npm run test-coverage", "test-api": "node test", "test-coverage": "nyc --reporter lcov tape test.js" }, - "version": "1.0.2", + "version": "1.0.3", "xo": { "prettier": true, "esnext": false, - "rules": { - "no-var": "off", - "prefer-arrow-callback": "off" - }, "ignores": [ "is-whitespace-character.js" ] diff --git a/tools/node_modules/eslint/node_modules/is-whitespace-character/readme.md b/tools/node_modules/eslint/node_modules/is-whitespace-character/readme.md index f99068a7db0763..b448f41f7732d5 100644 --- a/tools/node_modules/eslint/node_modules/is-whitespace-character/readme.md +++ b/tools/node_modules/eslint/node_modules/is-whitespace-character/readme.md @@ -1,4 +1,9 @@ -# is-whitespace-character [![Build Status][travis-badge]][travis] [![Coverage Status][codecov-badge]][codecov] +# is-whitespace-character + +[![Build][build-badge]][build] +[![Coverage][coverage-badge]][coverage] +[![Downloads][downloads-badge]][downloads] +[![Size][size-badge]][size] Check if a character is a whitespace character: `\s`, which equals all Unicode Space Separators (including `[ \t\v\f]`), the BOM @@ -46,16 +51,24 @@ code at the first position (`string`), is a whitespace character. -[travis-badge]: https://img.shields.io/travis/wooorm/is-whitespace-character.svg +[build-badge]: https://img.shields.io/travis/wooorm/is-whitespace-character.svg + +[build]: https://travis-ci.org/wooorm/is-whitespace-character + +[coverage-badge]: https://img.shields.io/codecov/c/github/wooorm/is-whitespace-character.svg + +[coverage]: https://codecov.io/github/wooorm/is-whitespace-character + +[downloads-badge]: https://img.shields.io/npm/dm/is-whitespace-character.svg -[travis]: https://travis-ci.org/wooorm/is-whitespace-character +[downloads]: https://www.npmjs.com/package/is-whitespace-character -[codecov-badge]: https://img.shields.io/codecov/c/github/wooorm/is-whitespace-character.svg +[size-badge]: https://img.shields.io/bundlephobia/minzip/is-whitespace-character.svg -[codecov]: https://codecov.io/github/wooorm/is-whitespace-character +[size]: https://bundlephobia.com/result?p=is-whitespace-character [npm]: https://docs.npmjs.com/cli/install -[license]: LICENSE +[license]: license -[author]: http://wooorm.com +[author]: https://wooorm.com diff --git a/tools/node_modules/eslint/node_modules/is-word-character/index.js b/tools/node_modules/eslint/node_modules/is-word-character/index.js index 6713f0f6b803cf..8c3537f99568c3 100644 --- a/tools/node_modules/eslint/node_modules/is-word-character/index.js +++ b/tools/node_modules/eslint/node_modules/is-word-character/index.js @@ -5,8 +5,8 @@ module.exports = wordCharacter var fromCode = String.fromCharCode var re = /\w/ -/* Check if the given character code, or the character - * code at the first character, is a word character. */ +// Check if the given character code, or the character code at the first +// character, is a word character. function wordCharacter(character) { return re.test( typeof character === 'number' ? fromCode(character) : character.charAt(0) diff --git a/tools/node_modules/eslint/node_modules/is-word-character/LICENSE b/tools/node_modules/eslint/node_modules/is-word-character/license similarity index 100% rename from tools/node_modules/eslint/node_modules/is-word-character/LICENSE rename to tools/node_modules/eslint/node_modules/is-word-character/license diff --git a/tools/node_modules/eslint/node_modules/is-word-character/package.json b/tools/node_modules/eslint/node_modules/is-word-character/package.json index 7a4dad754f0848..6ed0e5065c3ef7 100644 --- a/tools/node_modules/eslint/node_modules/is-word-character/package.json +++ b/tools/node_modules/eslint/node_modules/is-word-character/package.json @@ -2,7 +2,7 @@ "author": { "name": "Titus Wormer", "email": "tituswormer@gmail.com", - "url": "http://wooorm.com" + "url": "https://wooorm.com" }, "bugs": { "url": "https://github.com/wooorm/is-word-character/issues" @@ -12,7 +12,7 @@ { "name": "Titus Wormer", "email": "tituswormer@gmail.com", - "url": "http://wooorm.com" + "url": "https://wooorm.com" } ], "dependencies": {}, @@ -20,13 +20,13 @@ "description": "Check if a character is a word character", "devDependencies": { "browserify": "^16.0.0", - "esmangle": "^1.0.1", - "nyc": "^11.0.0", + "nyc": "^14.0.0", "prettier": "^1.12.1", - "remark-cli": "^5.0.0", + "remark-cli": "^6.0.0", "remark-preset-wooorm": "^4.0.0", "tape": "^4.0.0", - "xo": "^0.20.0" + "tinyify": "^2.5.0", + "xo": "^0.24.0" }, "files": [ "index.js" @@ -66,21 +66,17 @@ }, "scripts": { "build": "npm run build-bundle && npm run build-mangle", - "build-bundle": "browserify index.js --bare -s isWordCharacter > is-word-character.js", - "build-mangle": "esmangle < is-word-character.js > is-word-character.min.js", - "format": "remark . -qfo && prettier --write '**/*.js' && xo --fix", + "build-bundle": "browserify . -s isWordCharacter -o is-word-character.js", + "build-mangle": "browserify . -s isWordCharacter -p tinyify -o is-word-character.min.js", + "format": "remark . -qfo && prettier --write \"**/*.js\" && xo --fix", "test": "npm run format && npm run build && npm run test-coverage", "test-api": "node test", "test-coverage": "nyc --reporter lcov tape test.js" }, - "version": "1.0.2", + "version": "1.0.3", "xo": { "prettier": true, "esnext": false, - "rules": { - "no-var": "off", - "prefer-arrow-callback": "off" - }, "ignores": [ "is-word-character.js" ] diff --git a/tools/node_modules/eslint/node_modules/is-word-character/readme.md b/tools/node_modules/eslint/node_modules/is-word-character/readme.md index f046d0f022584e..441cb3e6bdc87d 100644 --- a/tools/node_modules/eslint/node_modules/is-word-character/readme.md +++ b/tools/node_modules/eslint/node_modules/is-word-character/readme.md @@ -1,4 +1,9 @@ -# is-word-character [![Build Status][travis-badge]][travis] [![Coverage Status][codecov-badge]][codecov] +# is-word-character + +[![Build][build-badge]][build] +[![Coverage][coverage-badge]][coverage] +[![Downloads][downloads-badge]][downloads] +[![Size][size-badge]][size] Check if a character is a word character (`\w`, which equals `[a-zA-Z0-9_]`). @@ -45,16 +50,24 @@ code at the first position (`string`), is a word character. -[travis-badge]: https://img.shields.io/travis/wooorm/is-word-character.svg +[build-badge]: https://img.shields.io/travis/wooorm/is-word-character.svg + +[build]: https://travis-ci.org/wooorm/is-word-character + +[coverage-badge]: https://img.shields.io/codecov/c/github/wooorm/is-word-character.svg + +[coverage]: https://codecov.io/github/wooorm/is-word-character + +[downloads-badge]: https://img.shields.io/npm/dm/is-word-character.svg -[travis]: https://travis-ci.org/wooorm/is-word-character +[downloads]: https://www.npmjs.com/package/is-word-character -[codecov-badge]: https://img.shields.io/codecov/c/github/wooorm/is-word-character.svg +[size-badge]: https://img.shields.io/bundlephobia/minzip/is-word-character.svg -[codecov]: https://codecov.io/github/wooorm/is-word-character +[size]: https://bundlephobia.com/result?p=is-word-character [npm]: https://docs.npmjs.com/cli/install -[license]: LICENSE +[license]: license -[author]: http://wooorm.com +[author]: https://wooorm.com diff --git a/tools/node_modules/eslint/node_modules/js-yaml/dist/js-yaml.js b/tools/node_modules/eslint/node_modules/js-yaml/dist/js-yaml.js index b9e80da637e496..fad044a48a8e4f 100644 --- a/tools/node_modules/eslint/node_modules/js-yaml/dist/js-yaml.js +++ b/tools/node_modules/eslint/node_modules/js-yaml/dist/js-yaml.js @@ -1,4 +1,4 @@ -/* js-yaml 3.13.0 https://github.com/nodeca/js-yaml */(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.jsyaml = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i=i.flowLevel;switch(H(r,n,i.indent,t,function(e){return function(e,t){var n,i;for(n=0,i=e.implicitTypes.length;n"+V(r,i.indent)+Z(L(function(t,n){var e,i,r=/(\n+)([^\n]*)/g,o=function(){var e=t.indexOf("\n");return e=-1!==e?e:t.length,r.lastIndex=e,z(t.slice(0,e),n)}(),a="\n"===t[0]||" "===t[0];for(;i=r.exec(t);){var s=i[1],c=i[2];e=" "===c[0],o+=s+(a||e||""===c?"":"\n")+z(c,n),a=e}return o}(r,t),e));case $:return'"'+function(e){for(var t,n,i,r="",o=0;ot&&o tag resolver accepts not "'+c+'" style');i=s.represent[c](t,c)}e.dump=i}return!0}return!1}function Q(e,t,n,i,r,o){e.tag=null,e.dump=n,J(e,n,!1)||J(e,n,!0);var a=p.call(e.dump);i&&(i=e.flowLevel<0||e.flowLevel>t);var s,c,u="[object Object]"===a||"[object Array]"===a;if(u&&(c=-1!==(s=e.duplicates.indexOf(n))),(null!==e.tag&&"?"!==e.tag||c||2!==e.indent&&0 "+e.dump)}return!0}function X(e,t){var n,i,r=[],o=[];for(function e(t,n,i){var r,o,a;if(null!==t&&"object"==typeof t)if(-1!==(o=n.indexOf(t)))-1===i.indexOf(o)&&i.push(o);else if(n.push(t),Array.isArray(t))for(o=0,a=t.length;o>10),56320+(e-65536&1023))}for(var M=new Array(256),T=new Array(256),d=0;d<256;d++)M[d]=f(d)?1:0,T[d]=f(d);function h(e,t){this.input=e,this.filename=t.filename||null,this.schema=t.schema||a,this.onWarning=t.onWarning||null,this.legacy=t.legacy||!1,this.json=t.json||!1,this.listener=t.listener||null,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=e.length,this.position=0,this.line=0,this.lineStart=0,this.lineIndent=0,this.documents=[]}function m(e,t){return new i(t,new r(e.filename,e.input,e.position,e.line,e.position-e.lineStart))}function L(e,t){throw m(e,t)}function D(e,t){e.onWarning&&e.onWarning.call(null,m(e,t))}var U={YAML:function(e,t,n){var i,r,o;null!==e.version&&L(e,"duplication of %YAML directive"),1!==n.length&&L(e,"YAML directive accepts exactly one argument"),null===(i=/^([0-9]+)\.([0-9]+)$/.exec(n[0]))&&L(e,"ill-formed argument of the YAML directive"),r=parseInt(i[1],10),o=parseInt(i[2],10),1!==r&&L(e,"unacceptable YAML version of the document"),e.version=n[0],e.checkLineBreaks=o<2,1!==o&&2!==o&&D(e,"unsupported YAML version of the document")},TAG:function(e,t,n){var i,r;2!==n.length&&L(e,"TAG directive accepts exactly two arguments"),i=n[0],r=n[1],l.test(i)||L(e,"ill-formed tag handle (first argument) of the TAG directive"),y.call(e.tagMap,i)&&L(e,'there is a previously declared suffix for "'+i+'" tag handle'),p.test(r)||L(e,"ill-formed tag prefix (second argument) of the TAG directive"),e.tagMap[i]=r}};function q(e,t,n,i){var r,o,a,s;if(tt)&&0!==i)L(e,"bad indentation of a sequence entry");else if(e.lineIndentt?d=1:e.lineIndent===t?d=0:e.lineIndentt?d=1:e.lineIndent===t?d=0:e.lineIndentt)&&(V(e,t,b,!0,r)&&(m?d=e.result:h=e.result),m||(R(e,l,p,f,d,h,o,a),f=d=h=null),P(e,!0,-1),s=e.input.charCodeAt(e.position)),e.lineIndent>t&&0!==s)L(e,"bad indentation of a mapping entry");else if(e.lineIndentu&&(u=e.lineIndent),j(o))l++;else{if(e.lineIndent=t){a=!0,l=e.input.charCodeAt(e.position);continue}e.position=o,e.line=s,e.lineStart=c,e.lineIndent=u;break}}a&&(q(e,r,o,!1),K(e,e.line-s),r=o=e.position,a=!1),I(l)||(o=e.position+1),l=e.input.charCodeAt(++e.position)}return q(e,r,o,!1),!!e.result||(e.kind=p,e.result=f,!1)}(e,p,x===n)&&(m=!0,null===e.tag&&(e.tag="?")):(m=!0,null===e.tag&&null===e.anchor||L(e,"alias node should not have any properties")),null!==e.anchor&&(e.anchorMap[e.anchor]=e.result)):0===d&&(m=s&&$(e,f))),null!==e.tag&&"!"!==e.tag)if("?"===e.tag){for(c=0,u=e.implicitTypes.length;c tag; it should be "'+l.kind+'", not "'+e.kind+'"'),l.resolve(e.result)?(e.result=l.construct(e.result),null!==e.anchor&&(e.anchorMap[e.anchor]=e.result)):L(e,"cannot resolve a node with !<"+e.tag+"> explicit tag")):L(e,"unknown tag !<"+e.tag+">");return null!==e.listener&&e.listener("close",e),null!==e.tag||null!==e.anchor||m}function Z(e){var t,n,i,r,o=e.position,a=!1;for(e.version=null,e.checkLineBreaks=e.legacy,e.tagMap={},e.anchorMap={};0!==(r=e.input.charCodeAt(e.position))&&(P(e,!0,-1),r=e.input.charCodeAt(e.position),!(0t/2-1){n=" ... ",i+=5;break}for(r="",o=this.position;ot/2-1){r=" ... ",o-=5;break}return a=this.buffer.slice(i,o),s.repeat(" ",e)+n+a+r+"\n"+s.repeat(" ",e+this.position-i+n.length)+"^"},i.prototype.toString=function(e){var t,n="";return this.name&&(n+='in "'+this.name+'" '),n+="at line "+(this.line+1)+", column "+(this.column+1),e||(t=this.getSnippet())&&(n+=":\n"+t),n},t.exports=i},{"./common":2}],7:[function(e,t,n){"use strict";var i=e("./common"),r=e("./exception"),o=e("./type");function a(e,t,i){var r=[];return e.include.forEach(function(e){i=a(e,t,i)}),e[t].forEach(function(n){i.forEach(function(e,t){e.tag===n.tag&&e.kind===n.kind&&r.push(t)}),i.push(n)}),i.filter(function(e,t){return-1===r.indexOf(t)})}function s(e){this.include=e.include||[],this.implicit=e.implicit||[],this.explicit=e.explicit||[],this.implicit.forEach(function(e){if(e.loadKind&&"scalar"!==e.loadKind)throw new r("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.")}),this.compiledImplicit=a(this,"implicit",[]),this.compiledExplicit=a(this,"explicit",[]),this.compiledTypeMap=function(){var e,t,n={scalar:{},sequence:{},mapping:{},fallback:{}};function i(e){n[e.kind][e.tag]=n.fallback[e.tag]=e}for(e=0,t=arguments.length;e>16&255),s.push(a>>8&255),s.push(255&a)),a=a<<6|o.indexOf(i.charAt(t));return 0==(n=r%4*6)?(s.push(a>>16&255),s.push(a>>8&255),s.push(255&a)):18==n?(s.push(a>>10&255),s.push(a>>2&255)):12==n&&s.push(a>>4&255),c?c.from?c.from(s):new c(s):s},predicate:function(e){return c&&c.isBuffer(e)},represent:function(e){var t,n,i="",r=0,o=e.length,a=u;for(t=0;t>18&63],i+=a[r>>12&63],i+=a[r>>6&63],i+=a[63&r]),r=(r<<8)+e[t];return 0==(n=o%3)?(i+=a[r>>18&63],i+=a[r>>12&63],i+=a[r>>6&63],i+=a[63&r]):2==n?(i+=a[r>>10&63],i+=a[r>>4&63],i+=a[r<<2&63],i+=a[64]):1==n&&(i+=a[r>>2&63],i+=a[r<<4&63],i+=a[64],i+=a[64]),i}})},{"../type":13}],15:[function(e,t,n){"use strict";var i=e("../type");t.exports=new i("tag:yaml.org,2002:bool",{kind:"scalar",resolve:function(e){if(null===e)return!1;var t=e.length;return 4===t&&("true"===e||"True"===e||"TRUE"===e)||5===t&&("false"===e||"False"===e||"FALSE"===e)},construct:function(e){return"true"===e||"True"===e||"TRUE"===e},predicate:function(e){return"[object Boolean]"===Object.prototype.toString.call(e)},represent:{lowercase:function(e){return e?"true":"false"},uppercase:function(e){return e?"TRUE":"FALSE"},camelcase:function(e){return e?"True":"False"}},defaultStyle:"lowercase"})},{"../type":13}],16:[function(e,t,n){"use strict";var i=e("../common"),r=e("../type"),o=new RegExp("^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");var a=/^[-+]?[0-9]+e/;t.exports=new r("tag:yaml.org,2002:float",{kind:"scalar",resolve:function(e){return null!==e&&!(!o.test(e)||"_"===e[e.length-1])},construct:function(e){var t,n,i,r;return n="-"===(t=e.replace(/_/g,"").toLowerCase())[0]?-1:1,r=[],0<="+-".indexOf(t[0])&&(t=t.slice(1)),".inf"===t?1==n?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:".nan"===t?NaN:0<=t.indexOf(":")?(t.split(":").forEach(function(e){r.unshift(parseFloat(e,10))}),t=0,i=1,r.forEach(function(e){t+=e*i,i*=60}),n*t):n*parseFloat(t,10)},predicate:function(e){return"[object Number]"===Object.prototype.toString.call(e)&&(e%1!=0||i.isNegativeZero(e))},represent:function(e,t){var n;if(isNaN(e))switch(t){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===e)switch(t){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===e)switch(t){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(i.isNegativeZero(e))return"-0.0";return n=e.toString(10),a.test(n)?n.replace("e",".e"):n},defaultStyle:"lowercase"})},{"../common":2,"../type":13}],17:[function(e,t,n){"use strict";var i=e("../common"),r=e("../type");function o(e){return 48<=e&&e<=57||65<=e&&e<=70||97<=e&&e<=102}function a(e){return 48<=e&&e<=55}function s(e){return 48<=e&&e<=57}t.exports=new r("tag:yaml.org,2002:int",{kind:"scalar",resolve:function(e){if(null===e)return!1;var t,n=e.length,i=0,r=!1;if(!n)return!1;if("-"!==(t=e[i])&&"+"!==t||(t=e[++i]),"0"===t){if(i+1===n)return!0;if("b"===(t=e[++i])){for(i++;i=i.flowLevel;switch(H(r,n,i.indent,t,function(e){return function(e,t){var n,i;for(n=0,i=e.implicitTypes.length;n"+V(r,i.indent)+Z(L(function(t,n){var e,i,r=/(\n+)([^\n]*)/g,o=function(){var e=t.indexOf("\n");return e=-1!==e?e:t.length,r.lastIndex=e,z(t.slice(0,e),n)}(),a="\n"===t[0]||" "===t[0];for(;i=r.exec(t);){var s=i[1],c=i[2];e=" "===c[0],o+=s+(a||e||""===c?"":"\n")+z(c,n),a=e}return o}(r,t),e));case $:return'"'+function(e){for(var t,n,i,r="",o=0;ot&&o tag resolver accepts not "'+c+'" style');i=s.represent[c](t,c)}e.dump=i}return!0}return!1}function Q(e,t,n,i,r,o){e.tag=null,e.dump=n,J(e,n,!1)||J(e,n,!0);var a=p.call(e.dump);i&&(i=e.flowLevel<0||e.flowLevel>t);var s,c,u="[object Object]"===a||"[object Array]"===a;if(u&&(c=-1!==(s=e.duplicates.indexOf(n))),(null!==e.tag&&"?"!==e.tag||c||2!==e.indent&&0 "+e.dump)}return!0}function X(e,t){var n,i,r=[],o=[];for(function e(t,n,i){var r,o,a;if(null!==t&&"object"==typeof t)if(-1!==(o=n.indexOf(t)))-1===i.indexOf(o)&&i.push(o);else if(n.push(t),Array.isArray(t))for(o=0,a=t.length;ot)&&0!==i)N(e,"bad indentation of a sequence entry");else if(e.lineIndentt?d=1:e.lineIndent===t?d=0:e.lineIndentt?d=1:e.lineIndent===t?d=0:e.lineIndentt)&&($(e,t,b,!0,r)&&(m?d=e.result:h=e.result),m||(U(e,l,p,f,d,h,o,a),f=d=h=null),Y(e,!0,-1),s=e.input.charCodeAt(e.position)),e.lineIndent>t&&0!==s)N(e,"bad indentation of a mapping entry");else if(e.lineIndentl&&(l=e.lineIndent),j(o))p++;else{if(e.lineIndent>10),56320+(c-65536&1023)),e.position++}else N(e,"unknown escape sequence");n=i=e.position}else j(s)?(L(e,n,i,!0),B(e,Y(e,!1,t)),n=i=e.position):e.position===e.lineStart&&R(e)?N(e,"unexpected end of the document within a double quoted scalar"):(e.position++,i=e.position)}N(e,"unexpected end of the stream within a double quoted scalar")}(e,p)?m=!0:!function(e){var t,n,i;if(42!==(i=e.input.charCodeAt(e.position)))return!1;for(i=e.input.charCodeAt(++e.position),t=e.position;0!==i&&!I(i)&&!O(i);)i=e.input.charCodeAt(++e.position);return e.position===t&&N(e,"name of an alias node must contain at least one character"),n=e.input.slice(t,e.position),e.anchorMap.hasOwnProperty(n)||N(e,'unidentified alias "'+n+'"'),e.result=e.anchorMap[n],Y(e,!0,-1),!0}(e)?function(e,t,n){var i,r,o,a,s,c,u,l,p=e.kind,f=e.result;if(I(l=e.input.charCodeAt(e.position))||O(l)||35===l||38===l||42===l||33===l||124===l||62===l||39===l||34===l||37===l||64===l||96===l)return!1;if((63===l||45===l)&&(I(i=e.input.charCodeAt(e.position+1))||n&&O(i)))return!1;for(e.kind="scalar",e.result="",r=o=e.position,a=!1;0!==l;){if(58===l){if(I(i=e.input.charCodeAt(e.position+1))||n&&O(i))break}else if(35===l){if(I(e.input.charCodeAt(e.position-1)))break}else{if(e.position===e.lineStart&&R(e)||n&&O(l))break;if(j(l)){if(s=e.line,c=e.lineStart,u=e.lineIndent,Y(e,!1,-1),e.lineIndent>=t){a=!0,l=e.input.charCodeAt(e.position);continue}e.position=o,e.line=s,e.lineStart=c,e.lineIndent=u;break}}a&&(L(e,r,o,!1),B(e,e.line-s),r=o=e.position,a=!1),S(l)||(o=e.position+1),l=e.input.charCodeAt(++e.position)}return L(e,r,o,!1),!!e.result||(e.kind=p,e.result=f,!1)}(e,p,x===n)&&(m=!0,null===e.tag&&(e.tag="?")):(m=!0,null===e.tag&&null===e.anchor||N(e,"alias node should not have any properties")),null!==e.anchor&&(e.anchorMap[e.anchor]=e.result)):0===d&&(m=s&&P(e,f))),null!==e.tag&&"!"!==e.tag)if("?"===e.tag){for(c=0,u=e.implicitTypes.length;c tag; it should be "'+l.kind+'", not "'+e.kind+'"'),l.resolve(e.result)?(e.result=l.construct(e.result),null!==e.anchor&&(e.anchorMap[e.anchor]=e.result)):N(e,"cannot resolve a node with !<"+e.tag+"> explicit tag")):N(e,"unknown tag !<"+e.tag+">");return null!==e.listener&&e.listener("close",e),null!==e.tag||null!==e.anchor||m}function H(e){var t,n,i,r,o=e.position,a=!1;for(e.version=null,e.checkLineBreaks=e.legacy,e.tagMap={},e.anchorMap={};0!==(r=e.input.charCodeAt(e.position))&&(Y(e,!0,-1),r=e.input.charCodeAt(e.position),!(0t/2-1){n=" ... ",i+=5;break}for(r="",o=this.position;ot/2-1){r=" ... ",o-=5;break}return a=this.buffer.slice(i,o),s.repeat(" ",e)+n+a+r+"\n"+s.repeat(" ",e+this.position-i+n.length)+"^"},i.prototype.toString=function(e){var t,n="";return this.name&&(n+='in "'+this.name+'" '),n+="at line "+(this.line+1)+", column "+(this.column+1),e||(t=this.getSnippet())&&(n+=":\n"+t),n},t.exports=i},{"./common":2}],7:[function(e,t,n){"use strict";var i=e("./common"),r=e("./exception"),o=e("./type");function a(e,t,i){var r=[];return e.include.forEach(function(e){i=a(e,t,i)}),e[t].forEach(function(n){i.forEach(function(e,t){e.tag===n.tag&&e.kind===n.kind&&r.push(t)}),i.push(n)}),i.filter(function(e,t){return-1===r.indexOf(t)})}function s(e){this.include=e.include||[],this.implicit=e.implicit||[],this.explicit=e.explicit||[],this.implicit.forEach(function(e){if(e.loadKind&&"scalar"!==e.loadKind)throw new r("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.")}),this.compiledImplicit=a(this,"implicit",[]),this.compiledExplicit=a(this,"explicit",[]),this.compiledTypeMap=function(){var e,t,n={scalar:{},sequence:{},mapping:{},fallback:{}};function i(e){n[e.kind][e.tag]=n.fallback[e.tag]=e}for(e=0,t=arguments.length;e>16&255),s.push(a>>8&255),s.push(255&a)),a=a<<6|o.indexOf(i.charAt(t));return 0==(n=r%4*6)?(s.push(a>>16&255),s.push(a>>8&255),s.push(255&a)):18==n?(s.push(a>>10&255),s.push(a>>2&255)):12==n&&s.push(a>>4&255),c?c.from?c.from(s):new c(s):s},predicate:function(e){return c&&c.isBuffer(e)},represent:function(e){var t,n,i="",r=0,o=e.length,a=u;for(t=0;t>18&63],i+=a[r>>12&63],i+=a[r>>6&63],i+=a[63&r]),r=(r<<8)+e[t];return 0==(n=o%3)?(i+=a[r>>18&63],i+=a[r>>12&63],i+=a[r>>6&63],i+=a[63&r]):2==n?(i+=a[r>>10&63],i+=a[r>>4&63],i+=a[r<<2&63],i+=a[64]):1==n&&(i+=a[r>>2&63],i+=a[r<<4&63],i+=a[64],i+=a[64]),i}})},{"../type":13}],15:[function(e,t,n){"use strict";var i=e("../type");t.exports=new i("tag:yaml.org,2002:bool",{kind:"scalar",resolve:function(e){if(null===e)return!1;var t=e.length;return 4===t&&("true"===e||"True"===e||"TRUE"===e)||5===t&&("false"===e||"False"===e||"FALSE"===e)},construct:function(e){return"true"===e||"True"===e||"TRUE"===e},predicate:function(e){return"[object Boolean]"===Object.prototype.toString.call(e)},represent:{lowercase:function(e){return e?"true":"false"},uppercase:function(e){return e?"TRUE":"FALSE"},camelcase:function(e){return e?"True":"False"}},defaultStyle:"lowercase"})},{"../type":13}],16:[function(e,t,n){"use strict";var i=e("../common"),r=e("../type"),o=new RegExp("^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");var a=/^[-+]?[0-9]+e/;t.exports=new r("tag:yaml.org,2002:float",{kind:"scalar",resolve:function(e){return null!==e&&!(!o.test(e)||"_"===e[e.length-1])},construct:function(e){var t,n,i,r;return n="-"===(t=e.replace(/_/g,"").toLowerCase())[0]?-1:1,r=[],0<="+-".indexOf(t[0])&&(t=t.slice(1)),".inf"===t?1==n?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:".nan"===t?NaN:0<=t.indexOf(":")?(t.split(":").forEach(function(e){r.unshift(parseFloat(e,10))}),t=0,i=1,r.forEach(function(e){t+=e*i,i*=60}),n*t):n*parseFloat(t,10)},predicate:function(e){return"[object Number]"===Object.prototype.toString.call(e)&&(e%1!=0||i.isNegativeZero(e))},represent:function(e,t){var n;if(isNaN(e))switch(t){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===e)switch(t){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===e)switch(t){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(i.isNegativeZero(e))return"-0.0";return n=e.toString(10),a.test(n)?n.replace("e",".e"):n},defaultStyle:"lowercase"})},{"../common":2,"../type":13}],17:[function(e,t,n){"use strict";var i=e("../common"),r=e("../type");t.exports=new r("tag:yaml.org,2002:int",{kind:"scalar",resolve:function(e){if(null===e)return!1;var t,n,i,r,o=e.length,a=0,s=!1;if(!o)return!1;if("-"!==(t=e[a])&&"+"!==t||(t=e[++a]),"0"===t){if(a+1===o)return!0;if("b"===(t=e[++a])){for(a++;a markdown-escapes.js", - "build-mangle": "esmangle < markdown-escapes.js > markdown-escapes.min.js", - "format": "remark . -qfo && prettier --write '**/*.js' && xo --fix", + "build-bundle": "browserify . -s markdownEscapes -o markdown-escapes.js", + "build-mangle": "browserify . -s markdownEscapes -p tinyify -o markdown-escapes.min.js", + "format": "remark . -qfo && prettier --write \"**/*.js\" && xo --fix", "test": "npm run format && npm run build && npm run test-coverage", "test-api": "node test", "test-coverage": "nyc --reporter lcov tape test.js" }, - "version": "1.0.2", + "version": "1.0.3", "xo": { "prettier": true, "esnext": false, - "rules": { - "no-var": "off", - "prefer-arrow-callback": "off" - }, "ignores": [ "markdown-escapes.js" ] diff --git a/tools/node_modules/eslint/node_modules/markdown-escapes/readme.md b/tools/node_modules/eslint/node_modules/markdown-escapes/readme.md index 2f01806a34cb7b..9d0b7a88a54493 100644 --- a/tools/node_modules/eslint/node_modules/markdown-escapes/readme.md +++ b/tools/node_modules/eslint/node_modules/markdown-escapes/readme.md @@ -1,4 +1,9 @@ -# markdown-escapes [![Build Status][travis-badge]][travis] [![Coverage Status][codecov-badge]][codecov] +# markdown-escapes + +[![Build][build-badge]][build] +[![Coverage][coverage-badge]][coverage] +[![Downloads][downloads-badge]][downloads] +[![Size][size-badge]][size] List of escapable characters in markdown. @@ -52,16 +57,24 @@ List of escapable characters in CommonMark (which includes all `gfm`s). -[travis-badge]: https://img.shields.io/travis/wooorm/markdown-escapes.svg +[build-badge]: https://img.shields.io/travis/wooorm/markdown-escapes.svg + +[build]: https://travis-ci.org/wooorm/markdown-escapes + +[coverage-badge]: https://img.shields.io/codecov/c/github/wooorm/markdown-escapes.svg + +[coverage]: https://codecov.io/github/wooorm/markdown-escapes + +[downloads-badge]: https://img.shields.io/npm/dm/markdown-escapes.svg -[travis]: https://travis-ci.org/wooorm/markdown-escapes +[downloads]: https://www.npmjs.com/package/markdown-escapes -[codecov-badge]: https://img.shields.io/codecov/c/github/wooorm/markdown-escapes.svg +[size-badge]: https://img.shields.io/bundlephobia/minzip/markdown-escapes.svg -[codecov]: https://codecov.io/github/wooorm/markdown-escapes +[size]: https://bundlephobia.com/result?p=markdown-escapes [npm]: https://docs.npmjs.com/cli/install -[license]: LICENSE +[license]: license -[author]: http://wooorm.com +[author]: https://wooorm.com diff --git a/tools/node_modules/eslint/node_modules/parse-entities/decode-entity.browser.js b/tools/node_modules/eslint/node_modules/parse-entities/decode-entity.browser.js index ca97cd28958dea..feb32664202d16 100644 --- a/tools/node_modules/eslint/node_modules/parse-entities/decode-entity.browser.js +++ b/tools/node_modules/eslint/node_modules/parse-entities/decode-entity.browser.js @@ -4,6 +4,8 @@ var el +var semicolon = 59 // ';' + module.exports = decodeEntity function decodeEntity(characters) { @@ -14,12 +16,12 @@ function decodeEntity(characters) { el.innerHTML = entity char = el.textContent - // Some entities do not require the closing semicolon (¬ - for instance), + // Some entities do not require the closing semicolon (`¬` - for instance), // which leads to situations where parsing the assumed entity of ¬it; will // result in the string `¬it;`. When we encounter a trailing semicolon after - // parsing and the entity to decode was not a semicolon (;), we can + // parsing and the entity to decode was not a semicolon (`;`), we can // assume that the matching was incomplete - if (char.slice(-1) === ';' && characters !== 'semi') { + if (char.charCodeAt(char.length - 1) === semicolon && characters !== 'semi') { return false } diff --git a/tools/node_modules/eslint/node_modules/parse-entities/index.js b/tools/node_modules/eslint/node_modules/parse-entities/index.js index ab332bf2f93fc3..1606d02f6590c5 100644 --- a/tools/node_modules/eslint/node_modules/parse-entities/index.js +++ b/tools/node_modules/eslint/node_modules/parse-entities/index.js @@ -13,7 +13,7 @@ var own = {}.hasOwnProperty var fromCharCode = String.fromCharCode var noop = Function.prototype -/* Default settings. */ +// Default settings. var defaults = { warning: null, reference: null, @@ -27,51 +27,66 @@ var defaults = { nonTerminated: true } -/* Reference types. */ -var NAMED = 'named' -var HEXADECIMAL = 'hexadecimal' -var DECIMAL = 'decimal' - -/* Map of bases. */ -var BASE = {} - -BASE[HEXADECIMAL] = 16 -BASE[DECIMAL] = 10 - -/* Map of types to tests. Each type of character reference - * accepts different characters. This test is used to - * detect whether a reference has ended (as the semicolon - * is not strictly needed). */ -var TESTS = {} - -TESTS[NAMED] = alphanumerical -TESTS[DECIMAL] = decimal -TESTS[HEXADECIMAL] = hexadecimal - -/* Warning messages. */ -var NAMED_NOT_TERMINATED = 1 -var NUMERIC_NOT_TERMINATED = 2 -var NAMED_EMPTY = 3 -var NUMERIC_EMPTY = 4 -var NAMED_UNKNOWN = 5 -var NUMERIC_DISALLOWED = 6 -var NUMERIC_PROHIBITED = 7 - -var MESSAGES = {} - -MESSAGES[NAMED_NOT_TERMINATED] = +// Characters. +var tab = 9 // '\t' +var lineFeed = 10 // '\n' +var formFeed = 12 // '\f' +var space = 32 // ' ' +var ampersand = 38 // '&' +var semicolon = 59 // ';' +var lessThan = 60 // '<' +var equalsTo = 61 // '=' +var numberSign = 35 // '#' +var uppercaseX = 88 // 'X' +var lowercaseX = 120 // 'x' +var replacementCharacter = 65533 // '�' + +// Reference types. +var name = 'named' +var hexa = 'hexadecimal' +var deci = 'decimal' + +// Map of bases. +var bases = {} + +bases[hexa] = 16 +bases[deci] = 10 + +// Map of types to tests. +// Each type of character reference accepts different characters. +// This test is used to detect whether a reference has ended (as the semicolon +// is not strictly needed). +var tests = {} + +tests[name] = alphanumerical +tests[deci] = decimal +tests[hexa] = hexadecimal + +// Warning types. +var namedNotTerminated = 1 +var numericNotTerminated = 2 +var namedEmpty = 3 +var numericEmpty = 4 +var namedUnknown = 5 +var numericDisallowed = 6 +var numericProhibited = 7 + +// Warning messages. +var messages = {} + +messages[namedNotTerminated] = 'Named character references must be terminated by a semicolon' -MESSAGES[NUMERIC_NOT_TERMINATED] = +messages[numericNotTerminated] = 'Numeric character references must be terminated by a semicolon' -MESSAGES[NAMED_EMPTY] = 'Named character references cannot be empty' -MESSAGES[NUMERIC_EMPTY] = 'Numeric character references cannot be empty' -MESSAGES[NAMED_UNKNOWN] = 'Named character references must be known' -MESSAGES[NUMERIC_DISALLOWED] = +messages[namedEmpty] = 'Named character references cannot be empty' +messages[numericEmpty] = 'Numeric character references cannot be empty' +messages[namedUnknown] = 'Named character references must be known' +messages[numericDisallowed] = 'Numeric character references cannot be disallowed' -MESSAGES[NUMERIC_PROHIBITED] = +messages[numericProhibited] = 'Numeric character references cannot be outside the permissible Unicode range' -/* Wrap to ensure clean parameters are given to `parse`. */ +// Wrap to ensure clean parameters are given to `parse`. function parseEntities(value, options) { var settings = {} var option @@ -95,7 +110,8 @@ function parseEntities(value, options) { return parse(value, settings) } -/* Parse entities. */ +// Parse entities. +// eslint-disable-next-line complexity function parse(value, settings) { var additional = settings.additional var nonTerminated = settings.nonTerminated @@ -134,59 +150,46 @@ function parse(value, settings) { var diff var end - /* Cache the current point. */ + if (typeof additional === 'string') { + additional = additional.charCodeAt(0) + } + + // Cache the current point. prev = now() - /* Wrap `handleWarning`. */ + // Wrap `handleWarning`. warning = handleWarning ? parseError : noop - /* Ensure the algorithm walks over the first character - * and the end (inclusive). */ + // Ensure the algorithm walks over the first character and the end (inclusive). index-- length++ while (++index < length) { - /* If the previous character was a newline. */ - if (character === '\n') { + // If the previous character was a newline. + if (character === lineFeed) { column = indent[lines] || 1 } - character = at(index) + character = value.charCodeAt(index) - /* Handle anything other than an ampersand, - * including newlines and EOF. */ - if (character !== '&') { - if (character === '\n') { - line++ - lines++ - column = 0 - } + if (character === ampersand) { + following = value.charCodeAt(index + 1) - if (character) { - queue += character - column++ - } else { - flush() - } - } else { - following = at(index + 1) - - /* The behaviour depends on the identity of the next - * character. */ + // The behaviour depends on the identity of the next character. if ( - following === '\t' /* Tab */ || - following === '\n' /* Newline */ || - following === '\f' /* Form feed */ || - following === ' ' /* Space */ || - following === '<' /* Less-than */ || - following === '&' /* Ampersand */ || - following === '' || + following === tab || + following === lineFeed || + following === formFeed || + following === space || + following === ampersand || + following === lessThan || + following !== following || (additional && following === additional) ) { - /* Not a character reference. No characters - * are consumed, and nothing is returned. - * This is not an error, either. */ - queue += character + // Not a character reference. + // No characters are consumed, and nothing is returned. + // This is not an error, either. + queue += fromCharCode(character) column++ continue @@ -196,58 +199,56 @@ function parse(value, settings) { begin = start end = start - /* Numerical entity. */ - if (following !== '#') { - type = NAMED - } else { + if (following === numberSign) { + // Numerical entity. end = ++begin - /* The behaviour further depends on the - * character after the U+0023 NUMBER SIGN. */ - following = at(end) + // The behaviour further depends on the next character. + following = value.charCodeAt(end) - if (following === 'x' || following === 'X') { - /* ASCII hex digits. */ - type = HEXADECIMAL + if (following === uppercaseX || following === lowercaseX) { + // ASCII hex digits. + type = hexa end = ++begin } else { - /* ASCII digits. */ - type = DECIMAL + // ASCII digits. + type = deci } + } else { + // Named entity. + type = name } entityCharacters = '' entity = '' characters = '' - test = TESTS[type] + test = tests[type] end-- while (++end < length) { - following = at(end) + following = value.charCodeAt(end) if (!test(following)) { break } - characters += following + characters += fromCharCode(following) - /* Check if we can match a legacy named - * reference. If so, we cache that as the - * last viable named reference. This - * ensures we do not need to walk backwards - * later. */ - if (type === NAMED && own.call(legacy, characters)) { + // Check if we can match a legacy named reference. + // If so, we cache that as the last viable named reference. + // This ensures we do not need to walk backwards later. + if (type === name && own.call(legacy, characters)) { entityCharacters = characters entity = legacy[characters] } } - terminated = at(end) === ';' + terminated = value.charCodeAt(end) === semicolon if (terminated) { end++ - namedEntity = type === NAMED ? decodeEntity(characters) : false + namedEntity = type === name ? decodeEntity(characters) : false if (namedEntity) { entityCharacters = characters @@ -258,40 +259,35 @@ function parse(value, settings) { diff = 1 + end - start if (!terminated && !nonTerminated) { - /* Empty. */ + // Empty. } else if (!characters) { - /* An empty (possible) entity is valid, unless - * its numeric (thus an ampersand followed by - * an octothorp). */ - if (type !== NAMED) { - warning(NUMERIC_EMPTY, diff) + // An empty (possible) entity is valid, unless it’s numeric (thus an + // ampersand followed by an octothorp). + if (type !== name) { + warning(numericEmpty, diff) } - } else if (type === NAMED) { - /* An ampersand followed by anything - * unknown, and not terminated, is invalid. */ + } else if (type === name) { + // An ampersand followed by anything unknown, and not terminated, is + // invalid. if (terminated && !entity) { - warning(NAMED_UNKNOWN, 1) + warning(namedUnknown, 1) } else { - /* If theres something after an entity - * name which is not known, cap the - * reference. */ + // If theres something after an entity name which is not known, cap + // the reference. if (entityCharacters !== characters) { end = begin + entityCharacters.length diff = 1 + end - begin terminated = false } - /* If the reference is not terminated, - * warn. */ + // If the reference is not terminated, warn. if (!terminated) { - reason = entityCharacters ? NAMED_NOT_TERMINATED : NAMED_EMPTY + reason = entityCharacters ? namedNotTerminated : namedEmpty - if (!settings.attribute) { - warning(reason, diff) - } else { - following = at(end) + if (settings.attribute) { + following = value.charCodeAt(end) - if (following === '=') { + if (following === equalsTo) { warning(reason, diff) entity = null } else if (alphanumerical(following)) { @@ -299,6 +295,8 @@ function parse(value, settings) { } else { warning(reason, diff) } + } else { + warning(reason, diff) } } } @@ -306,38 +304,34 @@ function parse(value, settings) { reference = entity } else { if (!terminated) { - /* All non-terminated numeric entities are - * not rendered, and trigger a warning. */ - warning(NUMERIC_NOT_TERMINATED, diff) + // All non-terminated numeric entities are not rendered, and trigger a + // warning. + warning(numericNotTerminated, diff) } - /* When terminated and number, parse as - * either hexadecimal or decimal. */ - reference = parseInt(characters, BASE[type]) + // When terminated and number, parse as either hexadecimal or decimal. + reference = parseInt(characters, bases[type]) - /* Trigger a warning when the parsed number - * is prohibited, and replace with - * replacement character. */ + // Trigger a warning when the parsed number is prohibited, and replace + // with replacement character. if (prohibited(reference)) { - warning(NUMERIC_PROHIBITED, diff) - reference = '\uFFFD' + warning(numericProhibited, diff) + reference = fromCharCode(replacementCharacter) } else if (reference in invalid) { - /* Trigger a warning when the parsed number - * is disallowed, and replace by an - * alternative. */ - warning(NUMERIC_DISALLOWED, diff) + // Trigger a warning when the parsed number is disallowed, and replace + // by an alternative. + warning(numericDisallowed, diff) reference = invalid[reference] } else { - /* Parse the number. */ + // Parse the number. output = '' - /* Trigger a warning when the parsed - * number should not be used. */ + // Trigger a warning when the parsed number should not be used. if (disallowed(reference)) { - warning(NUMERIC_DISALLOWED, diff) + warning(numericDisallowed, diff) } - /* Stringify the number. */ + // Stringify the number. if (reference > 0xffff) { reference -= 0x10000 output += fromCharCode((reference >>> (10 & 0x3ff)) | 0xd800) @@ -348,20 +342,9 @@ function parse(value, settings) { } } - /* If we could not find a reference, queue the - * checked characters (as normal characters), - * and move the pointer to their end. This is - * possible because we can be certain neither - * newlines nor ampersands are included. */ - if (!reference) { - characters = value.slice(start - 1, end) - queue += characters - column += characters.length - index = end - 1 - } else { - /* Found it! First eat the queued - * characters as normal text, then eat - * an entity. */ + // Found it! + // First eat the queued characters as normal text, then eat an entity. + if (reference) { flush() prev = now() @@ -381,14 +364,39 @@ function parse(value, settings) { } prev = next + } else { + // If we could not find a reference, queue the checked characters (as + // normal characters), and move the pointer to their end. + // This is possible because we can be certain neither newlines nor + // ampersands are included. + characters = value.slice(start - 1, end) + queue += characters + column += characters.length + index = end - 1 + } + } else { + // Handle anything other than an ampersand, including newlines and EOF. + if ( + character === 10 // Line feed + ) { + line++ + lines++ + column = 0 + } + + if (character === character) { + queue += fromCharCode(character) + column++ + } else { + flush() } } } - /* Return the reduced nodes, and any possible warnings. */ + // Return the reduced nodes, and any possible warnings. return result.join('') - /* Get current position. */ + // Get current position. function now() { return { line: line, @@ -397,24 +405,19 @@ function parse(value, settings) { } } - /* “Throw” a parse-error: a warning. */ + // “Throw” a parse-error: a warning. function parseError(code, offset) { var position = now() position.column += offset position.offset += offset - handleWarning.call(warningContext, MESSAGES[code], position, code) - } - - /* Get character at position. */ - function at(position) { - return value.charAt(position) + handleWarning.call(warningContext, messages[code], position, code) } - /* Flush `queue` (normal text). Macro invoked before - * each entity and at the end of `value`. - * Does nothing when `queue` is empty. */ + // Flush `queue` (normal text). + // Macro invoked before each entity and at the end of `value`. + // Does nothing when `queue` is empty. function flush() { if (queue) { result.push(queue) @@ -428,12 +431,12 @@ function parse(value, settings) { } } -/* Check if `character` is outside the permissible unicode range. */ +// Check if `character` is outside the permissible unicode range. function prohibited(code) { return (code >= 0xd800 && code <= 0xdfff) || code > 0x10ffff } -/* Check if `character` is disallowed. */ +// Check if `character` is disallowed. function disallowed(code) { return ( (code >= 0x0001 && code <= 0x0008) || diff --git a/tools/node_modules/eslint/node_modules/parse-entities/LICENSE b/tools/node_modules/eslint/node_modules/parse-entities/license similarity index 100% rename from tools/node_modules/eslint/node_modules/parse-entities/LICENSE rename to tools/node_modules/eslint/node_modules/parse-entities/license diff --git a/tools/node_modules/eslint/node_modules/parse-entities/package.json b/tools/node_modules/eslint/node_modules/parse-entities/package.json index 03871755f2d1fa..f2eee3452e6f79 100644 --- a/tools/node_modules/eslint/node_modules/parse-entities/package.json +++ b/tools/node_modules/eslint/node_modules/parse-entities/package.json @@ -2,7 +2,7 @@ "author": { "name": "Titus Wormer", "email": "tituswormer@gmail.com", - "url": "http://wooorm.com" + "url": "https://wooorm.com" }, "browser": { "./decode-entity.js": "./decode-entity.browser.js" @@ -15,7 +15,7 @@ { "name": "Titus Wormer", "email": "tituswormer@gmail.com", - "url": "http://wooorm.com" + "url": "https://wooorm.com" } ], "dependencies": { @@ -30,14 +30,14 @@ "description": "Parse HTML character references: fast, spec-compliant, positional information", "devDependencies": { "browserify": "^16.0.0", - "nyc": "^11.0.0", + "nyc": "^14.0.0", "prettier": "^1.12.1", - "remark-cli": "^5.0.0", + "remark-cli": "^6.0.0", "remark-preset-wooorm": "^4.0.0", "tape": "^4.2.0", - "tape-run": "^4.0.0", + "tape-run": "^6.0.0", "tinyify": "^2.4.3", - "xo": "^0.20.0" + "xo": "^0.24.0" }, "files": [ "index.js", @@ -85,25 +85,20 @@ "build": "npm run build-bundle && npm run build-mangle", "build-bundle": "browserify . -s parseEntities > parse-entities.js", "build-mangle": "browserify . -s parseEntities -p tinyify > parse-entities.min.js", - "format": "remark . -qfo && prettier --write '**/*.js' && xo --fix", + "format": "remark . -qfo && prettier --write \"**/*.js\" && xo --fix", "test": "npm run format && npm run build && npm run test-coverage && npm run test-browser", "test-api": "node test", "test-browser": "browserify test.js | tape-run", "test-coverage": "nyc --reporter lcov tape test.js" }, - "version": "1.2.1", + "version": "1.2.2", "xo": { "prettier": true, "esnext": false, "rules": { - "unicorn/number-literal-case": "off", - "object-shorthand": "off", - "no-var": "off", - "prefer-arrow-callback": "off", + "no-self-compare": "off", "guard-for-in": "off", - "no-negated-condition": "off", - "max-depth": "off", - "complexity": "off" + "max-depth": "off" }, "ignores": [ "parse-entities.js" diff --git a/tools/node_modules/eslint/node_modules/parse-entities/readme.md b/tools/node_modules/eslint/node_modules/parse-entities/readme.md index c7f547d4c9c94d..e9cc0f037ff16f 100644 --- a/tools/node_modules/eslint/node_modules/parse-entities/readme.md +++ b/tools/node_modules/eslint/node_modules/parse-entities/readme.md @@ -1,4 +1,9 @@ -# parse-entities [![Build Status][build-badge]][build-status] [![Coverage Status][coverage-badge]][coverage-status] +# parse-entities + +[![Build][build-badge]][build] +[![Coverage][coverage-badge]][coverage] +[![Downloads][downloads-badge]][downloads] +[![Size][size-badge]][size] Parse HTML character references: fast, spec-compliant, positional information. @@ -183,17 +188,25 @@ Source of character reference (`Location`). [build-badge]: https://img.shields.io/travis/wooorm/parse-entities.svg -[build-status]: https://travis-ci.org/wooorm/parse-entities +[build]: https://travis-ci.org/wooorm/parse-entities [coverage-badge]: https://img.shields.io/codecov/c/github/wooorm/parse-entities.svg -[coverage-status]: https://codecov.io/github/wooorm/parse-entities +[coverage]: https://codecov.io/github/wooorm/parse-entities + +[downloads-badge]: https://img.shields.io/npm/dm/parse-entities.svg + +[downloads]: https://www.npmjs.com/package/parse-entities + +[size-badge]: https://img.shields.io/bundlephobia/minzip/parse-entities.svg + +[size]: https://bundlephobia.com/result?p=parse-entities [npm]: https://docs.npmjs.com/cli/install [license]: license -[author]: http://wooorm.com +[author]: https://wooorm.com [warning]: #function-warningreason-position-code diff --git a/tools/node_modules/eslint/node_modules/path-dirname/index.js b/tools/node_modules/eslint/node_modules/path-dirname/index.js new file mode 100644 index 00000000000000..ed67817a0045b0 --- /dev/null +++ b/tools/node_modules/eslint/node_modules/path-dirname/index.js @@ -0,0 +1,143 @@ +'use strict'; + +var path = require('path'); +var inspect = require('util').inspect; + +function assertPath(path) { + if (typeof path !== 'string') { + throw new TypeError('Path must be a string. Received ' + inspect(path)); + } +} + +function posix(path) { + assertPath(path); + if (path.length === 0) + return '.'; + var code = path.charCodeAt(0); + var hasRoot = (code === 47/*/*/); + var end = -1; + var matchedSlash = true; + for (var i = path.length - 1; i >= 1; --i) { + code = path.charCodeAt(i); + if (code === 47/*/*/) { + if (!matchedSlash) { + end = i; + break; + } + } else { + // We saw the first non-path separator + matchedSlash = false; + } + } + + if (end === -1) + return hasRoot ? '/' : '.'; + if (hasRoot && end === 1) + return '//'; + return path.slice(0, end); +} + +function win32(path) { + assertPath(path); + var len = path.length; + if (len === 0) + return '.'; + var rootEnd = -1; + var end = -1; + var matchedSlash = true; + var offset = 0; + var code = path.charCodeAt(0); + + // Try to match a root + if (len > 1) { + if (code === 47/*/*/ || code === 92/*\*/) { + // Possible UNC root + + rootEnd = offset = 1; + + code = path.charCodeAt(1); + if (code === 47/*/*/ || code === 92/*\*/) { + // Matched double path separator at beginning + var j = 2; + var last = j; + // Match 1 or more non-path separators + for (; j < len; ++j) { + code = path.charCodeAt(j); + if (code === 47/*/*/ || code === 92/*\*/) + break; + } + if (j < len && j !== last) { + // Matched! + last = j; + // Match 1 or more path separators + for (; j < len; ++j) { + code = path.charCodeAt(j); + if (code !== 47/*/*/ && code !== 92/*\*/) + break; + } + if (j < len && j !== last) { + // Matched! + last = j; + // Match 1 or more non-path separators + for (; j < len; ++j) { + code = path.charCodeAt(j); + if (code === 47/*/*/ || code === 92/*\*/) + break; + } + if (j === len) { + // We matched a UNC root only + return path; + } + if (j !== last) { + // We matched a UNC root with leftovers + + // Offset by 1 to include the separator after the UNC root to + // treat it as a "normal root" on top of a (UNC) root + rootEnd = offset = j + 1; + } + } + } + } + } else if ((code >= 65/*A*/ && code <= 90/*Z*/) || + (code >= 97/*a*/ && code <= 122/*z*/)) { + // Possible device root + + code = path.charCodeAt(1); + if (path.charCodeAt(1) === 58/*:*/) { + rootEnd = offset = 2; + if (len > 2) { + code = path.charCodeAt(2); + if (code === 47/*/*/ || code === 92/*\*/) + rootEnd = offset = 3; + } + } + } + } else if (code === 47/*/*/ || code === 92/*\*/) { + return path[0]; + } + + for (var i = len - 1; i >= offset; --i) { + code = path.charCodeAt(i); + if (code === 47/*/*/ || code === 92/*\*/) { + if (!matchedSlash) { + end = i; + break; + } + } else { + // We saw the first non-path separator + matchedSlash = false; + } + } + + if (end === -1) { + if (rootEnd === -1) + return '.'; + else + end = rootEnd; + } + return path.slice(0, end); +} + +module.exports = process.platform === 'win32' ? win32 : posix; +module.exports.posix = posix; +module.exports.win32 = win32; diff --git a/tools/node_modules/eslint/node_modules/path-dirname/license b/tools/node_modules/eslint/node_modules/path-dirname/license new file mode 100644 index 00000000000000..1981663ad8f104 --- /dev/null +++ b/tools/node_modules/eslint/node_modules/path-dirname/license @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) Elan Shanker and Node.js contributors. All rights reserved. + +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/path-dirname/package.json b/tools/node_modules/eslint/node_modules/path-dirname/package.json new file mode 100644 index 00000000000000..81aad7d043f386 --- /dev/null +++ b/tools/node_modules/eslint/node_modules/path-dirname/package.json @@ -0,0 +1,40 @@ +{ + "author": { + "name": "Elan Shanker" + }, + "bugs": { + "url": "https://github.com/es128/path-dirname/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Node.js path.dirname() ponyfill", + "files": [ + "index.js" + ], + "homepage": "https://github.com/es128/path-dirname#readme", + "keywords": [ + "dirname", + "dir", + "path", + "paths", + "file", + "built-in", + "util", + "utils", + "core", + "stdlib", + "ponyfill", + "polyfill", + "shim" + ], + "license": "MIT", + "name": "path-dirname", + "repository": { + "type": "git", + "url": "git+https://github.com/es128/path-dirname.git" + }, + "scripts": { + "test": "node test.js" + }, + "version": "1.0.2" +} \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/path-dirname/readme.md b/tools/node_modules/eslint/node_modules/path-dirname/readme.md new file mode 100644 index 00000000000000..652a5623dfca72 --- /dev/null +++ b/tools/node_modules/eslint/node_modules/path-dirname/readme.md @@ -0,0 +1,53 @@ +# path-dirname [![Build Status](https://travis-ci.org/es128/path-dirname.svg?branch=master)](https://travis-ci.org/es128/path-dirname) + +> Node.js [`path.dirname()`](https://nodejs.org/api/path.html#path_path_dirname_path) [ponyfill](https://ponyfill.com) + +This was needed in order to expose `path.posix.dirname()` on Node.js v0.10 + +## Install + +``` +$ npm install --save path-dirname +``` + + +## Usage + +```js +const pathDirname = require('path-dirname'); + +pathDirname('/home/foo'); +//=> '/home' +pathDirname('C:\\Users\\foo'); +//=> 'C:\\Users' +pathDirname('foo'); +//=> '.' +pathDirname('foo/bar'); +//=> 'foo' + +//Using posix version for consistent output when dealing with glob escape chars +pathDirname.win32('C:\\Users\\foo/\\*bar'); +//=> 'C:\\Users\\foo/' +pathDirname.posix('C:\\Users\\foo/\\*bar'); +//=> 'C:\\Users\\foo' +``` + + +## API + +See the [`path.dirname()` docs](https://nodejs.org/api/path.html#path_path_dirname_path). + +### pathDirname(path) + +### pathDirname.posix(path) + +POSIX specific version. + +### pathDirname.win32(path) + +Windows specific version. + + +## License + +MIT diff --git a/tools/node_modules/eslint/node_modules/path-is-inside/lib/path-is-inside.js b/tools/node_modules/eslint/node_modules/path-is-inside/lib/path-is-inside.js deleted file mode 100644 index 596dfd3b3c5d01..00000000000000 --- a/tools/node_modules/eslint/node_modules/path-is-inside/lib/path-is-inside.js +++ /dev/null @@ -1,28 +0,0 @@ -"use strict"; - -var path = require("path"); - -module.exports = function (thePath, potentialParent) { - // For inside-directory checking, we want to allow trailing slashes, so normalize. - thePath = stripTrailingSep(thePath); - potentialParent = stripTrailingSep(potentialParent); - - // Node treats only Windows as case-insensitive in its path module; we follow those conventions. - if (process.platform === "win32") { - thePath = thePath.toLowerCase(); - potentialParent = potentialParent.toLowerCase(); - } - - return thePath.lastIndexOf(potentialParent, 0) === 0 && - ( - thePath[potentialParent.length] === path.sep || - thePath[potentialParent.length] === undefined - ); -}; - -function stripTrailingSep(thePath) { - if (thePath[thePath.length - 1] === path.sep) { - return thePath.slice(0, -1); - } - return thePath; -} diff --git a/tools/node_modules/eslint/node_modules/path-is-inside/package.json b/tools/node_modules/eslint/node_modules/path-is-inside/package.json deleted file mode 100644 index 0a6632f5fd2a96..00000000000000 --- a/tools/node_modules/eslint/node_modules/path-is-inside/package.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "author": { - "name": "Domenic Denicola", - "email": "d@domenic.me", - "url": "https://domenic.me" - }, - "bugs": { - "url": "https://github.com/domenic/path-is-inside/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Tests whether one path is inside another path", - "devDependencies": { - "jshint": "~2.3.0", - "mocha": "~1.15.1" - }, - "files": [ - "lib" - ], - "homepage": "https://github.com/domenic/path-is-inside#readme", - "keywords": [ - "path", - "directory", - "folder", - "inside", - "relative" - ], - "license": "(WTFPL OR MIT)", - "main": "lib/path-is-inside.js", - "name": "path-is-inside", - "repository": { - "type": "git", - "url": "git+https://github.com/domenic/path-is-inside.git" - }, - "scripts": { - "lint": "jshint lib", - "test": "mocha" - }, - "version": "1.0.2" -} \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/progress/README.md b/tools/node_modules/eslint/node_modules/progress/Readme.md similarity index 100% rename from tools/node_modules/eslint/node_modules/progress/README.md rename to tools/node_modules/eslint/node_modules/progress/Readme.md diff --git a/tools/node_modules/eslint/node_modules/rxjs/README.md b/tools/node_modules/eslint/node_modules/rxjs/README.md index df22c904342017..20e4d8bcba3f0e 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/README.md +++ b/tools/node_modules/eslint/node_modules/rxjs/README.md @@ -27,7 +27,7 @@ Reactive Extensions Library for JavaScript. This is a rewrite of [Reactive-Exten - [Contribution Guidelines](CONTRIBUTING.md) - [Maintainer Guidelines](doc/maintainer-guidelines.md) - [Creating Operators](doc/operator-creation.md) -- [API Documentation (WIP)](https://rxjs-dev.firebaseapp.com/) +- [API Documentation (WIP)](https://rxjs.dev/) ## Versions In This Repository diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/README.md b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/README.md index df22c904342017..20e4d8bcba3f0e 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/README.md +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/README.md @@ -27,7 +27,7 @@ Reactive Extensions Library for JavaScript. This is a rewrite of [Reactive-Exten - [Contribution Guidelines](CONTRIBUTING.md) - [Maintainer Guidelines](doc/maintainer-guidelines.md) - [Creating Operators](doc/operator-creation.md) -- [API Documentation (WIP)](https://rxjs-dev.firebaseapp.com/) +- [API Documentation (WIP)](https://rxjs.dev/) ## Versions In This Repository diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/fetch/index.js b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/fetch/index.js new file mode 100644 index 00000000000000..e851987c6e1c6d --- /dev/null +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/fetch/index.js @@ -0,0 +1,2 @@ +export { fromFetch } from '../internal/observable/dom/fetch'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/index.js b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/index.js index f3b5f95b32c7bd..a8a925e660c444 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/index.js +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/index.js @@ -14,7 +14,7 @@ export { VirtualTimeScheduler, VirtualAction } from './internal/scheduler/Virtua export { Scheduler } from './internal/Scheduler'; export { Subscription } from './internal/Subscription'; export { Subscriber } from './internal/Subscriber'; -export { Notification } from './internal/Notification'; +export { Notification, NotificationKind } from './internal/Notification'; export { pipe } from './internal/util/pipe'; export { noop } from './internal/util/noop'; export { identity } from './internal/util/identity'; @@ -42,12 +42,14 @@ export { never } from './internal/observable/never'; export { of } from './internal/observable/of'; export { onErrorResumeNext } from './internal/observable/onErrorResumeNext'; export { pairs } from './internal/observable/pairs'; +export { partition } from './internal/observable/partition'; export { race } from './internal/observable/race'; export { range } from './internal/observable/range'; export { throwError } from './internal/observable/throwError'; export { timer } from './internal/observable/timer'; export { using } from './internal/observable/using'; export { zip } from './internal/observable/zip'; +export { scheduled } from './internal/scheduled/scheduled'; export { EMPTY } from './internal/observable/empty'; export { NEVER } from './internal/observable/never'; export { config } from './internal/config'; diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/Notification.js b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/Notification.js index 329cdd447fa218..29713d053afa62 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/Notification.js +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/Notification.js @@ -12,26 +12,26 @@ export class Notification { this.kind = kind; this.value = value; this.error = error; - this.hasValue = kind === "N"; + this.hasValue = kind === 'N'; } observe(observer) { switch (this.kind) { - case "N": + case 'N': return observer.next && observer.next(this.value); - case "E": + case 'E': return observer.error && observer.error(this.error); - case "C": + case 'C': return observer.complete && observer.complete(); } } do(next, error, complete) { const kind = this.kind; switch (kind) { - case "N": + case 'N': return next && next(this.value); - case "E": + case 'E': return error && error(this.error); - case "C": + case 'C': return complete && complete(); } } @@ -46,28 +46,28 @@ export class Notification { toObservable() { const kind = this.kind; switch (kind) { - case "N": + case 'N': return of(this.value); - case "E": + case 'E': return throwError(this.error); - case "C": + case 'C': return empty(); } throw new Error('unexpected notification kind value'); } static createNext(value) { if (typeof value !== 'undefined') { - return new Notification("N", value); + return new Notification('N', value); } return Notification.undefinedValueNotification; } static createError(err) { - return new Notification("E", undefined, err); + return new Notification('E', undefined, err); } static createComplete() { return Notification.completeNotification; } } -Notification.completeNotification = new Notification("C"); -Notification.undefinedValueNotification = new Notification("N", undefined); +Notification.completeNotification = new Notification('C'); +Notification.undefinedValueNotification = new Notification('N', undefined); //# sourceMappingURL=Notification.js.map \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/Observable.js b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/Observable.js index bc603ce7f56948..4904b3f57da109 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/Observable.js +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/Observable.js @@ -1,6 +1,6 @@ import { canReportError } from './util/canReportError'; import { toSubscriber } from './util/toSubscriber'; -import { observable as Symbol_observable } from '../internal/symbol/observable'; +import { observable as Symbol_observable } from './symbol/observable'; import { pipeFromArray } from './util/pipe'; import { config } from './config'; export class Observable { diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/Subscriber.js b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/Subscriber.js index 42df33c7c798da..7dfed3c853ccc7 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/Subscriber.js +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/Subscriber.js @@ -80,14 +80,12 @@ export class Subscriber extends Subscription { this.unsubscribe(); } _unsubscribeAndRecycle() { - const { _parent, _parents } = this; - this._parent = null; - this._parents = null; + const { _parentOrParents } = this; + this._parentOrParents = null; this.unsubscribe(); this.closed = false; this.isStopped = false; - this._parent = _parent; - this._parents = _parents; + this._parentOrParents = _parentOrParents; return this; } } diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/Subscription.js b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/Subscription.js index b93bf0b65f468e..78301c66d846e8 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/Subscription.js +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/Subscription.js @@ -5,42 +5,41 @@ import { UnsubscriptionError } from './util/UnsubscriptionError'; export class Subscription { constructor(unsubscribe) { this.closed = false; - this._parent = null; - this._parents = null; + this._parentOrParents = null; this._subscriptions = null; if (unsubscribe) { this._unsubscribe = unsubscribe; } } unsubscribe() { - let hasErrors = false; let errors; if (this.closed) { return; } - let { _parent, _parents, _unsubscribe, _subscriptions } = this; + let { _parentOrParents, _unsubscribe, _subscriptions } = this; this.closed = true; - this._parent = null; - this._parents = null; + this._parentOrParents = null; this._subscriptions = null; - let index = -1; - let len = _parents ? _parents.length : 0; - while (_parent) { - _parent.remove(this); - _parent = ++index < len && _parents[index] || null; + if (_parentOrParents instanceof Subscription) { + _parentOrParents.remove(this); + } + else if (_parentOrParents !== null) { + for (let index = 0; index < _parentOrParents.length; ++index) { + const parent = _parentOrParents[index]; + parent.remove(this); + } } if (isFunction(_unsubscribe)) { try { _unsubscribe.call(this); } catch (e) { - hasErrors = true; errors = e instanceof UnsubscriptionError ? flattenUnsubscriptionErrors(e.errors) : [e]; } } if (isArray(_subscriptions)) { - index = -1; - len = _subscriptions.length; + let index = -1; + let len = _subscriptions.length; while (++index < len) { const sub = _subscriptions[index]; if (isObject(sub)) { @@ -48,7 +47,6 @@ export class Subscription { sub.unsubscribe(); } catch (e) { - hasErrors = true; errors = errors || []; if (e instanceof UnsubscriptionError) { errors = errors.concat(flattenUnsubscriptionErrors(e.errors)); @@ -60,12 +58,15 @@ export class Subscription { } } } - if (hasErrors) { + if (errors) { throw new UnsubscriptionError(errors); } } add(teardown) { let subscription = teardown; + if (!teardown) { + return Subscription.EMPTY; + } switch (typeof teardown) { case 'function': subscription = new Subscription(teardown); @@ -84,20 +85,31 @@ export class Subscription { } break; default: { - if (!teardown) { - return Subscription.EMPTY; - } throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.'); } } - if (subscription._addParent(this)) { - const subscriptions = this._subscriptions; - if (subscriptions) { - subscriptions.push(subscription); - } - else { - this._subscriptions = [subscription]; + let { _parentOrParents } = subscription; + if (_parentOrParents === null) { + subscription._parentOrParents = this; + } + else if (_parentOrParents instanceof Subscription) { + if (_parentOrParents === this) { + return subscription; } + subscription._parentOrParents = [_parentOrParents, this]; + } + else if (_parentOrParents.indexOf(this) === -1) { + _parentOrParents.push(this); + } + else { + return subscription; + } + const subscriptions = this._subscriptions; + if (subscriptions === null) { + this._subscriptions = [subscription]; + } + else { + subscriptions.push(subscription); } return subscription; } @@ -110,25 +122,6 @@ export class Subscription { } } } - _addParent(parent) { - let { _parent, _parents } = this; - if (_parent === parent) { - return false; - } - else if (!_parent) { - this._parent = parent; - return true; - } - else if (!_parents) { - this._parents = [parent]; - return true; - } - else if (_parents.indexOf(parent) === -1) { - _parents.push(parent); - return true; - } - return false; - } } Subscription.EMPTY = (function (empty) { empty.closed = true; diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/observable/ConnectableObservable.js b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/observable/ConnectableObservable.js index a1ac3f7978186f..6704cfbfd80b8e 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/observable/ConnectableObservable.js +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/observable/ConnectableObservable.js @@ -32,9 +32,6 @@ export class ConnectableObservable extends Observable { this._connection = null; connection = Subscription.EMPTY; } - else { - this._connection = connection; - } } return connection; } diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/observable/dom/fetch.js b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/observable/dom/fetch.js new file mode 100644 index 00000000000000..d9adff6d76d2f7 --- /dev/null +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/observable/dom/fetch.js @@ -0,0 +1,41 @@ +import { Observable } from '../../Observable'; +export function fromFetch(input, init) { + return new Observable(subscriber => { + const controller = new AbortController(); + const signal = controller.signal; + let outerSignalHandler; + let abortable = true; + let unsubscribed = false; + if (init) { + if (init.signal) { + outerSignalHandler = () => { + if (!signal.aborted) { + controller.abort(); + } + }; + init.signal.addEventListener('abort', outerSignalHandler); + } + init.signal = signal; + } + else { + init = { signal }; + } + fetch(input, init).then(response => { + abortable = false; + subscriber.next(response); + subscriber.complete(); + }).catch(err => { + abortable = false; + if (!unsubscribed) { + subscriber.error(err); + } + }); + return () => { + unsubscribed = true; + if (abortable) { + controller.abort(); + } + }; + }); +} +//# sourceMappingURL=fetch.js.map \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/observable/empty.js b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/observable/empty.js index 91faf2d83f803f..6cbbbdc6780dc2 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/observable/empty.js +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/observable/empty.js @@ -3,7 +3,7 @@ export const EMPTY = new Observable(subscriber => subscriber.complete()); export function empty(scheduler) { return scheduler ? emptyScheduled(scheduler) : EMPTY; } -export function emptyScheduled(scheduler) { +function emptyScheduled(scheduler) { return new Observable(subscriber => scheduler.schedule(() => subscriber.complete())); } //# sourceMappingURL=empty.js.map \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/observable/forkJoin.js b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/observable/forkJoin.js index 9edad93056d351..ca915a1ce3c3aa 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/observable/forkJoin.js +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/observable/forkJoin.js @@ -1,65 +1,61 @@ import { Observable } from '../Observable'; import { isArray } from '../util/isArray'; -import { EMPTY } from './empty'; -import { subscribeToResult } from '../util/subscribeToResult'; -import { OuterSubscriber } from '../OuterSubscriber'; import { map } from '../operators/map'; +import { isObject } from '../util/isObject'; +import { from } from './from'; export function forkJoin(...sources) { - let resultSelector; - if (typeof sources[sources.length - 1] === 'function') { - resultSelector = sources.pop(); - } - if (sources.length === 1 && isArray(sources[0])) { - sources = sources[0]; - } - if (sources.length === 0) { - return EMPTY; + if (sources.length === 1) { + const first = sources[0]; + if (isArray(first)) { + return forkJoinInternal(first, null); + } + if (isObject(first) && Object.getPrototypeOf(first) === Object.prototype) { + const keys = Object.keys(first); + return forkJoinInternal(keys.map(key => first[key]), keys); + } } - if (resultSelector) { - return forkJoin(sources).pipe(map(args => resultSelector(...args))); + if (typeof sources[sources.length - 1] === 'function') { + const resultSelector = sources.pop(); + sources = (sources.length === 1 && isArray(sources[0])) ? sources[0] : sources; + return forkJoinInternal(sources, null).pipe(map((args) => resultSelector(...args))); } - return new Observable(subscriber => { - return new ForkJoinSubscriber(subscriber, sources); - }); + return forkJoinInternal(sources, null); } -class ForkJoinSubscriber extends OuterSubscriber { - constructor(destination, sources) { - super(destination); - this.sources = sources; - this.completed = 0; - this.haveValues = 0; +function forkJoinInternal(sources, keys) { + return new Observable(subscriber => { const len = sources.length; - this.values = new Array(len); - for (let i = 0; i < len; i++) { - const source = sources[i]; - const innerSubscription = subscribeToResult(this, source, null, i); - if (innerSubscription) { - this.add(innerSubscription); - } - } - } - notifyNext(outerValue, innerValue, outerIndex, innerIndex, innerSub) { - this.values[outerIndex] = innerValue; - if (!innerSub._hasValue) { - innerSub._hasValue = true; - this.haveValues++; - } - } - notifyComplete(innerSub) { - const { destination, haveValues, values } = this; - const len = values.length; - if (!innerSub._hasValue) { - destination.complete(); + if (len === 0) { + subscriber.complete(); return; } - this.completed++; - if (this.completed !== len) { - return; - } - if (haveValues === len) { - destination.next(values); + const values = new Array(len); + let completed = 0; + let emitted = 0; + for (let i = 0; i < len; i++) { + const source = from(sources[i]); + let hasValue = false; + subscriber.add(source.subscribe({ + next: value => { + if (!hasValue) { + hasValue = true; + emitted++; + } + values[i] = value; + }, + error: err => subscriber.error(err), + complete: () => { + completed++; + if (completed === len || !hasValue) { + if (emitted === len) { + subscriber.next(keys ? + keys.reduce((result, key, i) => (result[key] = values[i], result), {}) : + values); + } + subscriber.complete(); + } + } + })); } - destination.complete(); - } + }); } //# sourceMappingURL=forkJoin.js.map \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/observable/from.js b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/observable/from.js index 8c155566ab7e4f..8dfff4e7f3b500 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/observable/from.js +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/observable/from.js @@ -1,13 +1,6 @@ import { Observable } from '../Observable'; -import { isPromise } from '../util/isPromise'; -import { isArrayLike } from '../util/isArrayLike'; -import { isInteropObservable } from '../util/isInteropObservable'; -import { isIterable } from '../util/isIterable'; -import { fromArray } from './fromArray'; -import { fromPromise } from './fromPromise'; -import { fromIterable } from './fromIterable'; -import { fromObservable } from './fromObservable'; import { subscribeTo } from '../util/subscribeTo'; +import { scheduled } from '../scheduled/scheduled'; export function from(input, scheduler) { if (!scheduler) { if (input instanceof Observable) { @@ -15,20 +8,8 @@ export function from(input, scheduler) { } return new Observable(subscribeTo(input)); } - if (input != null) { - if (isInteropObservable(input)) { - return fromObservable(input, scheduler); - } - else if (isPromise(input)) { - return fromPromise(input, scheduler); - } - else if (isArrayLike(input)) { - return fromArray(input, scheduler); - } - else if (isIterable(input) || typeof input === 'string') { - return fromIterable(input, scheduler); - } + else { + return scheduled(input, scheduler); } - throw new TypeError((input !== null && typeof input || input) + ' is not observable'); } //# sourceMappingURL=from.js.map \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/observable/fromArray.js b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/observable/fromArray.js index f54d96b887bbe7..b7384336ce1000 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/observable/fromArray.js +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/observable/fromArray.js @@ -1,26 +1,12 @@ import { Observable } from '../Observable'; -import { Subscription } from '../Subscription'; import { subscribeToArray } from '../util/subscribeToArray'; +import { scheduleArray } from '../scheduled/scheduleArray'; export function fromArray(input, scheduler) { if (!scheduler) { return new Observable(subscribeToArray(input)); } else { - return new Observable(subscriber => { - const sub = new Subscription(); - let i = 0; - sub.add(scheduler.schedule(function () { - if (i === input.length) { - subscriber.complete(); - return; - } - subscriber.next(input[i++]); - if (!subscriber.closed) { - sub.add(this.schedule()); - } - })); - return sub; - }); + return scheduleArray(input, scheduler); } } //# sourceMappingURL=fromArray.js.map \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/observable/fromIterable.js b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/observable/fromIterable.js index 60b390e5eee975..4788d58f66b7cc 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/observable/fromIterable.js +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/observable/fromIterable.js @@ -1,7 +1,6 @@ import { Observable } from '../Observable'; -import { Subscription } from '../Subscription'; -import { iterator as Symbol_iterator } from '../symbol/iterator'; import { subscribeToIterable } from '../util/subscribeToIterable'; +import { scheduleIterable } from '../scheduled/scheduleIterable'; export function fromIterable(input, scheduler) { if (!input) { throw new Error('Iterable cannot be null'); @@ -10,42 +9,7 @@ export function fromIterable(input, scheduler) { return new Observable(subscribeToIterable(input)); } else { - return new Observable(subscriber => { - const sub = new Subscription(); - let iterator; - sub.add(() => { - if (iterator && typeof iterator.return === 'function') { - iterator.return(); - } - }); - sub.add(scheduler.schedule(() => { - iterator = input[Symbol_iterator](); - sub.add(scheduler.schedule(function () { - if (subscriber.closed) { - return; - } - let value; - let done; - try { - const result = iterator.next(); - value = result.value; - done = result.done; - } - catch (err) { - subscriber.error(err); - return; - } - if (done) { - subscriber.complete(); - } - else { - subscriber.next(value); - this.schedule(); - } - })); - })); - return sub; - }); + return scheduleIterable(input, scheduler); } } //# sourceMappingURL=fromIterable.js.map \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/observable/fromObservable.js b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/observable/fromObservable.js deleted file mode 100644 index 36484185ef014f..00000000000000 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/observable/fromObservable.js +++ /dev/null @@ -1,24 +0,0 @@ -import { Observable } from '../Observable'; -import { Subscription } from '../Subscription'; -import { observable as Symbol_observable } from '../symbol/observable'; -import { subscribeToObservable } from '../util/subscribeToObservable'; -export function fromObservable(input, scheduler) { - if (!scheduler) { - return new Observable(subscribeToObservable(input)); - } - else { - return new Observable(subscriber => { - const sub = new Subscription(); - sub.add(scheduler.schedule(() => { - const observable = input[Symbol_observable](); - sub.add(observable.subscribe({ - next(value) { sub.add(scheduler.schedule(() => subscriber.next(value))); }, - error(err) { sub.add(scheduler.schedule(() => subscriber.error(err))); }, - complete() { sub.add(scheduler.schedule(() => subscriber.complete())); }, - })); - })); - return sub; - }); - } -} -//# sourceMappingURL=fromObservable.js.map \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/observable/fromPromise.js b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/observable/fromPromise.js index a2aa4c00fff23d..127086cfa781cf 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/observable/fromPromise.js +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/observable/fromPromise.js @@ -1,23 +1,12 @@ import { Observable } from '../Observable'; -import { Subscription } from '../Subscription'; import { subscribeToPromise } from '../util/subscribeToPromise'; +import { schedulePromise } from '../scheduled/schedulePromise'; export function fromPromise(input, scheduler) { if (!scheduler) { return new Observable(subscribeToPromise(input)); } else { - return new Observable(subscriber => { - const sub = new Subscription(); - sub.add(scheduler.schedule(() => input.then(value => { - sub.add(scheduler.schedule(() => { - subscriber.next(value); - sub.add(scheduler.schedule(() => subscriber.complete())); - })); - }, err => { - sub.add(scheduler.schedule(() => subscriber.error(err))); - }))); - return sub; - }); + return schedulePromise(input, scheduler); } } //# sourceMappingURL=fromPromise.js.map \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/observable/of.js b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/observable/of.js index 8fc0fe125fd54c..fdfd611a3f3a10 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/observable/of.js +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/observable/of.js @@ -1,22 +1,14 @@ import { isScheduler } from '../util/isScheduler'; import { fromArray } from './fromArray'; -import { empty } from './empty'; -import { scalar } from './scalar'; +import { scheduleArray } from '../scheduled/scheduleArray'; export function of(...args) { let scheduler = args[args.length - 1]; if (isScheduler(scheduler)) { args.pop(); + return scheduleArray(args, scheduler); } else { - scheduler = undefined; - } - switch (args.length) { - case 0: - return empty(scheduler); - case 1: - return scheduler ? fromArray(args, scheduler) : scalar(args[0]); - default: - return fromArray(args, scheduler); + return fromArray(args); } } //# sourceMappingURL=of.js.map \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/observable/partition.js b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/observable/partition.js new file mode 100644 index 00000000000000..a34a7342b1a1d4 --- /dev/null +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/observable/partition.js @@ -0,0 +1,11 @@ +import { not } from '../util/not'; +import { subscribeTo } from '../util/subscribeTo'; +import { filter } from '../operators/filter'; +import { Observable } from '../Observable'; +export function partition(source, predicate, thisArg) { + return [ + filter(predicate, thisArg)(new Observable(subscribeTo(source))), + filter(not(predicate, thisArg))(new Observable(subscribeTo(source))) + ]; +} +//# sourceMappingURL=partition.js.map \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/observable/scalar.js b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/observable/scalar.js deleted file mode 100644 index 0ab8359af15521..00000000000000 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/observable/scalar.js +++ /dev/null @@ -1,11 +0,0 @@ -import { Observable } from '../Observable'; -export function scalar(value) { - const result = new Observable(subscriber => { - subscriber.next(value); - subscriber.complete(); - }); - result._isScalar = true; - result.value = value; - return result; -} -//# sourceMappingURL=scalar.js.map \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/operators/endWith.js b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/operators/endWith.js index 6f36e2555f8691..cf52a35e5d3e52 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/operators/endWith.js +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/operators/endWith.js @@ -1,27 +1,6 @@ -import { fromArray } from '../observable/fromArray'; -import { scalar } from '../observable/scalar'; -import { empty } from '../observable/empty'; -import { concat as concatStatic } from '../observable/concat'; -import { isScheduler } from '../util/isScheduler'; +import { concat } from '../observable/concat'; +import { of } from '../observable/of'; export function endWith(...array) { - return (source) => { - let scheduler = array[array.length - 1]; - if (isScheduler(scheduler)) { - array.pop(); - } - else { - scheduler = null; - } - const len = array.length; - if (len === 1 && !scheduler) { - return concatStatic(source, scalar(array[0])); - } - else if (len > 0) { - return concatStatic(source, fromArray(array, scheduler)); - } - else { - return concatStatic(source, empty(scheduler)); - } - }; + return (source) => concat(source, of(...array)); } //# sourceMappingURL=endWith.js.map \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/operators/pairwise.js b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/operators/pairwise.js index 07647bd3727867..001367263dd6a2 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/operators/pairwise.js +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/operators/pairwise.js @@ -13,13 +13,17 @@ class PairwiseSubscriber extends Subscriber { this.hasPrev = false; } _next(value) { + let pair; if (this.hasPrev) { - this.destination.next([this.prev, value]); + pair = [this.prev, value]; } else { this.hasPrev = true; } this.prev = value; + if (pair) { + this.destination.next(pair); + } } } //# sourceMappingURL=pairwise.js.map \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/operators/startWith.js b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/operators/startWith.js index 495d3cec97ce77..a9a7c273938cf7 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/operators/startWith.js +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/operators/startWith.js @@ -1,27 +1,13 @@ -import { fromArray } from '../observable/fromArray'; -import { scalar } from '../observable/scalar'; -import { empty } from '../observable/empty'; -import { concat as concatStatic } from '../observable/concat'; +import { concat } from '../observable/concat'; import { isScheduler } from '../util/isScheduler'; export function startWith(...array) { - return (source) => { - let scheduler = array[array.length - 1]; - if (isScheduler(scheduler)) { - array.pop(); - } - else { - scheduler = null; - } - const len = array.length; - if (len === 1 && !scheduler) { - return concatStatic(scalar(array[0]), source); - } - else if (len > 0) { - return concatStatic(fromArray(array, scheduler), source); - } - else { - return concatStatic(empty(scheduler), source); - } - }; + const scheduler = array[array.length - 1]; + if (isScheduler(scheduler)) { + array.pop(); + return (source) => concat(array, source, scheduler); + } + else { + return (source) => concat(array, source); + } } //# sourceMappingURL=startWith.js.map \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/operators/throttleTime.js b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/operators/throttleTime.js index 3a9268a098dc6b..3a1a9c5efa1423 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/operators/throttleTime.js +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/operators/throttleTime.js @@ -37,6 +37,10 @@ class ThrottleTimeSubscriber extends Subscriber { if (this.leading) { this.destination.next(value); } + else if (this.trailing) { + this._trailingValue = value; + this._hasTrailingValue = true; + } } } _complete() { diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/operators/throwIfEmpty.js b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/operators/throwIfEmpty.js index 5a042e9d5e43fa..9a422069465411 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/operators/throwIfEmpty.js +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/operators/throwIfEmpty.js @@ -1,14 +1,44 @@ -import { tap } from './tap'; import { EmptyError } from '../util/EmptyError'; -export const throwIfEmpty = (errorFactory = defaultErrorFactory) => tap({ - hasValue: false, - next() { this.hasValue = true; }, - complete() { +import { Subscriber } from '../Subscriber'; +export function throwIfEmpty(errorFactory = defaultErrorFactory) { + return (source) => { + return source.lift(new ThrowIfEmptyOperator(errorFactory)); + }; +} +class ThrowIfEmptyOperator { + constructor(errorFactory) { + this.errorFactory = errorFactory; + } + call(subscriber, source) { + return source.subscribe(new ThrowIfEmptySubscriber(subscriber, this.errorFactory)); + } +} +class ThrowIfEmptySubscriber extends Subscriber { + constructor(destination, errorFactory) { + super(destination); + this.errorFactory = errorFactory; + this.hasValue = false; + } + _next(value) { + this.hasValue = true; + this.destination.next(value); + } + _complete() { if (!this.hasValue) { - throw errorFactory(); + let err; + try { + err = this.errorFactory(); + } + catch (e) { + err = e; + } + this.destination.error(err); + } + else { + return this.destination.complete(); } } -}); +} function defaultErrorFactory() { return new EmptyError(); } diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/scheduled/scheduleArray.js b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/scheduled/scheduleArray.js new file mode 100644 index 00000000000000..46045434dfbc7c --- /dev/null +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/scheduled/scheduleArray.js @@ -0,0 +1,20 @@ +import { Observable } from '../Observable'; +import { Subscription } from '../Subscription'; +export function scheduleArray(input, scheduler) { + return new Observable(subscriber => { + const sub = new Subscription(); + let i = 0; + sub.add(scheduler.schedule(function () { + if (i === input.length) { + subscriber.complete(); + return; + } + subscriber.next(input[i++]); + if (!subscriber.closed) { + sub.add(this.schedule()); + } + })); + return sub; + }); +} +//# sourceMappingURL=scheduleArray.js.map \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/scheduled/scheduleIterable.js b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/scheduled/scheduleIterable.js new file mode 100644 index 00000000000000..452d40d2259dba --- /dev/null +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/scheduled/scheduleIterable.js @@ -0,0 +1,45 @@ +import { Observable } from '../Observable'; +import { Subscription } from '../Subscription'; +import { iterator as Symbol_iterator } from '../symbol/iterator'; +export function scheduleIterable(input, scheduler) { + if (!input) { + throw new Error('Iterable cannot be null'); + } + return new Observable(subscriber => { + const sub = new Subscription(); + let iterator; + sub.add(() => { + if (iterator && typeof iterator.return === 'function') { + iterator.return(); + } + }); + sub.add(scheduler.schedule(() => { + iterator = input[Symbol_iterator](); + sub.add(scheduler.schedule(function () { + if (subscriber.closed) { + return; + } + let value; + let done; + try { + const result = iterator.next(); + value = result.value; + done = result.done; + } + catch (err) { + subscriber.error(err); + return; + } + if (done) { + subscriber.complete(); + } + else { + subscriber.next(value); + this.schedule(); + } + })); + })); + return sub; + }); +} +//# sourceMappingURL=scheduleIterable.js.map \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/scheduled/scheduleObservable.js b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/scheduled/scheduleObservable.js new file mode 100644 index 00000000000000..96ae599194acd3 --- /dev/null +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/scheduled/scheduleObservable.js @@ -0,0 +1,18 @@ +import { Observable } from '../Observable'; +import { Subscription } from '../Subscription'; +import { observable as Symbol_observable } from '../symbol/observable'; +export function scheduleObservable(input, scheduler) { + return new Observable(subscriber => { + const sub = new Subscription(); + sub.add(scheduler.schedule(() => { + const observable = input[Symbol_observable](); + sub.add(observable.subscribe({ + next(value) { sub.add(scheduler.schedule(() => subscriber.next(value))); }, + error(err) { sub.add(scheduler.schedule(() => subscriber.error(err))); }, + complete() { sub.add(scheduler.schedule(() => subscriber.complete())); }, + })); + })); + return sub; + }); +} +//# sourceMappingURL=scheduleObservable.js.map \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/scheduled/schedulePromise.js b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/scheduled/schedulePromise.js new file mode 100644 index 00000000000000..68d49388ba2a40 --- /dev/null +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/scheduled/schedulePromise.js @@ -0,0 +1,17 @@ +import { Observable } from '../Observable'; +import { Subscription } from '../Subscription'; +export function schedulePromise(input, scheduler) { + return new Observable(subscriber => { + const sub = new Subscription(); + sub.add(scheduler.schedule(() => input.then(value => { + sub.add(scheduler.schedule(() => { + subscriber.next(value); + sub.add(scheduler.schedule(() => subscriber.complete())); + })); + }, err => { + sub.add(scheduler.schedule(() => subscriber.error(err))); + }))); + return sub; + }); +} +//# sourceMappingURL=schedulePromise.js.map \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/scheduled/scheduled.js b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/scheduled/scheduled.js new file mode 100644 index 00000000000000..554d1a2d968b07 --- /dev/null +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/scheduled/scheduled.js @@ -0,0 +1,26 @@ +import { scheduleObservable } from './scheduleObservable'; +import { schedulePromise } from './schedulePromise'; +import { scheduleArray } from './scheduleArray'; +import { scheduleIterable } from './scheduleIterable'; +import { isInteropObservable } from '../util/isInteropObservable'; +import { isPromise } from '../util/isPromise'; +import { isArrayLike } from '../util/isArrayLike'; +import { isIterable } from '../util/isIterable'; +export function scheduled(input, scheduler) { + if (input != null) { + if (isInteropObservable(input)) { + return scheduleObservable(input, scheduler); + } + else if (isPromise(input)) { + return schedulePromise(input, scheduler); + } + else if (isArrayLike(input)) { + return scheduleArray(input, scheduler); + } + else if (isIterable(input) || typeof input === 'string') { + return scheduleIterable(input, scheduler); + } + } + throw new TypeError((input !== null && typeof input || input) + ' is not observable'); +} +//# sourceMappingURL=scheduled.js.map \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/util/hostReportError.js b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/util/hostReportError.js index 05f5533fec1992..3851a362b9c2a0 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/util/hostReportError.js +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/util/hostReportError.js @@ -1,4 +1,4 @@ export function hostReportError(err) { - setTimeout(() => { throw err; }); + setTimeout(() => { throw err; }, 0); } //# sourceMappingURL=hostReportError.js.map \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/util/subscribeTo.js b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/util/subscribeTo.js index 499dd67c6d7c27..71a569bf3e2164 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/util/subscribeTo.js +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/util/subscribeTo.js @@ -1,4 +1,3 @@ -import { Observable } from '../Observable'; import { subscribeToArray } from './subscribeToArray'; import { subscribeToPromise } from './subscribeToPromise'; import { subscribeToIterable } from './subscribeToIterable'; @@ -9,19 +8,7 @@ import { isObject } from './isObject'; import { iterator as Symbol_iterator } from '../symbol/iterator'; import { observable as Symbol_observable } from '../symbol/observable'; export const subscribeTo = (result) => { - if (result instanceof Observable) { - return (subscriber) => { - if (result._isScalar) { - subscriber.next(result.value); - subscriber.complete(); - return undefined; - } - else { - return result.subscribe(subscriber); - } - }; - } - else if (!!result && typeof result[Symbol_observable] === 'function') { + if (!!result && typeof result[Symbol_observable] === 'function') { return subscribeToObservable(result); } else if (isArrayLike(result)) { diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/util/subscribeToArray.js b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/util/subscribeToArray.js index 1364f7e8aa760e..2693661a36c6ad 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/util/subscribeToArray.js +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/util/subscribeToArray.js @@ -2,8 +2,6 @@ export const subscribeToArray = (array) => (subscriber) => { for (let i = 0, len = array.length; i < len && !subscriber.closed; i++) { subscriber.next(array[i]); } - if (!subscriber.closed) { - subscriber.complete(); - } + subscriber.complete(); }; //# sourceMappingURL=subscribeToArray.js.map \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/util/subscribeToResult.js b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/util/subscribeToResult.js index 00282e75757c23..1145d2b8a4199a 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/util/subscribeToResult.js +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm2015/internal/util/subscribeToResult.js @@ -1,8 +1,12 @@ import { InnerSubscriber } from '../InnerSubscriber'; import { subscribeTo } from './subscribeTo'; +import { Observable } from '../Observable'; export function subscribeToResult(outerSubscriber, result, outerValue, outerIndex, destination = new InnerSubscriber(outerSubscriber, outerValue, outerIndex)) { if (destination.closed) { - return; + return undefined; + } + if (result instanceof Observable) { + return result.subscribe(destination); } return subscribeTo(result)(destination); } diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm5/README.md b/tools/node_modules/eslint/node_modules/rxjs/_esm5/README.md index df22c904342017..20e4d8bcba3f0e 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm5/README.md +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm5/README.md @@ -27,7 +27,7 @@ Reactive Extensions Library for JavaScript. This is a rewrite of [Reactive-Exten - [Contribution Guidelines](CONTRIBUTING.md) - [Maintainer Guidelines](doc/maintainer-guidelines.md) - [Creating Operators](doc/operator-creation.md) -- [API Documentation (WIP)](https://rxjs-dev.firebaseapp.com/) +- [API Documentation (WIP)](https://rxjs.dev/) ## Versions In This Repository diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm5/fetch/index.js b/tools/node_modules/eslint/node_modules/rxjs/_esm5/fetch/index.js new file mode 100644 index 00000000000000..d6c825b0b14134 --- /dev/null +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm5/fetch/index.js @@ -0,0 +1,3 @@ +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +export { fromFetch } from '../internal/observable/dom/fetch'; +//# sourceMappingURL=index.js.map diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm5/index.js b/tools/node_modules/eslint/node_modules/rxjs/_esm5/index.js index 8638ae8e863639..c260ad07886555 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm5/index.js +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm5/index.js @@ -15,7 +15,7 @@ export { VirtualTimeScheduler, VirtualAction } from './internal/scheduler/Virtua export { Scheduler } from './internal/Scheduler'; export { Subscription } from './internal/Subscription'; export { Subscriber } from './internal/Subscriber'; -export { Notification } from './internal/Notification'; +export { Notification, NotificationKind } from './internal/Notification'; export { pipe } from './internal/util/pipe'; export { noop } from './internal/util/noop'; export { identity } from './internal/util/identity'; @@ -43,12 +43,14 @@ export { never } from './internal/observable/never'; export { of } from './internal/observable/of'; export { onErrorResumeNext } from './internal/observable/onErrorResumeNext'; export { pairs } from './internal/observable/pairs'; +export { partition } from './internal/observable/partition'; export { race } from './internal/observable/race'; export { range } from './internal/observable/range'; export { throwError } from './internal/observable/throwError'; export { timer } from './internal/observable/timer'; export { using } from './internal/observable/using'; export { zip } from './internal/observable/zip'; +export { scheduled } from './internal/scheduled/scheduled'; export { EMPTY } from './internal/observable/empty'; export { NEVER } from './internal/observable/never'; export { config } from './internal/config'; diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/Notification.js b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/Notification.js index 7578ac210cd540..3f7dcd7ede421c 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/Notification.js +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/Notification.js @@ -13,26 +13,26 @@ var Notification = /*@__PURE__*/ (function () { this.kind = kind; this.value = value; this.error = error; - this.hasValue = kind === "N"; + this.hasValue = kind === 'N'; } Notification.prototype.observe = function (observer) { switch (this.kind) { - case "N": + case 'N': return observer.next && observer.next(this.value); - case "E": + case 'E': return observer.error && observer.error(this.error); - case "C": + case 'C': return observer.complete && observer.complete(); } }; Notification.prototype.do = function (next, error, complete) { var kind = this.kind; switch (kind) { - case "N": + case 'N': return next && next(this.value); - case "E": + case 'E': return error && error(this.error); - case "C": + case 'C': return complete && complete(); } }; @@ -47,29 +47,29 @@ var Notification = /*@__PURE__*/ (function () { Notification.prototype.toObservable = function () { var kind = this.kind; switch (kind) { - case "N": + case 'N': return of(this.value); - case "E": + case 'E': return throwError(this.error); - case "C": + case 'C': return empty(); } throw new Error('unexpected notification kind value'); }; Notification.createNext = function (value) { if (typeof value !== 'undefined') { - return new Notification("N", value); + return new Notification('N', value); } return Notification.undefinedValueNotification; }; Notification.createError = function (err) { - return new Notification("E", undefined, err); + return new Notification('E', undefined, err); }; Notification.createComplete = function () { return Notification.completeNotification; }; - Notification.completeNotification = new Notification("C"); - Notification.undefinedValueNotification = new Notification("N", undefined); + Notification.completeNotification = new Notification('C'); + Notification.undefinedValueNotification = new Notification('N', undefined); return Notification; }()); export { Notification }; diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/Observable.js b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/Observable.js index 644b4c92b73106..8f2ef3067df955 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/Observable.js +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/Observable.js @@ -1,7 +1,7 @@ -/** PURE_IMPORTS_START _util_canReportError,_util_toSubscriber,_internal_symbol_observable,_util_pipe,_config PURE_IMPORTS_END */ +/** PURE_IMPORTS_START _util_canReportError,_util_toSubscriber,_symbol_observable,_util_pipe,_config PURE_IMPORTS_END */ import { canReportError } from './util/canReportError'; import { toSubscriber } from './util/toSubscriber'; -import { observable as Symbol_observable } from '../internal/symbol/observable'; +import { observable as Symbol_observable } from './symbol/observable'; import { pipeFromArray } from './util/pipe'; import { config } from './config'; var Observable = /*@__PURE__*/ (function () { diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/Subscriber.js b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/Subscriber.js index 67815afe066af6..8610093795bd59 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/Subscriber.js +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/Subscriber.js @@ -84,14 +84,12 @@ var Subscriber = /*@__PURE__*/ (function (_super) { this.unsubscribe(); }; Subscriber.prototype._unsubscribeAndRecycle = function () { - var _a = this, _parent = _a._parent, _parents = _a._parents; - this._parent = null; - this._parents = null; + var _parentOrParents = this._parentOrParents; + this._parentOrParents = null; this.unsubscribe(); this.closed = false; this.isStopped = false; - this._parent = _parent; - this._parents = _parents; + this._parentOrParents = _parentOrParents; return this; }; return Subscriber; diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/Subscription.js b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/Subscription.js index bc1832c89c81d4..a0b8e6227957cb 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/Subscription.js +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/Subscription.js @@ -6,42 +6,41 @@ import { UnsubscriptionError } from './util/UnsubscriptionError'; var Subscription = /*@__PURE__*/ (function () { function Subscription(unsubscribe) { this.closed = false; - this._parent = null; - this._parents = null; + this._parentOrParents = null; this._subscriptions = null; if (unsubscribe) { this._unsubscribe = unsubscribe; } } Subscription.prototype.unsubscribe = function () { - var hasErrors = false; var errors; if (this.closed) { return; } - var _a = this, _parent = _a._parent, _parents = _a._parents, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions; + var _a = this, _parentOrParents = _a._parentOrParents, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions; this.closed = true; - this._parent = null; - this._parents = null; + this._parentOrParents = null; this._subscriptions = null; - var index = -1; - var len = _parents ? _parents.length : 0; - while (_parent) { - _parent.remove(this); - _parent = ++index < len && _parents[index] || null; + if (_parentOrParents instanceof Subscription) { + _parentOrParents.remove(this); + } + else if (_parentOrParents !== null) { + for (var index = 0; index < _parentOrParents.length; ++index) { + var parent_1 = _parentOrParents[index]; + parent_1.remove(this); + } } if (isFunction(_unsubscribe)) { try { _unsubscribe.call(this); } catch (e) { - hasErrors = true; errors = e instanceof UnsubscriptionError ? flattenUnsubscriptionErrors(e.errors) : [e]; } } if (isArray(_subscriptions)) { - index = -1; - len = _subscriptions.length; + var index = -1; + var len = _subscriptions.length; while (++index < len) { var sub = _subscriptions[index]; if (isObject(sub)) { @@ -49,7 +48,6 @@ var Subscription = /*@__PURE__*/ (function () { sub.unsubscribe(); } catch (e) { - hasErrors = true; errors = errors || []; if (e instanceof UnsubscriptionError) { errors = errors.concat(flattenUnsubscriptionErrors(e.errors)); @@ -61,12 +59,15 @@ var Subscription = /*@__PURE__*/ (function () { } } } - if (hasErrors) { + if (errors) { throw new UnsubscriptionError(errors); } }; Subscription.prototype.add = function (teardown) { var subscription = teardown; + if (!teardown) { + return Subscription.EMPTY; + } switch (typeof teardown) { case 'function': subscription = new Subscription(teardown); @@ -85,20 +86,31 @@ var Subscription = /*@__PURE__*/ (function () { } break; default: { - if (!teardown) { - return Subscription.EMPTY; - } throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.'); } } - if (subscription._addParent(this)) { - var subscriptions = this._subscriptions; - if (subscriptions) { - subscriptions.push(subscription); - } - else { - this._subscriptions = [subscription]; + var _parentOrParents = subscription._parentOrParents; + if (_parentOrParents === null) { + subscription._parentOrParents = this; + } + else if (_parentOrParents instanceof Subscription) { + if (_parentOrParents === this) { + return subscription; } + subscription._parentOrParents = [_parentOrParents, this]; + } + else if (_parentOrParents.indexOf(this) === -1) { + _parentOrParents.push(this); + } + else { + return subscription; + } + var subscriptions = this._subscriptions; + if (subscriptions === null) { + this._subscriptions = [subscription]; + } + else { + subscriptions.push(subscription); } return subscription; }; @@ -111,25 +123,6 @@ var Subscription = /*@__PURE__*/ (function () { } } }; - Subscription.prototype._addParent = function (parent) { - var _a = this, _parent = _a._parent, _parents = _a._parents; - if (_parent === parent) { - return false; - } - else if (!_parent) { - this._parent = parent; - return true; - } - else if (!_parents) { - this._parents = [parent]; - return true; - } - else if (_parents.indexOf(parent) === -1) { - _parents.push(parent); - return true; - } - return false; - }; Subscription.EMPTY = (function (empty) { empty.closed = true; return empty; diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/observable/ConnectableObservable.js b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/observable/ConnectableObservable.js index c6bbeb68191048..7c039da8063c58 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/observable/ConnectableObservable.js +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/observable/ConnectableObservable.js @@ -36,9 +36,6 @@ var ConnectableObservable = /*@__PURE__*/ (function (_super) { this._connection = null; connection = Subscription.EMPTY; } - else { - this._connection = connection; - } } return connection; }; diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/observable/dom/fetch.js b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/observable/dom/fetch.js new file mode 100644 index 00000000000000..67f2cbf4b2d8a8 --- /dev/null +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/observable/dom/fetch.js @@ -0,0 +1,42 @@ +/** PURE_IMPORTS_START _.._Observable PURE_IMPORTS_END */ +import { Observable } from '../../Observable'; +export function fromFetch(input, init) { + return new Observable(function (subscriber) { + var controller = new AbortController(); + var signal = controller.signal; + var outerSignalHandler; + var abortable = true; + var unsubscribed = false; + if (init) { + if (init.signal) { + outerSignalHandler = function () { + if (!signal.aborted) { + controller.abort(); + } + }; + init.signal.addEventListener('abort', outerSignalHandler); + } + init.signal = signal; + } + else { + init = { signal: signal }; + } + fetch(input, init).then(function (response) { + abortable = false; + subscriber.next(response); + subscriber.complete(); + }).catch(function (err) { + abortable = false; + if (!unsubscribed) { + subscriber.error(err); + } + }); + return function () { + unsubscribed = true; + if (abortable) { + controller.abort(); + } + }; + }); +} +//# sourceMappingURL=fetch.js.map diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/observable/empty.js b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/observable/empty.js index 93a3c5ec520a14..1c4b0c7d377657 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/observable/empty.js +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/observable/empty.js @@ -4,7 +4,7 @@ export var EMPTY = /*@__PURE__*/ new Observable(function (subscriber) { return s export function empty(scheduler) { return scheduler ? emptyScheduled(scheduler) : EMPTY; } -export function emptyScheduled(scheduler) { +function emptyScheduled(scheduler) { return new Observable(function (subscriber) { return scheduler.schedule(function () { return subscriber.complete(); }); }); } //# sourceMappingURL=empty.js.map diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/observable/forkJoin.js b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/observable/forkJoin.js index a732a53818d049..5c38fe7bd3cfa2 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/observable/forkJoin.js +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/observable/forkJoin.js @@ -1,74 +1,69 @@ -/** PURE_IMPORTS_START tslib,_Observable,_util_isArray,_empty,_util_subscribeToResult,_OuterSubscriber,_operators_map PURE_IMPORTS_END */ -import * as tslib_1 from "tslib"; +/** PURE_IMPORTS_START _Observable,_util_isArray,_operators_map,_util_isObject,_from PURE_IMPORTS_END */ import { Observable } from '../Observable'; import { isArray } from '../util/isArray'; -import { EMPTY } from './empty'; -import { subscribeToResult } from '../util/subscribeToResult'; -import { OuterSubscriber } from '../OuterSubscriber'; import { map } from '../operators/map'; +import { isObject } from '../util/isObject'; +import { from } from './from'; export function forkJoin() { var sources = []; for (var _i = 0; _i < arguments.length; _i++) { sources[_i] = arguments[_i]; } - var resultSelector; - if (typeof sources[sources.length - 1] === 'function') { - resultSelector = sources.pop(); - } - if (sources.length === 1 && isArray(sources[0])) { - sources = sources[0]; - } - if (sources.length === 0) { - return EMPTY; + if (sources.length === 1) { + var first_1 = sources[0]; + if (isArray(first_1)) { + return forkJoinInternal(first_1, null); + } + if (isObject(first_1) && Object.getPrototypeOf(first_1) === Object.prototype) { + var keys = Object.keys(first_1); + return forkJoinInternal(keys.map(function (key) { return first_1[key]; }), keys); + } } - if (resultSelector) { - return forkJoin(sources).pipe(map(function (args) { return resultSelector.apply(void 0, args); })); + if (typeof sources[sources.length - 1] === 'function') { + var resultSelector_1 = sources.pop(); + sources = (sources.length === 1 && isArray(sources[0])) ? sources[0] : sources; + return forkJoinInternal(sources, null).pipe(map(function (args) { return resultSelector_1.apply(void 0, args); })); } - return new Observable(function (subscriber) { - return new ForkJoinSubscriber(subscriber, sources); - }); + return forkJoinInternal(sources, null); } -var ForkJoinSubscriber = /*@__PURE__*/ (function (_super) { - tslib_1.__extends(ForkJoinSubscriber, _super); - function ForkJoinSubscriber(destination, sources) { - var _this = _super.call(this, destination) || this; - _this.sources = sources; - _this.completed = 0; - _this.haveValues = 0; +function forkJoinInternal(sources, keys) { + return new Observable(function (subscriber) { var len = sources.length; - _this.values = new Array(len); - for (var i = 0; i < len; i++) { - var source = sources[i]; - var innerSubscription = subscribeToResult(_this, source, null, i); - if (innerSubscription) { - _this.add(innerSubscription); - } - } - return _this; - } - ForkJoinSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { - this.values[outerIndex] = innerValue; - if (!innerSub._hasValue) { - innerSub._hasValue = true; - this.haveValues++; - } - }; - ForkJoinSubscriber.prototype.notifyComplete = function (innerSub) { - var _a = this, destination = _a.destination, haveValues = _a.haveValues, values = _a.values; - var len = values.length; - if (!innerSub._hasValue) { - destination.complete(); + if (len === 0) { + subscriber.complete(); return; } - this.completed++; - if (this.completed !== len) { - return; - } - if (haveValues === len) { - destination.next(values); + var values = new Array(len); + var completed = 0; + var emitted = 0; + var _loop_1 = function (i) { + var source = from(sources[i]); + var hasValue = false; + subscriber.add(source.subscribe({ + next: function (value) { + if (!hasValue) { + hasValue = true; + emitted++; + } + values[i] = value; + }, + error: function (err) { return subscriber.error(err); }, + complete: function () { + completed++; + if (completed === len || !hasValue) { + if (emitted === len) { + subscriber.next(keys ? + keys.reduce(function (result, key, i) { return (result[key] = values[i], result); }, {}) : + values); + } + subscriber.complete(); + } + } + })); + }; + for (var i = 0; i < len; i++) { + _loop_1(i); } - destination.complete(); - }; - return ForkJoinSubscriber; -}(OuterSubscriber)); + }); +} //# sourceMappingURL=forkJoin.js.map diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/observable/from.js b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/observable/from.js index 4afe1c07d4bf62..453c25ee659a19 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/observable/from.js +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/observable/from.js @@ -1,14 +1,7 @@ -/** PURE_IMPORTS_START _Observable,_util_isPromise,_util_isArrayLike,_util_isInteropObservable,_util_isIterable,_fromArray,_fromPromise,_fromIterable,_fromObservable,_util_subscribeTo PURE_IMPORTS_END */ +/** PURE_IMPORTS_START _Observable,_util_subscribeTo,_scheduled_scheduled PURE_IMPORTS_END */ import { Observable } from '../Observable'; -import { isPromise } from '../util/isPromise'; -import { isArrayLike } from '../util/isArrayLike'; -import { isInteropObservable } from '../util/isInteropObservable'; -import { isIterable } from '../util/isIterable'; -import { fromArray } from './fromArray'; -import { fromPromise } from './fromPromise'; -import { fromIterable } from './fromIterable'; -import { fromObservable } from './fromObservable'; import { subscribeTo } from '../util/subscribeTo'; +import { scheduled } from '../scheduled/scheduled'; export function from(input, scheduler) { if (!scheduler) { if (input instanceof Observable) { @@ -16,20 +9,8 @@ export function from(input, scheduler) { } return new Observable(subscribeTo(input)); } - if (input != null) { - if (isInteropObservable(input)) { - return fromObservable(input, scheduler); - } - else if (isPromise(input)) { - return fromPromise(input, scheduler); - } - else if (isArrayLike(input)) { - return fromArray(input, scheduler); - } - else if (isIterable(input) || typeof input === 'string') { - return fromIterable(input, scheduler); - } + else { + return scheduled(input, scheduler); } - throw new TypeError((input !== null && typeof input || input) + ' is not observable'); } //# sourceMappingURL=from.js.map diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/observable/fromArray.js b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/observable/fromArray.js index 71f0274929cd4c..587cb7206f9d60 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/observable/fromArray.js +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/observable/fromArray.js @@ -1,27 +1,13 @@ -/** PURE_IMPORTS_START _Observable,_Subscription,_util_subscribeToArray PURE_IMPORTS_END */ +/** PURE_IMPORTS_START _Observable,_util_subscribeToArray,_scheduled_scheduleArray PURE_IMPORTS_END */ import { Observable } from '../Observable'; -import { Subscription } from '../Subscription'; import { subscribeToArray } from '../util/subscribeToArray'; +import { scheduleArray } from '../scheduled/scheduleArray'; export function fromArray(input, scheduler) { if (!scheduler) { return new Observable(subscribeToArray(input)); } else { - return new Observable(function (subscriber) { - var sub = new Subscription(); - var i = 0; - sub.add(scheduler.schedule(function () { - if (i === input.length) { - subscriber.complete(); - return; - } - subscriber.next(input[i++]); - if (!subscriber.closed) { - sub.add(this.schedule()); - } - })); - return sub; - }); + return scheduleArray(input, scheduler); } } //# sourceMappingURL=fromArray.js.map diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/observable/fromIterable.js b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/observable/fromIterable.js index ed91e0d8eea24d..c37371fd662b6c 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/observable/fromIterable.js +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/observable/fromIterable.js @@ -1,8 +1,7 @@ -/** PURE_IMPORTS_START _Observable,_Subscription,_symbol_iterator,_util_subscribeToIterable PURE_IMPORTS_END */ +/** PURE_IMPORTS_START _Observable,_util_subscribeToIterable,_scheduled_scheduleIterable PURE_IMPORTS_END */ import { Observable } from '../Observable'; -import { Subscription } from '../Subscription'; -import { iterator as Symbol_iterator } from '../symbol/iterator'; import { subscribeToIterable } from '../util/subscribeToIterable'; +import { scheduleIterable } from '../scheduled/scheduleIterable'; export function fromIterable(input, scheduler) { if (!input) { throw new Error('Iterable cannot be null'); @@ -11,42 +10,7 @@ export function fromIterable(input, scheduler) { return new Observable(subscribeToIterable(input)); } else { - return new Observable(function (subscriber) { - var sub = new Subscription(); - var iterator; - sub.add(function () { - if (iterator && typeof iterator.return === 'function') { - iterator.return(); - } - }); - sub.add(scheduler.schedule(function () { - iterator = input[Symbol_iterator](); - sub.add(scheduler.schedule(function () { - if (subscriber.closed) { - return; - } - var value; - var done; - try { - var result = iterator.next(); - value = result.value; - done = result.done; - } - catch (err) { - subscriber.error(err); - return; - } - if (done) { - subscriber.complete(); - } - else { - subscriber.next(value); - this.schedule(); - } - })); - })); - return sub; - }); + return scheduleIterable(input, scheduler); } } //# sourceMappingURL=fromIterable.js.map diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/observable/fromObservable.js b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/observable/fromObservable.js deleted file mode 100644 index 46b8167f582eaf..00000000000000 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/observable/fromObservable.js +++ /dev/null @@ -1,25 +0,0 @@ -/** PURE_IMPORTS_START _Observable,_Subscription,_symbol_observable,_util_subscribeToObservable PURE_IMPORTS_END */ -import { Observable } from '../Observable'; -import { Subscription } from '../Subscription'; -import { observable as Symbol_observable } from '../symbol/observable'; -import { subscribeToObservable } from '../util/subscribeToObservable'; -export function fromObservable(input, scheduler) { - if (!scheduler) { - return new Observable(subscribeToObservable(input)); - } - else { - return new Observable(function (subscriber) { - var sub = new Subscription(); - sub.add(scheduler.schedule(function () { - var observable = input[Symbol_observable](); - sub.add(observable.subscribe({ - next: function (value) { sub.add(scheduler.schedule(function () { return subscriber.next(value); })); }, - error: function (err) { sub.add(scheduler.schedule(function () { return subscriber.error(err); })); }, - complete: function () { sub.add(scheduler.schedule(function () { return subscriber.complete(); })); }, - })); - })); - return sub; - }); - } -} -//# sourceMappingURL=fromObservable.js.map diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/observable/fromPromise.js b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/observable/fromPromise.js index dee077c716ee25..a8262165791827 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/observable/fromPromise.js +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/observable/fromPromise.js @@ -1,26 +1,13 @@ -/** PURE_IMPORTS_START _Observable,_Subscription,_util_subscribeToPromise PURE_IMPORTS_END */ +/** PURE_IMPORTS_START _Observable,_util_subscribeToPromise,_scheduled_schedulePromise PURE_IMPORTS_END */ import { Observable } from '../Observable'; -import { Subscription } from '../Subscription'; import { subscribeToPromise } from '../util/subscribeToPromise'; +import { schedulePromise } from '../scheduled/schedulePromise'; export function fromPromise(input, scheduler) { if (!scheduler) { return new Observable(subscribeToPromise(input)); } else { - return new Observable(function (subscriber) { - var sub = new Subscription(); - sub.add(scheduler.schedule(function () { - return input.then(function (value) { - sub.add(scheduler.schedule(function () { - subscriber.next(value); - sub.add(scheduler.schedule(function () { return subscriber.complete(); })); - })); - }, function (err) { - sub.add(scheduler.schedule(function () { return subscriber.error(err); })); - }); - })); - return sub; - }); + return schedulePromise(input, scheduler); } } //# sourceMappingURL=fromPromise.js.map diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/observable/of.js b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/observable/of.js index 649236018922e3..90787442b336be 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/observable/of.js +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/observable/of.js @@ -1,8 +1,7 @@ -/** PURE_IMPORTS_START _util_isScheduler,_fromArray,_empty,_scalar PURE_IMPORTS_END */ +/** PURE_IMPORTS_START _util_isScheduler,_fromArray,_scheduled_scheduleArray PURE_IMPORTS_END */ import { isScheduler } from '../util/isScheduler'; import { fromArray } from './fromArray'; -import { empty } from './empty'; -import { scalar } from './scalar'; +import { scheduleArray } from '../scheduled/scheduleArray'; export function of() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { @@ -11,17 +10,10 @@ export function of() { var scheduler = args[args.length - 1]; if (isScheduler(scheduler)) { args.pop(); + return scheduleArray(args, scheduler); } else { - scheduler = undefined; - } - switch (args.length) { - case 0: - return empty(scheduler); - case 1: - return scheduler ? fromArray(args, scheduler) : scalar(args[0]); - default: - return fromArray(args, scheduler); + return fromArray(args); } } //# sourceMappingURL=of.js.map diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/observable/partition.js b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/observable/partition.js new file mode 100644 index 00000000000000..7b46b047dda155 --- /dev/null +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/observable/partition.js @@ -0,0 +1,12 @@ +/** PURE_IMPORTS_START _util_not,_util_subscribeTo,_operators_filter,_Observable PURE_IMPORTS_END */ +import { not } from '../util/not'; +import { subscribeTo } from '../util/subscribeTo'; +import { filter } from '../operators/filter'; +import { Observable } from '../Observable'; +export function partition(source, predicate, thisArg) { + return [ + filter(predicate, thisArg)(new Observable(subscribeTo(source))), + filter(not(predicate, thisArg))(new Observable(subscribeTo(source))) + ]; +} +//# sourceMappingURL=partition.js.map diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/observable/scalar.js b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/observable/scalar.js deleted file mode 100644 index 727c8ea1a24d35..00000000000000 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/observable/scalar.js +++ /dev/null @@ -1,12 +0,0 @@ -/** PURE_IMPORTS_START _Observable PURE_IMPORTS_END */ -import { Observable } from '../Observable'; -export function scalar(value) { - var result = new Observable(function (subscriber) { - subscriber.next(value); - subscriber.complete(); - }); - result._isScalar = true; - result.value = value; - return result; -} -//# sourceMappingURL=scalar.js.map diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/operators/endWith.js b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/operators/endWith.js index 83e37cb7459e68..081f55abbcabbd 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/operators/endWith.js +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/operators/endWith.js @@ -1,32 +1,11 @@ -/** PURE_IMPORTS_START _observable_fromArray,_observable_scalar,_observable_empty,_observable_concat,_util_isScheduler PURE_IMPORTS_END */ -import { fromArray } from '../observable/fromArray'; -import { scalar } from '../observable/scalar'; -import { empty } from '../observable/empty'; -import { concat as concatStatic } from '../observable/concat'; -import { isScheduler } from '../util/isScheduler'; +/** PURE_IMPORTS_START _observable_concat,_observable_of PURE_IMPORTS_END */ +import { concat } from '../observable/concat'; +import { of } from '../observable/of'; export function endWith() { var array = []; for (var _i = 0; _i < arguments.length; _i++) { array[_i] = arguments[_i]; } - return function (source) { - var scheduler = array[array.length - 1]; - if (isScheduler(scheduler)) { - array.pop(); - } - else { - scheduler = null; - } - var len = array.length; - if (len === 1 && !scheduler) { - return concatStatic(source, scalar(array[0])); - } - else if (len > 0) { - return concatStatic(source, fromArray(array, scheduler)); - } - else { - return concatStatic(source, empty(scheduler)); - } - }; + return function (source) { return concat(source, of.apply(void 0, array)); }; } //# sourceMappingURL=endWith.js.map diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/operators/pairwise.js b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/operators/pairwise.js index 6f0c1517d22924..50b742b09739bf 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/operators/pairwise.js +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/operators/pairwise.js @@ -20,13 +20,17 @@ var PairwiseSubscriber = /*@__PURE__*/ (function (_super) { return _this; } PairwiseSubscriber.prototype._next = function (value) { + var pair; if (this.hasPrev) { - this.destination.next([this.prev, value]); + pair = [this.prev, value]; } else { this.hasPrev = true; } this.prev = value; + if (pair) { + this.destination.next(pair); + } }; return PairwiseSubscriber; }(Subscriber)); diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/operators/startWith.js b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/operators/startWith.js index 1e28239822f0b1..fd531b82ec11b8 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/operators/startWith.js +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/operators/startWith.js @@ -1,32 +1,18 @@ -/** PURE_IMPORTS_START _observable_fromArray,_observable_scalar,_observable_empty,_observable_concat,_util_isScheduler PURE_IMPORTS_END */ -import { fromArray } from '../observable/fromArray'; -import { scalar } from '../observable/scalar'; -import { empty } from '../observable/empty'; -import { concat as concatStatic } from '../observable/concat'; +/** PURE_IMPORTS_START _observable_concat,_util_isScheduler PURE_IMPORTS_END */ +import { concat } from '../observable/concat'; import { isScheduler } from '../util/isScheduler'; export function startWith() { var array = []; for (var _i = 0; _i < arguments.length; _i++) { array[_i] = arguments[_i]; } - return function (source) { - var scheduler = array[array.length - 1]; - if (isScheduler(scheduler)) { - array.pop(); - } - else { - scheduler = null; - } - var len = array.length; - if (len === 1 && !scheduler) { - return concatStatic(scalar(array[0]), source); - } - else if (len > 0) { - return concatStatic(fromArray(array, scheduler), source); - } - else { - return concatStatic(empty(scheduler), source); - } - }; + var scheduler = array[array.length - 1]; + if (isScheduler(scheduler)) { + array.pop(); + return function (source) { return concat(array, source, scheduler); }; + } + else { + return function (source) { return concat(array, source); }; + } } //# sourceMappingURL=startWith.js.map diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/operators/throttleTime.js b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/operators/throttleTime.js index de6a588e541b90..78a228a62449df 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/operators/throttleTime.js +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/operators/throttleTime.js @@ -48,6 +48,10 @@ var ThrottleTimeSubscriber = /*@__PURE__*/ (function (_super) { if (this.leading) { this.destination.next(value); } + else if (this.trailing) { + this._trailingValue = value; + this._hasTrailingValue = true; + } } }; ThrottleTimeSubscriber.prototype._complete = function () { diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/operators/throwIfEmpty.js b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/operators/throwIfEmpty.js index 67ada7890ef88a..61e9716b129279 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/operators/throwIfEmpty.js +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/operators/throwIfEmpty.js @@ -1,20 +1,53 @@ -/** PURE_IMPORTS_START _tap,_util_EmptyError PURE_IMPORTS_END */ -import { tap } from './tap'; +/** PURE_IMPORTS_START tslib,_util_EmptyError,_Subscriber PURE_IMPORTS_END */ +import * as tslib_1 from "tslib"; import { EmptyError } from '../util/EmptyError'; -export var throwIfEmpty = function (errorFactory) { +import { Subscriber } from '../Subscriber'; +export function throwIfEmpty(errorFactory) { if (errorFactory === void 0) { errorFactory = defaultErrorFactory; } - return tap({ - hasValue: false, - next: function () { this.hasValue = true; }, - complete: function () { - if (!this.hasValue) { - throw errorFactory(); + return function (source) { + return source.lift(new ThrowIfEmptyOperator(errorFactory)); + }; +} +var ThrowIfEmptyOperator = /*@__PURE__*/ (function () { + function ThrowIfEmptyOperator(errorFactory) { + this.errorFactory = errorFactory; + } + ThrowIfEmptyOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new ThrowIfEmptySubscriber(subscriber, this.errorFactory)); + }; + return ThrowIfEmptyOperator; +}()); +var ThrowIfEmptySubscriber = /*@__PURE__*/ (function (_super) { + tslib_1.__extends(ThrowIfEmptySubscriber, _super); + function ThrowIfEmptySubscriber(destination, errorFactory) { + var _this = _super.call(this, destination) || this; + _this.errorFactory = errorFactory; + _this.hasValue = false; + return _this; + } + ThrowIfEmptySubscriber.prototype._next = function (value) { + this.hasValue = true; + this.destination.next(value); + }; + ThrowIfEmptySubscriber.prototype._complete = function () { + if (!this.hasValue) { + var err = void 0; + try { + err = this.errorFactory(); } + catch (e) { + err = e; + } + this.destination.error(err); + } + else { + return this.destination.complete(); } - }); -}; + }; + return ThrowIfEmptySubscriber; +}(Subscriber)); function defaultErrorFactory() { return new EmptyError(); } diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/scheduled/scheduleArray.js b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/scheduled/scheduleArray.js new file mode 100644 index 00000000000000..b9807565321d09 --- /dev/null +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/scheduled/scheduleArray.js @@ -0,0 +1,21 @@ +/** PURE_IMPORTS_START _Observable,_Subscription PURE_IMPORTS_END */ +import { Observable } from '../Observable'; +import { Subscription } from '../Subscription'; +export function scheduleArray(input, scheduler) { + return new Observable(function (subscriber) { + var sub = new Subscription(); + var i = 0; + sub.add(scheduler.schedule(function () { + if (i === input.length) { + subscriber.complete(); + return; + } + subscriber.next(input[i++]); + if (!subscriber.closed) { + sub.add(this.schedule()); + } + })); + return sub; + }); +} +//# sourceMappingURL=scheduleArray.js.map diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/scheduled/scheduleIterable.js b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/scheduled/scheduleIterable.js new file mode 100644 index 00000000000000..c199cc9a13e29c --- /dev/null +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/scheduled/scheduleIterable.js @@ -0,0 +1,46 @@ +/** PURE_IMPORTS_START _Observable,_Subscription,_symbol_iterator PURE_IMPORTS_END */ +import { Observable } from '../Observable'; +import { Subscription } from '../Subscription'; +import { iterator as Symbol_iterator } from '../symbol/iterator'; +export function scheduleIterable(input, scheduler) { + if (!input) { + throw new Error('Iterable cannot be null'); + } + return new Observable(function (subscriber) { + var sub = new Subscription(); + var iterator; + sub.add(function () { + if (iterator && typeof iterator.return === 'function') { + iterator.return(); + } + }); + sub.add(scheduler.schedule(function () { + iterator = input[Symbol_iterator](); + sub.add(scheduler.schedule(function () { + if (subscriber.closed) { + return; + } + var value; + var done; + try { + var result = iterator.next(); + value = result.value; + done = result.done; + } + catch (err) { + subscriber.error(err); + return; + } + if (done) { + subscriber.complete(); + } + else { + subscriber.next(value); + this.schedule(); + } + })); + })); + return sub; + }); +} +//# sourceMappingURL=scheduleIterable.js.map diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/scheduled/scheduleObservable.js b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/scheduled/scheduleObservable.js new file mode 100644 index 00000000000000..226f596afdb9e5 --- /dev/null +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/scheduled/scheduleObservable.js @@ -0,0 +1,19 @@ +/** PURE_IMPORTS_START _Observable,_Subscription,_symbol_observable PURE_IMPORTS_END */ +import { Observable } from '../Observable'; +import { Subscription } from '../Subscription'; +import { observable as Symbol_observable } from '../symbol/observable'; +export function scheduleObservable(input, scheduler) { + return new Observable(function (subscriber) { + var sub = new Subscription(); + sub.add(scheduler.schedule(function () { + var observable = input[Symbol_observable](); + sub.add(observable.subscribe({ + next: function (value) { sub.add(scheduler.schedule(function () { return subscriber.next(value); })); }, + error: function (err) { sub.add(scheduler.schedule(function () { return subscriber.error(err); })); }, + complete: function () { sub.add(scheduler.schedule(function () { return subscriber.complete(); })); }, + })); + })); + return sub; + }); +} +//# sourceMappingURL=scheduleObservable.js.map diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/scheduled/schedulePromise.js b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/scheduled/schedulePromise.js new file mode 100644 index 00000000000000..e2f79e3de11dac --- /dev/null +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/scheduled/schedulePromise.js @@ -0,0 +1,20 @@ +/** PURE_IMPORTS_START _Observable,_Subscription PURE_IMPORTS_END */ +import { Observable } from '../Observable'; +import { Subscription } from '../Subscription'; +export function schedulePromise(input, scheduler) { + return new Observable(function (subscriber) { + var sub = new Subscription(); + sub.add(scheduler.schedule(function () { + return input.then(function (value) { + sub.add(scheduler.schedule(function () { + subscriber.next(value); + sub.add(scheduler.schedule(function () { return subscriber.complete(); })); + })); + }, function (err) { + sub.add(scheduler.schedule(function () { return subscriber.error(err); })); + }); + })); + return sub; + }); +} +//# sourceMappingURL=schedulePromise.js.map diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/scheduled/scheduled.js b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/scheduled/scheduled.js new file mode 100644 index 00000000000000..52845751103f20 --- /dev/null +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/scheduled/scheduled.js @@ -0,0 +1,27 @@ +/** PURE_IMPORTS_START _scheduleObservable,_schedulePromise,_scheduleArray,_scheduleIterable,_util_isInteropObservable,_util_isPromise,_util_isArrayLike,_util_isIterable PURE_IMPORTS_END */ +import { scheduleObservable } from './scheduleObservable'; +import { schedulePromise } from './schedulePromise'; +import { scheduleArray } from './scheduleArray'; +import { scheduleIterable } from './scheduleIterable'; +import { isInteropObservable } from '../util/isInteropObservable'; +import { isPromise } from '../util/isPromise'; +import { isArrayLike } from '../util/isArrayLike'; +import { isIterable } from '../util/isIterable'; +export function scheduled(input, scheduler) { + if (input != null) { + if (isInteropObservable(input)) { + return scheduleObservable(input, scheduler); + } + else if (isPromise(input)) { + return schedulePromise(input, scheduler); + } + else if (isArrayLike(input)) { + return scheduleArray(input, scheduler); + } + else if (isIterable(input) || typeof input === 'string') { + return scheduleIterable(input, scheduler); + } + } + throw new TypeError((input !== null && typeof input || input) + ' is not observable'); +} +//# sourceMappingURL=scheduled.js.map diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/util/hostReportError.js b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/util/hostReportError.js index 95ed9e951f79d6..6b1d72295ccfb2 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/util/hostReportError.js +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/util/hostReportError.js @@ -1,5 +1,5 @@ /** PURE_IMPORTS_START PURE_IMPORTS_END */ export function hostReportError(err) { - setTimeout(function () { throw err; }); + setTimeout(function () { throw err; }, 0); } //# sourceMappingURL=hostReportError.js.map diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/util/subscribeTo.js b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/util/subscribeTo.js index 7b8647b7be0f89..f18d25e59f0046 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/util/subscribeTo.js +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/util/subscribeTo.js @@ -1,5 +1,4 @@ -/** PURE_IMPORTS_START _Observable,_subscribeToArray,_subscribeToPromise,_subscribeToIterable,_subscribeToObservable,_isArrayLike,_isPromise,_isObject,_symbol_iterator,_symbol_observable PURE_IMPORTS_END */ -import { Observable } from '../Observable'; +/** PURE_IMPORTS_START _subscribeToArray,_subscribeToPromise,_subscribeToIterable,_subscribeToObservable,_isArrayLike,_isPromise,_isObject,_symbol_iterator,_symbol_observable PURE_IMPORTS_END */ import { subscribeToArray } from './subscribeToArray'; import { subscribeToPromise } from './subscribeToPromise'; import { subscribeToIterable } from './subscribeToIterable'; @@ -10,19 +9,7 @@ import { isObject } from './isObject'; import { iterator as Symbol_iterator } from '../symbol/iterator'; import { observable as Symbol_observable } from '../symbol/observable'; export var subscribeTo = function (result) { - if (result instanceof Observable) { - return function (subscriber) { - if (result._isScalar) { - subscriber.next(result.value); - subscriber.complete(); - return undefined; - } - else { - return result.subscribe(subscriber); - } - }; - } - else if (!!result && typeof result[Symbol_observable] === 'function') { + if (!!result && typeof result[Symbol_observable] === 'function') { return subscribeToObservable(result); } else if (isArrayLike(result)) { diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/util/subscribeToArray.js b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/util/subscribeToArray.js index 827cabbb0c89d7..1c457189df1240 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/util/subscribeToArray.js +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/util/subscribeToArray.js @@ -4,9 +4,7 @@ export var subscribeToArray = function (array) { for (var i = 0, len = array.length; i < len && !subscriber.closed; i++) { subscriber.next(array[i]); } - if (!subscriber.closed) { - subscriber.complete(); - } + subscriber.complete(); }; }; //# sourceMappingURL=subscribeToArray.js.map diff --git a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/util/subscribeToResult.js b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/util/subscribeToResult.js index b375a40ae81a0f..e6e34eaedc200c 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/util/subscribeToResult.js +++ b/tools/node_modules/eslint/node_modules/rxjs/_esm5/internal/util/subscribeToResult.js @@ -1,12 +1,16 @@ -/** PURE_IMPORTS_START _InnerSubscriber,_subscribeTo PURE_IMPORTS_END */ +/** PURE_IMPORTS_START _InnerSubscriber,_subscribeTo,_Observable PURE_IMPORTS_END */ import { InnerSubscriber } from '../InnerSubscriber'; import { subscribeTo } from './subscribeTo'; +import { Observable } from '../Observable'; export function subscribeToResult(outerSubscriber, result, outerValue, outerIndex, destination) { if (destination === void 0) { destination = new InnerSubscriber(outerSubscriber, outerValue, outerIndex); } if (destination.closed) { - return; + return undefined; + } + if (result instanceof Observable) { + return result.subscribe(destination); } return subscribeTo(result)(destination); } diff --git a/tools/node_modules/eslint/node_modules/rxjs/bundles/rxjs.umd.js b/tools/node_modules/eslint/node_modules/rxjs/bundles/rxjs.umd.js index 85dd4bb12438b5..a5b39c072048cb 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/bundles/rxjs.umd.js +++ b/tools/node_modules/eslint/node_modules/rxjs/bundles/rxjs.umd.js @@ -473,7 +473,7 @@ }; function hostReportError(err) { - setTimeout(function () { throw err; }); + setTimeout(function () { throw err; }, 0); } var empty = { @@ -510,42 +510,41 @@ var Subscription = (function () { function Subscription(unsubscribe) { this.closed = false; - this._parent = null; - this._parents = null; + this._parentOrParents = null; this._subscriptions = null; if (unsubscribe) { this._unsubscribe = unsubscribe; } } Subscription.prototype.unsubscribe = function () { - var hasErrors = false; var errors; if (this.closed) { return; } - var _a = this, _parent = _a._parent, _parents = _a._parents, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions; + var _a = this, _parentOrParents = _a._parentOrParents, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions; this.closed = true; - this._parent = null; - this._parents = null; + this._parentOrParents = null; this._subscriptions = null; - var index = -1; - var len = _parents ? _parents.length : 0; - while (_parent) { - _parent.remove(this); - _parent = ++index < len && _parents[index] || null; + if (_parentOrParents instanceof Subscription) { + _parentOrParents.remove(this); + } + else if (_parentOrParents !== null) { + for (var index = 0; index < _parentOrParents.length; ++index) { + var parent_1 = _parentOrParents[index]; + parent_1.remove(this); + } } if (isFunction(_unsubscribe)) { try { _unsubscribe.call(this); } catch (e) { - hasErrors = true; errors = e instanceof UnsubscriptionError ? flattenUnsubscriptionErrors(e.errors) : [e]; } } if (isArray(_subscriptions)) { - index = -1; - len = _subscriptions.length; + var index = -1; + var len = _subscriptions.length; while (++index < len) { var sub = _subscriptions[index]; if (isObject(sub)) { @@ -553,7 +552,6 @@ sub.unsubscribe(); } catch (e) { - hasErrors = true; errors = errors || []; if (e instanceof UnsubscriptionError) { errors = errors.concat(flattenUnsubscriptionErrors(e.errors)); @@ -565,12 +563,15 @@ } } } - if (hasErrors) { + if (errors) { throw new UnsubscriptionError(errors); } }; Subscription.prototype.add = function (teardown) { var subscription = teardown; + if (!teardown) { + return Subscription.EMPTY; + } switch (typeof teardown) { case 'function': subscription = new Subscription(teardown); @@ -589,20 +590,31 @@ } break; default: { - if (!teardown) { - return Subscription.EMPTY; - } throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.'); } } - if (subscription._addParent(this)) { - var subscriptions = this._subscriptions; - if (subscriptions) { - subscriptions.push(subscription); - } - else { - this._subscriptions = [subscription]; + var _parentOrParents = subscription._parentOrParents; + if (_parentOrParents === null) { + subscription._parentOrParents = this; + } + else if (_parentOrParents instanceof Subscription) { + if (_parentOrParents === this) { + return subscription; } + subscription._parentOrParents = [_parentOrParents, this]; + } + else if (_parentOrParents.indexOf(this) === -1) { + _parentOrParents.push(this); + } + else { + return subscription; + } + var subscriptions = this._subscriptions; + if (subscriptions === null) { + this._subscriptions = [subscription]; + } + else { + subscriptions.push(subscription); } return subscription; }; @@ -615,25 +627,6 @@ } } }; - Subscription.prototype._addParent = function (parent) { - var _a = this, _parent = _a._parent, _parents = _a._parents; - if (_parent === parent) { - return false; - } - else if (!_parent) { - this._parent = parent; - return true; - } - else if (!_parents) { - this._parents = [parent]; - return true; - } - else if (_parents.indexOf(parent) === -1) { - _parents.push(parent); - return true; - } - return false; - }; Subscription.EMPTY = (function (empty) { empty.closed = true; return empty; @@ -726,14 +719,12 @@ this.unsubscribe(); }; Subscriber.prototype._unsubscribeAndRecycle = function () { - var _a = this, _parent = _a._parent, _parents = _a._parents; - this._parent = null; - this._parents = null; + var _parentOrParents = this._parentOrParents; + this._parentOrParents = null; this.unsubscribe(); this.closed = false; this.isStopped = false; - this._parent = _parent; - this._parents = _parents; + this._parentOrParents = _parentOrParents; return this; }; return Subscriber; @@ -1306,9 +1297,6 @@ this._connection = null; connection = Subscription.EMPTY; } - else { - this._connection = connection; - } } return connection; }; @@ -1827,44 +1815,36 @@ for (var i = 0, len = array.length; i < len && !subscriber.closed; i++) { subscriber.next(array[i]); } - if (!subscriber.closed) { - subscriber.complete(); - } + subscriber.complete(); }; }; + function scheduleArray(input, scheduler) { + return new Observable(function (subscriber) { + var sub = new Subscription(); + var i = 0; + sub.add(scheduler.schedule(function () { + if (i === input.length) { + subscriber.complete(); + return; + } + subscriber.next(input[i++]); + if (!subscriber.closed) { + sub.add(this.schedule()); + } + })); + return sub; + }); + } + function fromArray(input, scheduler) { if (!scheduler) { return new Observable(subscribeToArray(input)); } else { - return new Observable(function (subscriber) { - var sub = new Subscription(); - var i = 0; - sub.add(scheduler.schedule(function () { - if (i === input.length) { - subscriber.complete(); - return; - } - subscriber.next(input[i++]); - if (!subscriber.closed) { - sub.add(this.schedule()); - } - })); - return sub; - }); + return scheduleArray(input, scheduler); } } - function scalar(value) { - var result = new Observable(function (subscriber) { - subscriber.next(value); - subscriber.complete(); - }); - result._isScalar = true; - result.value = value; - return result; - } - function of() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { @@ -1873,17 +1853,10 @@ var scheduler = args[args.length - 1]; if (isScheduler(scheduler)) { args.pop(); + return scheduleArray(args, scheduler); } else { - scheduler = undefined; - } - switch (args.length) { - case 0: - return empty$1(scheduler); - case 1: - return scheduler ? fromArray(args, scheduler) : scalar(args[0]); - default: - return fromArray(args, scheduler); + return fromArray(args); } } @@ -1900,37 +1873,36 @@ subscriber.error(error); } - var NotificationKind; (function (NotificationKind) { NotificationKind["NEXT"] = "N"; NotificationKind["ERROR"] = "E"; NotificationKind["COMPLETE"] = "C"; - })(NotificationKind || (NotificationKind = {})); + })(exports.NotificationKind || (exports.NotificationKind = {})); var Notification = (function () { function Notification(kind, value, error) { this.kind = kind; this.value = value; this.error = error; - this.hasValue = kind === "N"; + this.hasValue = kind === 'N'; } Notification.prototype.observe = function (observer) { switch (this.kind) { - case "N": + case 'N': return observer.next && observer.next(this.value); - case "E": + case 'E': return observer.error && observer.error(this.error); - case "C": + case 'C': return observer.complete && observer.complete(); } }; Notification.prototype.do = function (next, error, complete) { var kind = this.kind; switch (kind) { - case "N": + case 'N': return next && next(this.value); - case "E": + case 'E': return error && error(this.error); - case "C": + case 'C': return complete && complete(); } }; @@ -1945,29 +1917,29 @@ Notification.prototype.toObservable = function () { var kind = this.kind; switch (kind) { - case "N": + case 'N': return of(this.value); - case "E": + case 'E': return throwError(this.error); - case "C": + case 'C': return empty$1(); } throw new Error('unexpected notification kind value'); }; Notification.createNext = function (value) { if (typeof value !== 'undefined') { - return new Notification("N", value); + return new Notification('N', value); } return Notification.undefinedValueNotification; }; Notification.createError = function (err) { - return new Notification("E", undefined, err); + return new Notification('E', undefined, err); }; Notification.createComplete = function () { return Notification.completeNotification; }; - Notification.completeNotification = new Notification("C"); - Notification.undefinedValueNotification = new Notification("N", undefined); + Notification.completeNotification = new Notification('C'); + Notification.undefinedValueNotification = new Notification('N', undefined); return Notification; }()); @@ -2784,19 +2756,7 @@ } var subscribeTo = function (result) { - if (result instanceof Observable) { - return function (subscriber) { - if (result._isScalar) { - subscriber.next(result.value); - subscriber.complete(); - return undefined; - } - else { - return result.subscribe(subscriber); - } - }; - } - else if (!!result && typeof result[observable] === 'function') { + if (!!result && typeof result[observable] === 'function') { return subscribeToObservable(result); } else if (isArrayLike(result)) { @@ -2819,7 +2779,10 @@ function subscribeToResult(outerSubscriber, result, outerValue, outerIndex, destination) { if (destination === void 0) { destination = new InnerSubscriber(outerSubscriber, outerValue, outerIndex); } if (destination.closed) { - return; + return undefined; + } + if (result instanceof Observable) { + return result.subscribe(destination); } return subscribeTo(result)(destination); } @@ -2916,125 +2879,116 @@ return CombineLatestSubscriber; }(OuterSubscriber)); - function isInteropObservable(input) { - return input && typeof input[observable] === 'function'; - } - - function isIterable(input) { - return input && typeof input[iterator] === 'function'; + function scheduleObservable(input, scheduler) { + return new Observable(function (subscriber) { + var sub = new Subscription(); + sub.add(scheduler.schedule(function () { + var observable$$1 = input[observable](); + sub.add(observable$$1.subscribe({ + next: function (value) { sub.add(scheduler.schedule(function () { return subscriber.next(value); })); }, + error: function (err) { sub.add(scheduler.schedule(function () { return subscriber.error(err); })); }, + complete: function () { sub.add(scheduler.schedule(function () { return subscriber.complete(); })); }, + })); + })); + return sub; + }); } - function fromPromise(input, scheduler) { - if (!scheduler) { - return new Observable(subscribeToPromise(input)); - } - else { - return new Observable(function (subscriber) { - var sub = new Subscription(); - sub.add(scheduler.schedule(function () { return input.then(function (value) { - sub.add(scheduler.schedule(function () { - subscriber.next(value); - sub.add(scheduler.schedule(function () { return subscriber.complete(); })); - })); - }, function (err) { - sub.add(scheduler.schedule(function () { return subscriber.error(err); })); - }); })); - return sub; - }); - } + function schedulePromise(input, scheduler) { + return new Observable(function (subscriber) { + var sub = new Subscription(); + sub.add(scheduler.schedule(function () { return input.then(function (value) { + sub.add(scheduler.schedule(function () { + subscriber.next(value); + sub.add(scheduler.schedule(function () { return subscriber.complete(); })); + })); + }, function (err) { + sub.add(scheduler.schedule(function () { return subscriber.error(err); })); + }); })); + return sub; + }); } - function fromIterable(input, scheduler) { + function scheduleIterable(input, scheduler) { if (!input) { throw new Error('Iterable cannot be null'); } - if (!scheduler) { - return new Observable(subscribeToIterable(input)); - } - else { - return new Observable(function (subscriber) { - var sub = new Subscription(); - var iterator$$1; - sub.add(function () { - if (iterator$$1 && typeof iterator$$1.return === 'function') { - iterator$$1.return(); - } - }); + return new Observable(function (subscriber) { + var sub = new Subscription(); + var iterator$$1; + sub.add(function () { + if (iterator$$1 && typeof iterator$$1.return === 'function') { + iterator$$1.return(); + } + }); + sub.add(scheduler.schedule(function () { + iterator$$1 = input[iterator](); sub.add(scheduler.schedule(function () { - iterator$$1 = input[iterator](); - sub.add(scheduler.schedule(function () { - if (subscriber.closed) { - return; - } - var value; - var done; - try { - var result = iterator$$1.next(); - value = result.value; - done = result.done; - } - catch (err) { - subscriber.error(err); - return; - } - if (done) { - subscriber.complete(); - } - else { - subscriber.next(value); - this.schedule(); - } - })); + if (subscriber.closed) { + return; + } + var value; + var done; + try { + var result = iterator$$1.next(); + value = result.value; + done = result.done; + } + catch (err) { + subscriber.error(err); + return; + } + if (done) { + subscriber.complete(); + } + else { + subscriber.next(value); + this.schedule(); + } })); - return sub; - }); - } + })); + return sub; + }); } - function fromObservable(input, scheduler) { - if (!scheduler) { - return new Observable(subscribeToObservable(input)); - } - else { - return new Observable(function (subscriber) { - var sub = new Subscription(); - sub.add(scheduler.schedule(function () { - var observable$$1 = input[observable](); - sub.add(observable$$1.subscribe({ - next: function (value) { sub.add(scheduler.schedule(function () { return subscriber.next(value); })); }, - error: function (err) { sub.add(scheduler.schedule(function () { return subscriber.error(err); })); }, - complete: function () { sub.add(scheduler.schedule(function () { return subscriber.complete(); })); }, - })); - })); - return sub; - }); - } + function isInteropObservable(input) { + return input && typeof input[observable] === 'function'; } - function from(input, scheduler) { - if (!scheduler) { - if (input instanceof Observable) { - return input; - } - return new Observable(subscribeTo(input)); - } + function isIterable(input) { + return input && typeof input[iterator] === 'function'; + } + + function scheduled(input, scheduler) { if (input != null) { if (isInteropObservable(input)) { - return fromObservable(input, scheduler); + return scheduleObservable(input, scheduler); } else if (isPromise(input)) { - return fromPromise(input, scheduler); + return schedulePromise(input, scheduler); } else if (isArrayLike(input)) { - return fromArray(input, scheduler); + return scheduleArray(input, scheduler); } else if (isIterable(input) || typeof input === 'string') { - return fromIterable(input, scheduler); + return scheduleIterable(input, scheduler); } } throw new TypeError((input !== null && typeof input || input) + ' is not observable'); } + function from(input, scheduler) { + if (!scheduler) { + if (input instanceof Observable) { + return input; + } + return new Observable(subscribeTo(input)); + } + else { + return scheduled(input, scheduler); + } + } + function mergeMap(project, resultSelector, concurrent) { if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; } if (typeof resultSelector === 'function') { @@ -3157,66 +3111,63 @@ for (var _i = 0; _i < arguments.length; _i++) { sources[_i] = arguments[_i]; } - var resultSelector; - if (typeof sources[sources.length - 1] === 'function') { - resultSelector = sources.pop(); - } - if (sources.length === 1 && isArray(sources[0])) { - sources = sources[0]; - } - if (sources.length === 0) { - return EMPTY; + if (sources.length === 1) { + var first_1 = sources[0]; + if (isArray(first_1)) { + return forkJoinInternal(first_1, null); + } + if (isObject(first_1) && Object.getPrototypeOf(first_1) === Object.prototype) { + var keys = Object.keys(first_1); + return forkJoinInternal(keys.map(function (key) { return first_1[key]; }), keys); + } } - if (resultSelector) { - return forkJoin(sources).pipe(map(function (args) { return resultSelector.apply(void 0, args); })); + if (typeof sources[sources.length - 1] === 'function') { + var resultSelector_1 = sources.pop(); + sources = (sources.length === 1 && isArray(sources[0])) ? sources[0] : sources; + return forkJoinInternal(sources, null).pipe(map(function (args) { return resultSelector_1.apply(void 0, args); })); } - return new Observable(function (subscriber) { - return new ForkJoinSubscriber(subscriber, sources); - }); + return forkJoinInternal(sources, null); } - var ForkJoinSubscriber = (function (_super) { - __extends(ForkJoinSubscriber, _super); - function ForkJoinSubscriber(destination, sources) { - var _this = _super.call(this, destination) || this; - _this.sources = sources; - _this.completed = 0; - _this.haveValues = 0; + function forkJoinInternal(sources, keys) { + return new Observable(function (subscriber) { var len = sources.length; - _this.values = new Array(len); - for (var i = 0; i < len; i++) { - var source = sources[i]; - var innerSubscription = subscribeToResult(_this, source, null, i); - if (innerSubscription) { - _this.add(innerSubscription); - } - } - return _this; - } - ForkJoinSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { - this.values[outerIndex] = innerValue; - if (!innerSub._hasValue) { - innerSub._hasValue = true; - this.haveValues++; - } - }; - ForkJoinSubscriber.prototype.notifyComplete = function (innerSub) { - var _a = this, destination = _a.destination, haveValues = _a.haveValues, values = _a.values; - var len = values.length; - if (!innerSub._hasValue) { - destination.complete(); - return; - } - this.completed++; - if (this.completed !== len) { + if (len === 0) { + subscriber.complete(); return; } - if (haveValues === len) { - destination.next(values); + var values = new Array(len); + var completed = 0; + var emitted = 0; + var _loop_1 = function (i) { + var source = from(sources[i]); + var hasValue = false; + subscriber.add(source.subscribe({ + next: function (value) { + if (!hasValue) { + hasValue = true; + emitted++; + } + values[i] = value; + }, + error: function (err) { return subscriber.error(err); }, + complete: function () { + completed++; + if (completed === len || !hasValue) { + if (emitted === len) { + subscriber.next(keys ? + keys.reduce(function (result, key, i) { return (result[key] = values[i], result); }, {}) : + values); + } + subscriber.complete(); + } + } + })); + }; + for (var i = 0; i < len; i++) { + _loop_1(i); } - destination.complete(); - }; - return ForkJoinSubscriber; - }(OuterSubscriber)); + }); + } function fromEvent(target, eventName, options, resultSelector) { if (isFunction(options)) { @@ -3539,6 +3490,62 @@ } } + function not(pred, thisArg) { + function notPred() { + return !(notPred.pred.apply(notPred.thisArg, arguments)); + } + notPred.pred = pred; + notPred.thisArg = thisArg; + return notPred; + } + + function filter(predicate, thisArg) { + return function filterOperatorFunction(source) { + return source.lift(new FilterOperator(predicate, thisArg)); + }; + } + var FilterOperator = (function () { + function FilterOperator(predicate, thisArg) { + this.predicate = predicate; + this.thisArg = thisArg; + } + FilterOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new FilterSubscriber(subscriber, this.predicate, this.thisArg)); + }; + return FilterOperator; + }()); + var FilterSubscriber = (function (_super) { + __extends(FilterSubscriber, _super); + function FilterSubscriber(destination, predicate, thisArg) { + var _this = _super.call(this, destination) || this; + _this.predicate = predicate; + _this.thisArg = thisArg; + _this.count = 0; + return _this; + } + FilterSubscriber.prototype._next = function (value) { + var result; + try { + result = this.predicate.call(this.thisArg, value, this.count++); + } + catch (err) { + this.destination.error(err); + return; + } + if (result) { + this.destination.next(value); + } + }; + return FilterSubscriber; + }(Subscriber)); + + function partition(source, predicate, thisArg) { + return [ + filter(predicate, thisArg)(new Observable(subscribeTo(source))), + filter(not(predicate, thisArg))(new Observable(subscribeTo(source))) + ]; + } + function race() { var observables = []; for (var _i = 0; _i < arguments.length; _i++) { @@ -5085,128 +5092,50 @@ return distinctUntilChanged(function (x, y) { return compare ? compare(x[key], y[key]) : x[key] === y[key]; }); } - function filter(predicate, thisArg) { - return function filterOperatorFunction(source) { - return source.lift(new FilterOperator(predicate, thisArg)); + function throwIfEmpty(errorFactory) { + if (errorFactory === void 0) { errorFactory = defaultErrorFactory; } + return function (source) { + return source.lift(new ThrowIfEmptyOperator(errorFactory)); }; } - var FilterOperator = (function () { - function FilterOperator(predicate, thisArg) { - this.predicate = predicate; - this.thisArg = thisArg; + var ThrowIfEmptyOperator = (function () { + function ThrowIfEmptyOperator(errorFactory) { + this.errorFactory = errorFactory; } - FilterOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new FilterSubscriber(subscriber, this.predicate, this.thisArg)); + ThrowIfEmptyOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new ThrowIfEmptySubscriber(subscriber, this.errorFactory)); }; - return FilterOperator; + return ThrowIfEmptyOperator; }()); - var FilterSubscriber = (function (_super) { - __extends(FilterSubscriber, _super); - function FilterSubscriber(destination, predicate, thisArg) { + var ThrowIfEmptySubscriber = (function (_super) { + __extends(ThrowIfEmptySubscriber, _super); + function ThrowIfEmptySubscriber(destination, errorFactory) { var _this = _super.call(this, destination) || this; - _this.predicate = predicate; - _this.thisArg = thisArg; - _this.count = 0; - return _this; - } - FilterSubscriber.prototype._next = function (value) { - var result; - try { - result = this.predicate.call(this.thisArg, value, this.count++); - } - catch (err) { - this.destination.error(err); - return; - } - if (result) { - this.destination.next(value); - } - }; - return FilterSubscriber; - }(Subscriber)); - - function tap(nextOrObserver, error, complete) { - return function tapOperatorFunction(source) { - return source.lift(new DoOperator(nextOrObserver, error, complete)); - }; - } - var DoOperator = (function () { - function DoOperator(nextOrObserver, error, complete) { - this.nextOrObserver = nextOrObserver; - this.error = error; - this.complete = complete; - } - DoOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new TapSubscriber(subscriber, this.nextOrObserver, this.error, this.complete)); - }; - return DoOperator; - }()); - var TapSubscriber = (function (_super) { - __extends(TapSubscriber, _super); - function TapSubscriber(destination, observerOrNext, error, complete) { - var _this = _super.call(this, destination) || this; - _this._tapNext = noop; - _this._tapError = noop; - _this._tapComplete = noop; - _this._tapError = error || noop; - _this._tapComplete = complete || noop; - if (isFunction(observerOrNext)) { - _this._context = _this; - _this._tapNext = observerOrNext; - } - else if (observerOrNext) { - _this._context = observerOrNext; - _this._tapNext = observerOrNext.next || noop; - _this._tapError = observerOrNext.error || noop; - _this._tapComplete = observerOrNext.complete || noop; - } + _this.errorFactory = errorFactory; + _this.hasValue = false; return _this; } - TapSubscriber.prototype._next = function (value) { - try { - this._tapNext.call(this._context, value); - } - catch (err) { - this.destination.error(err); - return; - } + ThrowIfEmptySubscriber.prototype._next = function (value) { + this.hasValue = true; this.destination.next(value); }; - TapSubscriber.prototype._error = function (err) { - try { - this._tapError.call(this._context, err); - } - catch (err) { + ThrowIfEmptySubscriber.prototype._complete = function () { + if (!this.hasValue) { + var err = void 0; + try { + err = this.errorFactory(); + } + catch (e) { + err = e; + } this.destination.error(err); - return; - } - this.destination.error(err); - }; - TapSubscriber.prototype._complete = function () { - try { - this._tapComplete.call(this._context); } - catch (err) { - this.destination.error(err); - return; + else { + return this.destination.complete(); } - return this.destination.complete(); }; - return TapSubscriber; + return ThrowIfEmptySubscriber; }(Subscriber)); - - var throwIfEmpty = function (errorFactory) { - if (errorFactory === void 0) { errorFactory = defaultErrorFactory; } - return tap({ - hasValue: false, - next: function () { this.hasValue = true; }, - complete: function () { - if (!this.hasValue) { - throw errorFactory(); - } - } - }); - }; function defaultErrorFactory() { return new EmptyError(); } @@ -5270,25 +5199,7 @@ for (var _i = 0; _i < arguments.length; _i++) { array[_i] = arguments[_i]; } - return function (source) { - var scheduler = array[array.length - 1]; - if (isScheduler(scheduler)) { - array.pop(); - } - else { - scheduler = null; - } - var len = array.length; - if (len === 1 && !scheduler) { - return concat(source, scalar(array[0])); - } - else if (len > 0) { - return concat(source, fromArray(array, scheduler)); - } - else { - return concat(source, empty$1(scheduler)); - } - }; + return function (source) { return concat(source, of.apply(void 0, array)); }; } function every(predicate, thisArg) { @@ -6119,27 +6030,22 @@ return _this; } PairwiseSubscriber.prototype._next = function (value) { + var pair; if (this.hasPrev) { - this.destination.next([this.prev, value]); + pair = [this.prev, value]; } else { this.hasPrev = true; } this.prev = value; + if (pair) { + this.destination.next(pair); + } }; return PairwiseSubscriber; }(Subscriber)); - function not(pred, thisArg) { - function notPred() { - return !(notPred.pred.apply(notPred.thisArg, arguments)); - } - notPred.pred = pred; - notPred.thisArg = thisArg; - return notPred; - } - - function partition(predicate, thisArg) { + function partition$1(predicate, thisArg) { return function (source) { return [ filter(predicate, thisArg)(source), filter(not(predicate, thisArg))(source) @@ -6913,25 +6819,14 @@ for (var _i = 0; _i < arguments.length; _i++) { array[_i] = arguments[_i]; } - return function (source) { - var scheduler = array[array.length - 1]; - if (isScheduler(scheduler)) { - array.pop(); - } - else { - scheduler = null; - } - var len = array.length; - if (len === 1 && !scheduler) { - return concat(scalar(array[0]), source); - } - else if (len > 0) { - return concat(fromArray(array, scheduler), source); - } - else { - return concat(empty$1(scheduler), source); - } - }; + var scheduler = array[array.length - 1]; + if (isScheduler(scheduler)) { + array.pop(); + return function (source) { return concat(array, source, scheduler); }; + } + else { + return function (source) { return concat(array, source); }; + } } var SubscribeOnObservable = (function (_super) { @@ -7151,6 +7046,76 @@ return TakeWhileSubscriber; }(Subscriber)); + function tap(nextOrObserver, error, complete) { + return function tapOperatorFunction(source) { + return source.lift(new DoOperator(nextOrObserver, error, complete)); + }; + } + var DoOperator = (function () { + function DoOperator(nextOrObserver, error, complete) { + this.nextOrObserver = nextOrObserver; + this.error = error; + this.complete = complete; + } + DoOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new TapSubscriber(subscriber, this.nextOrObserver, this.error, this.complete)); + }; + return DoOperator; + }()); + var TapSubscriber = (function (_super) { + __extends(TapSubscriber, _super); + function TapSubscriber(destination, observerOrNext, error, complete) { + var _this = _super.call(this, destination) || this; + _this._tapNext = noop; + _this._tapError = noop; + _this._tapComplete = noop; + _this._tapError = error || noop; + _this._tapComplete = complete || noop; + if (isFunction(observerOrNext)) { + _this._context = _this; + _this._tapNext = observerOrNext; + } + else if (observerOrNext) { + _this._context = observerOrNext; + _this._tapNext = observerOrNext.next || noop; + _this._tapError = observerOrNext.error || noop; + _this._tapComplete = observerOrNext.complete || noop; + } + return _this; + } + TapSubscriber.prototype._next = function (value) { + try { + this._tapNext.call(this._context, value); + } + catch (err) { + this.destination.error(err); + return; + } + this.destination.next(value); + }; + TapSubscriber.prototype._error = function (err) { + try { + this._tapError.call(this._context, err); + } + catch (err) { + this.destination.error(err); + return; + } + this.destination.error(err); + }; + TapSubscriber.prototype._complete = function () { + try { + this._tapComplete.call(this._context); + } + catch (err) { + this.destination.error(err); + return; + } + return this.destination.complete(); + }; + return TapSubscriber; + }(Subscriber)); + var defaultThrottleConfig = { leading: true, trailing: false @@ -7277,6 +7242,10 @@ if (this.leading) { this.destination.next(value); } + else if (this.trailing) { + this._trailingValue = value; + this._hasTrailingValue = true; + } } }; ThrottleTimeSubscriber.prototype._complete = function () { @@ -8048,7 +8017,7 @@ observeOn: observeOn, onErrorResumeNext: onErrorResumeNext$1, pairwise: pairwise, - partition: partition, + partition: partition$1, pluck: pluck, publish: publish, publishBehavior: publishBehavior, @@ -9150,15 +9119,63 @@ WebSocketSubject: WebSocketSubject }); + function fromFetch(input, init) { + return new Observable(function (subscriber) { + var controller = new AbortController(); + var signal = controller.signal; + var outerSignalHandler; + var abortable = true; + var unsubscribed = false; + if (init) { + if (init.signal) { + outerSignalHandler = function () { + if (!signal.aborted) { + controller.abort(); + } + }; + init.signal.addEventListener('abort', outerSignalHandler); + } + init.signal = signal; + } + else { + init = { signal: signal }; + } + fetch(input, init).then(function (response) { + abortable = false; + subscriber.next(response); + subscriber.complete(); + }).catch(function (err) { + abortable = false; + if (!unsubscribed) { + subscriber.error(err); + } + }); + return function () { + unsubscribed = true; + if (abortable) { + controller.abort(); + } + }; + }); + } + + + + var _fetch = /*#__PURE__*/Object.freeze({ + fromFetch: fromFetch + }); + var operators = _operators; var testing = _testing; var ajax$1 = _ajax; var webSocket$1 = _webSocket; + var fetch$1 = _fetch; exports.operators = operators; exports.testing = testing; exports.ajax = ajax$1; exports.webSocket = webSocket$1; + exports.fetch = fetch$1; exports.Observable = Observable; exports.ConnectableObservable = ConnectableObservable; exports.GroupedObservable = GroupedObservable; @@ -9204,12 +9221,14 @@ exports.of = of; exports.onErrorResumeNext = onErrorResumeNext; exports.pairs = pairs; + exports.partition = partition; exports.race = race; exports.range = range; exports.throwError = throwError; exports.timer = timer; exports.using = using; exports.zip = zip; + exports.scheduled = scheduled; exports.EMPTY = EMPTY; exports.NEVER = NEVER; exports.config = config; diff --git a/tools/node_modules/eslint/node_modules/rxjs/bundles/rxjs.umd.min.js b/tools/node_modules/eslint/node_modules/rxjs/bundles/rxjs.umd.min.js index 256c818786fd3e..773089446d8fbf 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/bundles/rxjs.umd.min.js +++ b/tools/node_modules/eslint/node_modules/rxjs/bundles/rxjs.umd.min.js @@ -21,247 +21,248 @@ See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. *****************************************************************************/ -(function(k,h){"object"===typeof exports&&"undefined"!==typeof module?h(exports):"function"===typeof define&&define.amd?define("rxjs",["exports"],h):h(k.rxjs={})})(this,function(k){function h(c,a){function b(){this.constructor=c}Ob(c,a);c.prototype=null===a?Object.create(a):(b.prototype=a.prototype,new b)}function T(c){return"function"===typeof c}function U(c){setTimeout(function(){throw c;})}function Ja(c){Error.call(this);this.message=c?c.length+" errors occurred during unsubscription:\n"+c.map(function(a, -b){return b+1+") "+a.toString()}).join("\n "):"";this.name="UnsubscriptionError";this.errors=c;return this}function Ka(c){return c.reduce(function(a,b){return a.concat(b instanceof aa?b.errors:b)},[])}function pa(c){for(;c;){var a=c.destination,b=c.isStopped;if(c.closed||b)return!1;c=a&&a instanceof m?a:null}return!0}function E(){}function qa(){for(var c=[],a=0;a=b.length?b[0]:b);g.complete()}]))}catch(x){pa(g)?g.error(x):console.warn(x)}}return g.subscribe(d)})}}function Tb(c){var a=this,b=c.args,d=c.subscriber;c=c.params;var e=c.callbackFunc,f=c.context,g=c.scheduler,l=c.subject;if(!l){l=c.subject=new V;try{e.apply(f,b.concat([function(){for(var b=[],c=0;c=b.length?b[0]:b,subject:l}))}]))}catch(v){l.error(v)}}this.add(l.subscribe(d))}function Ub(c){var a=c.subject;a.next(c.value);a.complete()}function Qa(c,a,b){if(a)if(z(a))b=a;else return function(){for(var d=[],e=0;e=b.length?b[0]:b),g.complete())}]))}catch(x){pa(g)?g.error(x):console.warn(x)}}return g.subscribe(d)})}}function Vb(c){var a=this,b=c.params,d=c.subscriber;c=c.context;var e=b.callbackFunc,f=b.args,g=b.scheduler,l=b.subject;if(!l){l= -b.subject=new V;try{e.apply(c,f.concat([function(){for(var b=[],c=0;c=b.length?b[0]:b,subject:l}))}]))}catch(v){this.add(g.schedule(Ra,0,{err:v,subject:l}))}}this.add(l.subscribe(d))}function Wb(c){var a=c.subject;a.next(c.value);a.complete()}function Ra(c){c.subject.error(c.err)}function Sa(c){return!!c&&"function"!==typeof c.subscribe&&"function"===typeof c.then}function p(c, -a,b,d,e){void 0===e&&(e=new J(c,b,d));if(!e.closed)return Ta(a)(e)}function Xb(c,a){return a?new n(function(b){var d=new t;d.add(a.schedule(function(){return c.then(function(c){d.add(a.schedule(function(){b.next(c);d.add(a.schedule(function(){return b.complete()}))}))},function(c){d.add(a.schedule(function(){return b.error(c)}))})}));return d}):new n(Ua(c))}function Yb(c,a){if(!c)throw Error("Iterable cannot be null");return a?new n(function(b){var d=new t,e;d.add(function(){e&&"function"===typeof e.return&& -e.return()});d.add(a.schedule(function(){e=c[I]();d.add(a.schedule(function(){if(!b.closed){var a,c;try{var d=e.next();a=d.value;c=d.done}catch(v){b.error(v);return}c?b.complete():(b.next(a),this.schedule())}}))}));return d}):new n(Va(c))}function Zb(c,a){return a?new n(function(b){var d=new t;d.add(a.schedule(function(){var e=c[W]();d.add(e.subscribe({next:function(c){d.add(a.schedule(function(){return b.next(c)}))},error:function(c){d.add(a.schedule(function(){return b.error(c)}))},complete:function(){d.add(a.schedule(function(){return b.complete()}))}}))})); -return d}):new n(Wa(c))}function K(c,a){if(!a)return c instanceof n?c:new n(Ta(c));if(null!=c){if(c&&"function"===typeof c[W])return Zb(c,a);if(Sa(c))return Xb(c,a);if(Xa(c))return H(c,a);if(c&&"function"===typeof c[I]||"string"===typeof c)return Yb(c,a)}throw new TypeError((null!==c&&typeof c||c)+" is not observable");}function P(c,a,b){void 0===b&&(b=Number.POSITIVE_INFINITY);if("function"===typeof a)return function(d){return d.pipe(P(function(b,d){return K(c(b,d)).pipe(C(function(c,e){return a(b, -c,d,e)}))},b))};"number"===typeof a&&(b=a);return function(a){return a.lift(new $b(c,b))}}function wa(c){void 0===c&&(c=Number.POSITIVE_INFINITY);return P(N,c)}function Ya(){return wa(1)}function L(){for(var c=[],a=0;a=c.count?d.complete():(d.next(a),d.closed||(c.index=b+1,c.start=a+1,this.schedule(c)))}function eb(c,a,b){void 0===c&&(c=0);var d=-1;X(a)?d=1>Number(a)&&1||Number(a):z(a)&&(b= -a);z(b)||(b=y);return new n(function(a){var e=X(c)?c:+c-b.now();return b.schedule(gc,e,{index:0,period:d,subscriber:a})})}function gc(c){var a=c.index,b=c.period,d=c.subscriber;d.next(a);if(!d.closed){if(-1===b)return d.complete();c.index=a+1;this.schedule(c,b)}}function fb(){for(var c=[],a=0;a=a?this.connection=null:(b._refCount=a-1,1=a?this.connection=null:(b._refCount=a-1,1b?1:b;d._windowTime=1>a?1:a;a===Number.POSITIVE_INFINITY?(d._infiniteTimeWindow=!0,d.next=d.nextInfiniteTimeWindow):d.next=d.nextTimeWindow;return d}h(a,c);a.prototype.nextInfiniteTimeWindow=function(b){var a=this._events;a.push(b);a.length>this._bufferSize&&a.shift();c.prototype.next.call(this, -b)};a.prototype.nextTimeWindow=function(b){this._events.push(new Zc(this._getNow(),b));this._trimBufferThenGetEvents();c.prototype.next.call(this,b)};a.prototype._subscribe=function(b){var a=this._infiniteTimeWindow,c=a?this._events:this._trimBufferThenGetEvents(),f=this.scheduler,g=c.length,l;if(this.closed)throw new F;this.isStopped||this.hasError?l=t.EMPTY:(this.observers.push(b),l=new ub(this,b));f&&b.add(b=new Ab(b,f));if(a)for(a=0;aa&&(l=Math.max(l,g-a));0=b.length?b[0]:b);g.complete()}]))}catch(L){ta(g)?g.error(L):console.warn(L)}}return g.subscribe(d)})}}function Rb(c){var a=this,b=c.args,d=c.subscriber;c=c.params;var e=c.callbackFunc,f=c.context,g=c.scheduler,l=c.subject;if(!l){l=c.subject=new U;try{e.apply(f,b.concat([function(){for(var b=[],c=0;c=b.length?b[0]:b,subject:l}))}]))}catch(u){l.error(u)}}this.add(l.subscribe(d))} +function Sb(c){var a=c.subject;a.next(c.value);a.complete()}function Ta(c,a,b){if(a)if(A(a))b=a;else return function(){for(var d=[],e=0;e=b.length?b[0]:b),g.complete())}]))}catch(L){ta(g)?g.error(L):console.warn(L)}}return g.subscribe(d)})}}function Tb(c){var a=this,b=c.params,d=c.subscriber;c=c.context;var e=b.callbackFunc,f=b.args,g=b.scheduler,l=b.subject;if(!l){l=b.subject=new U;try{e.apply(c,f.concat([function(){for(var b=[],c=0;c=b.length?b[0]:b,subject:l}))}]))}catch(u){this.add(g.schedule(Ua,0,{err:u,subject:l}))}}this.add(l.subscribe(d))}function Ub(c){var a=c.subject;a.next(c.value);a.complete()}function Ua(c){c.subject.error(c.err)}function Va(c){return!!c&&"function"!==typeof c.subscribe&&"function"===typeof c.then}function p(c,a,b,d,e){void 0===e&&(e=new H(c,b,d));if(!e.closed)return a instanceof n?a.subscribe(e):ia(a)(e)} +function Vb(c,a){return new n(function(b){var d=new t;d.add(a.schedule(function(){var e=c[V]();d.add(e.subscribe({next:function(c){d.add(a.schedule(function(){return b.next(c)}))},error:function(c){d.add(a.schedule(function(){return b.error(c)}))},complete:function(){d.add(a.schedule(function(){return b.complete()}))}}))}));return d})}function Wb(c,a){return new n(function(b){var d=new t;d.add(a.schedule(function(){return c.then(function(c){d.add(a.schedule(function(){b.next(c);d.add(a.schedule(function(){return b.complete()}))}))}, +function(c){d.add(a.schedule(function(){return b.error(c)}))})}));return d})}function Xb(c,a){if(!c)throw Error("Iterable cannot be null");return new n(function(b){var d=new t,e;d.add(function(){e&&"function"===typeof e.return&&e.return()});d.add(a.schedule(function(){e=c[F]();d.add(a.schedule(function(){if(!b.closed){var a,c;try{var d=e.next();a=d.value;c=d.done}catch(u){b.error(u);return}c?b.complete():(b.next(a),this.schedule())}}))}));return d})}function Wa(c,a){if(null!=c){if(c&&"function"=== +typeof c[V])return Vb(c,a);if(Va(c))return Wb(c,a);if(Xa(c))return wa(c,a);if(c&&"function"===typeof c[F]||"string"===typeof c)return Xb(c,a)}throw new TypeError((null!==c&&typeof c||c)+" is not observable");}function G(c,a){return a?Wa(c,a):c instanceof n?c:new n(ia(c))}function M(c,a,b){void 0===b&&(b=Number.POSITIVE_INFINITY);if("function"===typeof a)return function(d){return d.pipe(M(function(b,d){return G(c(b,d)).pipe(B(function(c,e){return a(b,c,d,e)}))},b))};"number"===typeof a&&(b=a);return function(a){return a.lift(new Yb(c, +b))}}function za(c){void 0===c&&(c=Number.POSITIVE_INFINITY);return M(J,c)}function Ya(){return za(1)}function aa(){for(var c=[],a=0;a=c.count?d.complete():(d.next(a),d.closed||(c.index=b+1,c.start=a+1,this.schedule(c)))}function eb(c,a,b){void 0===c&&(c=0);var d=-1;W(a)?d=1>Number(a)&&1||Number(a):A(a)&&(b=a);A(b)||(b=y);return new n(function(a){var e=W(c)?c:+c-b.now();return b.schedule(hc,e,{index:0,period:d,subscriber:a})})}function hc(c){var a=c.index,b=c.period,d=c.subscriber;d.next(a);if(!d.closed){if(-1===b)return d.complete();c.index=a+1;this.schedule(c,b)}}function fb(){for(var c= +[],a=0;a=a?this.connection=null:(b._refCount=a-1,1=a?this.connection=null:(b._refCount=a-1,1b?1:b;d._windowTime=1>a?1:a;a===Number.POSITIVE_INFINITY?(d._infiniteTimeWindow=!0,d.next=d.nextInfiniteTimeWindow):d.next=d.nextTimeWindow;return d}h(a,c);a.prototype.nextInfiniteTimeWindow=function(b){var a=this._events;a.push(b);a.length>this._bufferSize&&a.shift();c.prototype.next.call(this, +b)};a.prototype.nextTimeWindow=function(b){this._events.push(new Wc(this._getNow(),b));this._trimBufferThenGetEvents();c.prototype.next.call(this,b)};a.prototype._subscribe=function(b){var a=this._infiniteTimeWindow,c=a?this._events:this._trimBufferThenGetEvents(),f=this.scheduler,g=c.length,l;if(this.closed)throw new E;this.isStopped||this.hasError?l=t.EMPTY:(this.observers.push(b),l=new tb(this,b));f&&b.add(b=new yb(b,f));if(a)for(a=0;aa&&(l=Math.max(l,g-a));0a.index?1:-1:b.delay>a.delay?1:-1};return a}(fa);O.prototype=Object.create(Error.prototype);Oa.prototype=Object.create(Error.prototype);var ca=Oa;va.prototype=Object.create(Error.prototype);var Sb=function(){function c(a,b){this.project=a;this.thisArg=b}c.prototype.call=function(a, -b){return b.subscribe(new dd(a,this.project,this.thisArg))};return c}(),dd=function(c){function a(b,a,e){b=c.call(this,b)||this;b.project=a;b.count=0;b.thisArg=e||b;return b}h(a,c);a.prototype._next=function(b){var a;try{a=this.project.call(this.thisArg,b,this.count++)}catch(e){this.destination.error(e);return}this.destination.next(a)};return a}(m),q=function(c){function a(){return null!==c&&c.apply(this,arguments)||this}h(a,c);a.prototype.notifyNext=function(b,a,c,f,g){this.destination.next(a)}; -a.prototype.notifyError=function(b,a){this.destination.error(b)};a.prototype.notifyComplete=function(b){this.destination.complete()};return a}(m),J=function(c){function a(b,a,e){var d=c.call(this)||this;d.parent=b;d.outerValue=a;d.outerIndex=e;d.index=0;return d}h(a,c);a.prototype._next=function(b){this.parent.notifyNext(this.outerValue,b,this.outerIndex,this.index++,this)};a.prototype._error=function(b){this.parent.notifyError(b,this);this.unsubscribe()};a.prototype._complete=function(){this.parent.notifyComplete(this); -this.unsubscribe()};return a}(m),Ua=function(c){return function(a){c.then(function(b){a.closed||(a.next(b),a.complete())},function(b){return a.error(b)}).then(null,U);return a}},I;I="function"===typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator";var Va=function(c){return function(a){var b=c[I]();do{var d=b.next();if(d.done){a.complete();break}a.next(d.value);if(a.closed)break}while(1);"function"===typeof b.return&&a.add(function(){b.return&&b.return()});return a}},Wa=function(c){return function(a){var b= -c[W]();if("function"!==typeof b.subscribe)throw new TypeError("Provided object does not correctly implement Symbol.observable");return b.subscribe(a)}},Xa=function(c){return c&&"number"===typeof c.length&&"function"!==typeof c},Ta=function(c){if(c instanceof n)return function(a){if(c._isScalar)a.next(c.value),a.complete();else return c.subscribe(a)};if(c&&"function"===typeof c[W])return Wa(c);if(Xa(c))return Na(c);if(Sa(c))return Ua(c);if(c&&"function"===typeof c[I])return Va(c);throw new TypeError("You provided "+ -(null!==c&&"object"===typeof c?"an invalid object":"'"+c+"'")+" where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.");},Db={},Ga=function(){function c(a){this.resultSelector=a}c.prototype.call=function(a,b){return b.subscribe(new ed(a,this.resultSelector))};return c}(),ed=function(c){function a(b,a){b=c.call(this,b)||this;b.resultSelector=a;b.active=0;b.values=[];b.observables=[];return b}h(a,c);a.prototype._next=function(b){this.values.push(Db);this.observables.push(b)}; -a.prototype._complete=function(){var b=this.observables,a=b.length;if(0===a)this.destination.complete();else{this.toRespond=this.active=a;for(var c=0;cthis.index};c.prototype.hasCompleted=function(){return this.array.length===this.index};return c}(),kd=function(c){function a(b,a,e){b=c.call(this,b)||this;b.parent=a;b.observable=e;b.stillUnsubscribed=!0;b.buffer=[];b.isComplete=!1;return b}h(a,c);a.prototype[I]=function(){return this};a.prototype.next=function(){var b=this.buffer;return 0===b.length&&this.isComplete?{value:null,done:!0}:{value:b.shift(),done:!1}};a.prototype.hasValue=function(){return 0< -this.buffer.length};a.prototype.hasCompleted=function(){return 0===this.buffer.length&&this.isComplete};a.prototype.notifyComplete=function(){0e;if(b.timespanOnly)b.add(f.closeAction=g.schedule(ib,a,{subscriber:b,context:f,bufferTimeSpan:a}));else{var d={bufferTimeSpan:a,bufferCreationInterval:e,subscriber:b,scheduler:g};b.add(f.closeAction=g.schedule(jb,a,{subscriber:b, -context:f}));b.add(g.schedule(ic,e,d))}return b}h(a,c);a.prototype._next=function(b){for(var a=this.contexts,c=a.length,f,g=0;g=c[0].time-f.now();)c.shift().notification.observe(g);0this.total)throw new O;}c.prototype.call=function(a,b){return b.subscribe(new Ud(a,this.total))};return c}(),Ud=function(c){function a(b,a){b=c.call(this,b)||this;b.total=a;b.count=0;return b}h(a,c);a.prototype._next=function(b){var a=this.total,c=++this.count; -c<=a&&(this.destination.next(b),c===a&&(this.destination.complete(),this.unsubscribe()))};return a}(m),Wd=function(){function c(a,b,c){this.predicate=a;this.thisArg=b;this.source=c}c.prototype.call=function(a,b){return b.subscribe(new Vd(a,this.predicate,this.thisArg,this.source))};return c}(),Vd=function(c){function a(b,a,e,f){b=c.call(this,b)||this;b.predicate=a;b.thisArg=e;b.source=f;b.index=0;b.thisArg=e||b;return b}h(a,c);a.prototype.notifyComplete=function(b){this.destination.next(b);this.destination.complete()}; -a.prototype._next=function(b){var a=!1;try{a=this.predicate.call(this.thisArg,b,this.index++,this.source)}catch(e){this.destination.error(e);return}a||this.notifyComplete(!1)};a.prototype._complete=function(){this.notifyComplete(!0)};return a}(m),Yd=function(){function c(){}c.prototype.call=function(a,b){return b.subscribe(new Xd(a))};return c}(),Xd=function(c){function a(b){b=c.call(this,b)||this;b.hasCompleted=!1;b.hasSubscription=!1;return b}h(a,c);a.prototype._next=function(b){this.hasSubscription|| -(this.hasSubscription=!0,this.add(p(this,b)))};a.prototype._complete=function(){this.hasCompleted=!0;this.hasSubscription||this.destination.complete()};a.prototype.notifyComplete=function(b){this.remove(b);this.hasSubscription=!1;this.hasCompleted&&this.destination.complete()};return a}(q),qc=function(){function c(a){this.project=a}c.prototype.call=function(a,b){return b.subscribe(new Zd(a,this.project))};return c}(),Zd=function(c){function a(b,a){b=c.call(this,b)||this;b.project=a;b.hasSubscription= -!1;b.hasCompleted=!1;b.index=0;return b}h(a,c);a.prototype._next=function(b){this.hasSubscription||this.tryNext(b)};a.prototype.tryNext=function(b){var a,c=this.index++;try{a=this.project(b,c)}catch(f){this.destination.error(f);return}this.hasSubscription=!0;this._innerSub(a,b,c)};a.prototype._innerSub=function(b,a,c){var d=new J(this,void 0,void 0);this.destination.add(d);p(this,b,a,c,d)};a.prototype._complete=function(){this.hasCompleted=!0;this.hasSubscription||this.destination.complete();this.unsubscribe()}; -a.prototype.notifyNext=function(b,a,c,f,g){this.destination.next(a)};a.prototype.notifyError=function(b){this.destination.error(b)};a.prototype.notifyComplete=function(b){this.destination.remove(b);this.hasSubscription=!1;this.hasCompleted&&this.destination.complete()};return a}(q),ae=function(){function c(a,b,c){this.project=a;this.concurrent=b;this.scheduler=c}c.prototype.call=function(a,b){return b.subscribe(new $d(a,this.project,this.concurrent,this.scheduler))};return c}(),$d=function(c){function a(b, -a,e,f){b=c.call(this,b)||this;b.project=a;b.concurrent=e;b.scheduler=f;b.index=0;b.active=0;b.hasCompleted=!1;ethis.total)throw new O;}c.prototype.call=function(a,b){return b.subscribe(new ie(a,this.total))};return c}(),ie=function(c){function a(b,a){b=c.call(this,b)||this;b.total=a;b.ring=[];b.count=0;return b}h(a,c);a.prototype._next=function(b){var a=this.ring,c=this.total,f= -this.count++;a.length=this.total?this.total:this.count,f=this.ring,g=0;gthis.total&&this.destination.next(a)};return a}(m),Ne=function(){function c(a){this._skipCount= -a;if(0>this._skipCount)throw new O;}c.prototype.call=function(a,b){return 0===this._skipCount?b.subscribe(new m(a)):b.subscribe(new Me(a,this._skipCount))};return c}(),Me=function(c){function a(a,d){a=c.call(this,a)||this;a._skipCount=d;a._count=0;a._ring=Array(d);return a}h(a,c);a.prototype._next=function(a){var b=this._skipCount,c=this._count++;if(cd)b.delayTime=0;e&&"function"===typeof e.schedule||(b.scheduler=ma);return b}h(a,c);a.create=function(b,c,e){void 0===c&&(c=0);void 0===e&&(e=ma);return new a(b,c,e)};a.dispatch=function(a){return this.add(a.source.subscribe(a.subscriber))};a.prototype._subscribe=function(b){return this.scheduler.schedule(a.dispatch,this.delayTime,{source:this.source,subscriber:b})};return a}(n),Te=function(){function c(a, -b){this.scheduler=a;this.delay=b}c.prototype.call=function(a,b){return(new Se(b,this.delay,this.scheduler)).subscribe(a)};return c}(),Cc=function(){function c(a){this.project=a}c.prototype.call=function(a,b){return b.subscribe(new Ue(a,this.project))};return c}(),Ue=function(c){function a(a,d){a=c.call(this,a)||this;a.project=d;a.index=0;return a}h(a,c);a.prototype._next=function(a){var b,c=this.index++;try{b=this.project(a,c)}catch(f){this.destination.error(f);return}this._innerSub(b,a,c)};a.prototype._innerSub= -function(a,c,e){var b=this.innerSubscription;b&&b.unsubscribe();b=new J(this,void 0,void 0);this.destination.add(b);this.innerSubscription=p(this,a,c,e,b)};a.prototype._complete=function(){var a=this.innerSubscription;a&&!a.closed||c.prototype._complete.call(this);this.unsubscribe()};a.prototype._unsubscribe=function(){this.innerSubscription=null};a.prototype.notifyComplete=function(a){this.destination.remove(a);this.innerSubscription=null;this.isStopped&&c.prototype._complete.call(this)};a.prototype.notifyNext= -function(a,c,e,f,g){this.destination.next(c)};return a}(q),We=function(){function c(a){this.notifier=a}c.prototype.call=function(a,b){a=new Ve(a);var c=p(a,this.notifier);return c&&!a.seenValue?(a.add(c),b.subscribe(a)):a};return c}(),Ve=function(c){function a(a){a=c.call(this,a)||this;a.seenValue=!1;return a}h(a,c);a.prototype.notifyNext=function(a,c,e,f,g){this.seenValue=!0;this.complete()};a.prototype.notifyComplete=function(){};return a}(q),Ye=function(){function c(a,b){this.predicate=a;this.inclusive= -b}c.prototype.call=function(a,b){return b.subscribe(new Xe(a,this.predicate,this.inclusive))};return c}(),Xe=function(c){function a(a,d,e){a=c.call(this,a)||this;a.predicate=d;a.inclusive=e;a.index=0;return a}h(a,c);a.prototype._next=function(a){var b=this.destination,c;try{c=this.predicate(a,this.index++)}catch(f){b.error(f);return}this.nextOrComplete(a,c)};a.prototype.nextOrComplete=function(a,c){var b=this.destination;c?b.next(a):(this.inclusive&&b.next(a),b.complete())};return a}(m),Ib={leading:!0, -trailing:!1},$e=function(){function c(a,b,c){this.durationSelector=a;this.leading=b;this.trailing=c}c.prototype.call=function(a,b){return b.subscribe(new Ze(a,this.durationSelector,this.leading,this.trailing))};return c}(),Ze=function(c){function a(a,d,e,f){var b=c.call(this,a)||this;b.destination=a;b.durationSelector=d;b._leading=e;b._trailing=f;b._hasValue=!1;return b}h(a,c);a.prototype._next=function(a){this._hasValue=!0;this._sendValue=a;this._throttled||(this._leading?this.send():this.throttle(a))}; -a.prototype.send=function(){var a=this._sendValue;this._hasValue&&(this.destination.next(a),this.throttle(a));this._hasValue=!1;this._sendValue=null};a.prototype.throttle=function(a){(a=this.tryDurationSelector(a))&&this.add(this._throttled=p(this,a))};a.prototype.tryDurationSelector=function(a){try{return this.durationSelector(a)}catch(d){return this.destination.error(d),null}};a.prototype.throttlingDone=function(){var a=this._throttled,c=this._trailing;a&&a.unsubscribe();this._throttled=null;c&& -this.send()};a.prototype.notifyNext=function(a,c,e,f,g){this.throttlingDone()};a.prototype.notifyComplete=function(){this.throttlingDone()};return a}(q),bf=function(){function c(a,b,c,e){this.duration=a;this.scheduler=b;this.leading=c;this.trailing=e}c.prototype.call=function(a,b){return b.subscribe(new af(a,this.duration,this.scheduler,this.leading,this.trailing))};return c}(),af=function(c){function a(a,d,e,f,g){a=c.call(this,a)||this;a.duration=d;a.scheduler=e;a.leading=f;a.trailing=g;a._hasTrailingValue= -!1;a._trailingValue=null;return a}h(a,c);a.prototype._next=function(a){this.throttled?this.trailing&&(this._trailingValue=a,this._hasTrailingValue=!0):(this.add(this.throttled=this.scheduler.schedule(Dc,this.duration,{subscriber:this})),this.leading&&this.destination.next(a))};a.prototype._complete=function(){this._hasTrailingValue&&this.destination.next(this._trailingValue);this.destination.complete()};a.prototype.clearThrottle=function(){var a=this.throttled;a&&(this.trailing&&this._hasTrailingValue&& -(this.destination.next(this._trailingValue),this._trailingValue=null,this._hasTrailingValue=!1),a.unsubscribe(),this.remove(a),this.throttled=null)};return a}(m),cf=function(){return function(c,a){this.value=c;this.interval=a}}(),Ec=function(){function c(a,b,c,e){this.waitFor=a;this.absoluteTimeout=b;this.withObservable=c;this.scheduler=e}c.prototype.call=function(a,b){return b.subscribe(new df(a,this.absoluteTimeout,this.waitFor,this.withObservable,this.scheduler))};return c}(),df=function(c){function a(a, -d,e,f,g){a=c.call(this,a)||this;a.absoluteTimeout=d;a.waitFor=e;a.withObservable=f;a.scheduler=g;a.action=null;a.scheduleTimeout();return a}h(a,c);a.dispatchTimeout=function(a){var b=a.withObservable;a._unsubscribeAndRecycle();a.add(p(a,b))};a.prototype.scheduleTimeout=function(){var b=this.action;b?this.action=b.schedule(this,this.waitFor):this.add(this.action=this.scheduler.schedule(a.dispatchTimeout,this.waitFor,this))};a.prototype._next=function(a){this.absoluteTimeout||this.scheduleTimeout(); -c.prototype._next.call(this,a)};a.prototype._unsubscribe=function(){this.withObservable=this.scheduler=this.action=null};return a}(q),ef=function(){return function(c,a){this.value=c;this.timestamp=a}}(),gf=function(){function c(a){this.windowBoundaries=a}c.prototype.call=function(a,b){a=new ff(a);b=b.subscribe(a);b.closed||a.add(p(a,this.windowBoundaries));return b};return c}(),ff=function(c){function a(a){var b=c.call(this,a)||this;b.window=new u;a.next(b.window);return b}h(a,c);a.prototype.notifyNext= -function(a,c,e,f,g){this.openWindow()};a.prototype.notifyError=function(a,c){this._error(a)};a.prototype.notifyComplete=function(a){this._complete()};a.prototype._next=function(a){this.window.next(a)};a.prototype._error=function(a){this.window.error(a);this.destination.error(a)};a.prototype._complete=function(){this.window.complete();this.destination.complete()};a.prototype._unsubscribe=function(){this.window=null};a.prototype.openWindow=function(){var a=this.window;a&&a.complete();var a=this.destination, -c=this.window=new u;a.next(c)};return a}(q),jf=function(){function c(a,b){this.windowSize=a;this.startWindowEvery=b}c.prototype.call=function(a,b){return b.subscribe(new hf(a,this.windowSize,this.startWindowEvery))};return c}(),hf=function(c){function a(a,d,e){var b=c.call(this,a)||this;b.destination=a;b.windowSize=d;b.startWindowEvery=e;b.windows=[new u];b.count=0;a.next(b.windows[0]);return b}h(a,c);a.prototype._next=function(a){for(var b=0=this.maxWindowSize&&this.closeWindow(g))}};a.prototype._error=function(a){for(var b=this.windows;0c)throw new O; -var b=2<=arguments.length;return function(d){return d.pipe(Y(function(a,b){return b===c}),za(1),b?ba(a):na(function(){return new O}))}},endWith:function(){for(var c=[],a=0;a(a||0)?Number.POSITIVE_INFINITY:a;return function(d){return d.lift(new ae(c,a,b))}},filter:Y,finalize:function(c){return function(a){return a.lift(new ce(c))}},find:function(c,a){if("function"!==typeof c)throw new TypeError("predicate is not a function");return function(b){return b.lift(new Gb(c,b,!1,a))}},findIndex:function(c,a){return function(b){return b.lift(new Gb(c,b,!0,a))}},first:function(c,a){var b=2<=arguments.length; -return function(d){return d.pipe(c?Y(function(a,b){return c(a,b,d)}):N,za(1),b?ba(a):na(function(){return new ca}))}},groupBy:function(c,a,b,d){return function(e){return e.lift(new Tc(c,a,b,d))}},ignoreElements:function(){return function(c){return c.lift(new fe)}},isEmpty:function(){return function(c){return c.lift(new he)}},last:function(c,a){var b=2<=arguments.length;return function(d){return d.pipe(c?Y(function(a,b){return c(a,b,d)}):N,ha(1),b?ba(a):na(function(){return new ca}))}},map:C,mapTo:function(c){return function(a){return a.lift(new ke(c))}}, -materialize:function(){return function(c){return c.lift(new me)}},max:function(c){return ja("function"===typeof c?function(a,b){return 0b?a:b})},merge:function(){for(var c=[],a=0;ac(a,b)?a:b}:function(a,b){return ac?a.lift(new Hb(-1,a)):a.lift(new Hb(c-1,a))}},repeatWhen:function(c){return function(a){return a.lift(new we(c))}}, -retry:function(c){void 0===c&&(c=-1);return function(a){return a.lift(new ye(c,a))}},retryWhen:function(c){return function(a){return a.lift(new Ae(c,a))}},refCount:ra,sample:function(c){return function(a){return a.lift(new Ce(c))}},sampleTime:function(c,a){void 0===a&&(a=y);return function(b){return b.lift(new Ee(c,a))}},scan:ia,sequenceEqual:function(c,a){return function(b){return b.lift(new Ge(c,a))}},share:function(){return function(c){return ra()(Q(yc)(c))}},shareReplay:function(c,a,b){var d; -d=c&&"object"===typeof c?c:{bufferSize:c,windowTime:a,refCount:!1,scheduler:b};return function(a){return a.lift(zc(d))}},single:function(c){return function(a){return a.lift(new Je(c,a))}},skip:function(c){return function(a){return a.lift(new Le(c))}},skipLast:function(c){return function(a){return a.lift(new Ne(c))}},skipUntil:function(c){return function(a){return a.lift(new Pe(c))}},skipWhile:function(c){return function(a){return a.lift(new Re(c))}},startWith:function(){for(var c=[],a=0;ak?new ga(h):new ga(h,k)};a.parseMarbles=function(a,c, -e,f,g){var b=this;void 0===f&&(f=!1);void 0===g&&(g=!1);if(-1!==a.indexOf("!"))throw Error('conventional marble diagrams cannot have the unsubscription marker "!"');for(var d=a.length,h=[],k=g?a.replace(/^[ ]+/,"").indexOf("^"):a.indexOf("^"),m=-1===k?0:k*-this.frameTimeFactor,n="object"!==typeof c?function(a){return a}:function(a){return f&&c[a]instanceof Ha?c[a].messages:c[a]},p=-1,k=function(c){var d=m,f=function(a){d+=a*b.frameTimeFactor},l=void 0,k=a[c];switch(k){case " ":g||f(1);break;case "-":f(1); -break;case "(":p=m;f(1);break;case ")":p=-1;f(1);break;case "|":l=w.createComplete();f(1);break;case "^":f(1);break;case "#":l=w.createError(e||"error");f(1);break;default:if(g&&k.match(/^[0-9]$/)&&(0===c||" "===a[c-1])){var r=a.slice(c).match(/^([0-9]+(?:\.[0-9]+)?)(ms|s|m) /);if(r){c+=r[0].length-1;var k=parseFloat(r[1]),v=void 0;switch(r[2]){case "ms":v=k;break;case "s":v=1E3*k;break;case "m":v=6E4*k}f(v/q.frameTimeFactor);break}}l=w.createNext(n(k));f(1)}l&&h.push({frame:-1d;d++)try{b=c[d];new B.ActiveXObject(b);break}catch(r){}a=new B.ActiveXObject(b)}catch(r){throw Error("XMLHttpRequest is not supported by your browser");}}return a},crossDomain:!0,withCredentials:!1, -headers:{},method:"GET",responseType:"json",timeout:0};if("string"===typeof a)e.url=a;else for(var f in a)a.hasOwnProperty(f)&&(e[f]=a[f]);b.request=e;return b}h(a,c);a.prototype._subscribe=function(a){return new Af(a,this.request)};a.create=function(){var b=function(b){return new a(b)};b.get=Ic;b.post=Jc;b.delete=Kc;b.put=Lc;b.patch=Mc;b.getJSON=Nc;return b}();return a}(n),Af=function(c){function a(a,d){a=c.call(this,a)||this;a.request=d;a.done=!1;var b=d.headers=d.headers||{};d.crossDomain||a.getHeader(b, -"X-Requested-With")||(b["X-Requested-With"]="XMLHttpRequest");a.getHeader(b,"Content-Type")||B.FormData&&d.body instanceof B.FormData||"undefined"===typeof d.body||(b["Content-Type"]="application/x-www-form-urlencoded; charset\x3dUTF-8");d.body=a.serializeBody(d.body,a.getHeader(d.headers,"Content-Type"));a.send();return a}h(a,c);a.prototype.next=function(a){this.done=!0;var b=this.xhr,c=this.request,f=this.destination,g;try{g=new Lb(a,b,c)}catch(l){return f.error(l)}f.next(g)};a.prototype.send=function(){var a= -this.request,c=this.request,e=c.user,f=c.method,g=c.url,h=c.async,k=c.password,m=c.headers,c=c.body;try{var r=this.xhr=a.createXHR();this.setupEvents(r,a);e?r.open(f,g,h,e,k):r.open(f,g,h);h&&(r.timeout=a.timeout,r.responseType=a.responseType);"withCredentials"in r&&(r.withCredentials=!!a.withCredentials);this.setHeaders(r,m);c?r.send(c):r.send()}catch(Ac){this.error(Ac)}};a.prototype.serializeBody=function(a,c){if(!a||"string"===typeof a||B.FormData&&a instanceof B.FormData)return a;if(c){var b= -c.indexOf(";");-1!==b&&(c=c.substring(0,b))}switch(c){case "application/x-www-form-urlencoded":return Object.keys(a).map(function(b){return encodeURIComponent(b)+"\x3d"+encodeURIComponent(a[b])}).join("\x26");case "application/json":return JSON.stringify(a);default:return a}};a.prototype.setHeaders=function(a,c){for(var b in c)c.hasOwnProperty(b)&&a.setRequestHeader(b,c[b])};a.prototype.getHeader=function(a,c){for(var b in a)if(b.toLowerCase()===c.toLowerCase())return a[b]};a.prototype.setupEvents= -function(a,c){function b(a){var c=b.subscriber,d=b.progressSubscriber,e=b.request;d&&d.error(a);var f;try{f=new Mb(this,e)}catch(Ia){f=Ia}c.error(f)}function d(a){}function g(a){var b=g.subscriber,c=g.progressSubscriber,d=g.request;if(4===this.readyState){var e=1223===this.status?204:this.status,f="text"===this.responseType?this.response||this.responseText:this.response;0===e&&(e=f?200:0);if(400>e)c&&c.complete(),b.next(a),b.complete();else{c&&c.error(a);a=void 0;try{a=new oa("ajax error "+e,this, -d)}catch(vf){a=vf}b.error(a)}}}var h=c.progressSubscriber;a.ontimeout=b;b.request=c;b.subscriber=this;b.progressSubscriber=h;if(a.upload&&"withCredentials"in a){if(h){var k;k=function(a){k.progressSubscriber.next(a)};B.XDomainRequest?a.onprogress=k:a.upload.onprogress=k;k.progressSubscriber=h}var m;m=function(a){var b=m.progressSubscriber,c=m.subscriber,d=m.request;b&&b.error(a);var e;try{e=new oa("ajax error",this,d)}catch(Ia){e=Ia}c.error(e)};a.onerror=m;m.request=c;m.subscriber=this;m.progressSubscriber= -h}a.onreadystatechange=d;d.subscriber=this;d.progressSubscriber=h;d.request=c;a.onload=g;g.subscriber=this;g.progressSubscriber=h;g.request=c};a.prototype.unsubscribe=function(){var a=this.xhr;!this.done&&a&&4!==a.readyState&&"function"===typeof a.abort&&a.abort();c.prototype.unsubscribe.call(this)};return a}(m),Lb=function(){return function(c,a,b){this.originalEvent=c;this.xhr=a;this.request=b;this.status=a.status;this.responseType=a.responseType||b.responseType;this.response=sb(this.responseType, -a)}}();rb.prototype=Object.create(Error.prototype);var oa=rb,Mb=function(c,a){oa.call(this,"ajax timeout",c,a);this.name="AjaxTimeoutError";return this},Bf=Object.freeze({ajax:R.create,AjaxResponse:Lb,AjaxError:oa,AjaxTimeoutError:Mb}),Cf={url:"",deserializer:function(c){return JSON.parse(c.data)},serializer:function(c){return JSON.stringify(c)}},Nb=function(c){function a(a,d){var b=c.call(this)||this;if(a instanceof n)b.destination=d,b.source=a;else{d=b._config=Pc({},Cf);b._output=new u;if("string"=== -typeof a)d.url=a;else for(var f in a)a.hasOwnProperty(f)&&(d[f]=a[f]);if(!d.WebSocketCtor&&WebSocket)d.WebSocketCtor=WebSocket;else if(!d.WebSocketCtor)throw Error("no WebSocket constructor can be found");b.destination=new Z}return b}h(a,c);a.prototype.lift=function(b){var c=new a(this._config,this.destination);c.operator=b;c.source=this;return c};a.prototype._resetState=function(){this._socket=null;this.source||(this.destination=new Z);this._output=new u};a.prototype.multiplex=function(a,c,e){var b= -this;return new n(function(d){try{b.next(a())}catch(v){d.error(v)}var f=b.subscribe(function(a){try{e(a)&&d.next(a)}catch(x){d.error(x)}},function(a){return d.error(a)},function(){return d.complete()});return function(){try{b.next(c())}catch(v){d.error(v)}f.unsubscribe()}})};a.prototype._connectSocket=function(){var a=this,c=this._config,e=c.WebSocketCtor,f=c.protocol,g=c.url,c=c.binaryType,h=this._output,k=null;try{this._socket=k=f?new e(g,f):new e(g),c&&(this._socket.binaryType=c)}catch(r){h.error(r); -return}var n=new t(function(){a._socket=null;k&&1===k.readyState&&k.close()});k.onopen=function(b){if(a._socket){var c=a._config.openObserver;c&&c.next(b);b=a.destination;a.destination=m.create(function(b){if(1===k.readyState)try{var c=a._config.serializer;k.send(c(b))}catch(uf){a.destination.error(uf)}},function(b){var c=a._config.closingObserver;c&&c.next(void 0);b&&b.code?k.close(b.code,b.reason):h.error(new TypeError("WebSocketSubject.error must be called with an object with an error code, and an optional reason: { code: number, reason: string }")); -a._resetState()},function(){var b=a._config.closingObserver;b&&b.next(void 0);k.close();a._resetState()});b&&b instanceof Z&&n.add(b.subscribe(a.destination))}else k.close(),a._resetState()};k.onerror=function(b){a._resetState();h.error(b)};k.onclose=function(b){a._resetState();var c=a._config.closeObserver;c&&c.next(b);b.wasClean?h.complete():h.error(b)};k.onmessage=function(b){try{var c=a._config.deserializer;h.next(c(b))}catch(Bc){h.error(Bc)}}};a.prototype._subscribe=function(a){var b=this,c= -this.source;if(c)return c.subscribe(a);this._socket||this._connectSocket();this._output.subscribe(a);a.add(function(){var a=b._socket;0===b._output.observers.length&&(a&&1===a.readyState&&a.close(),b._resetState())});return a};a.prototype.unsubscribe=function(){var a=this._socket;a&&1===a.readyState&&a.close();this._resetState();c.prototype.unsubscribe.call(this)};return a}(Ba),Df=Object.freeze({webSocket:function(c){return new Nb(c)},WebSocketSubject:Nb});k.operators=tf;k.testing=xf;k.ajax=Bf;k.webSocket= -Df;k.Observable=n;k.ConnectableObservable=wb;k.GroupedObservable=Ca;k.observable=W;k.Subject=u;k.BehaviorSubject=xb;k.ReplaySubject=Z;k.AsyncSubject=V;k.asapScheduler=ma;k.asyncScheduler=y;k.queueScheduler=yb;k.animationFrameScheduler=cd;k.VirtualTimeScheduler=Cb;k.VirtualAction=Fa;k.Scheduler=Da;k.Subscription=t;k.Subscriber=m;k.Notification=w;k.pipe=qa;k.noop=E;k.identity=N;k.isObservable=function(c){return!!c&&(c instanceof n||"function"===typeof c.lift&&"function"===typeof c.subscribe)};k.ArgumentOutOfRangeError= -O;k.EmptyError=ca;k.ObjectUnsubscribedError=F;k.UnsubscriptionError=aa;k.TimeoutError=va;k.bindCallback=Pa;k.bindNodeCallback=Qa;k.combineLatest=function(){for(var c=[],a=0;ac)c=0;a&&"function"===typeof a.schedule||(a=y);return new n(function(b){b.add(a.schedule(cc,c,{subscriber:b,counter:0,period:c}));return b})};k.merge=cb;k.never=function(){return Eb};k.of=ta;k.onErrorResumeNext=ya;k.pairs=function(c,a){return a?new n(function(b){var d=Object.keys(c),e=new t;e.add(a.schedule(dc,0,{keys:d,index:0,subscriber:b,subscription:e,obj:c})); -return e}):new n(function(a){for(var b=Object.keys(c),e=0;e=a){d.complete();break}d.next(f++);if(d.closed)break}while(1)})};k.throwError=ua;k.timer=eb;k.using=function(c,a){return new n(function(b){var d;try{d=c()}catch(g){b.error(g); -return}var e;try{e=a(d)}catch(g){b.error(g);return}var f=(e?K(e):M).subscribe(b);return function(){f.unsubscribe();d&&d.unsubscribe()}})};k.zip=fb;k.EMPTY=M;k.NEVER=Eb;k.config=D;Object.defineProperty(k,"__esModule",{value:!0})}); +this.value);c.prototype.complete.call(this)};return a}(v),Xc=1,Ha={},zb={setImmediate:function(c){var a=Xc++;Ha[a]=c;Promise.resolve().then(function(){var b=Ha[a];b&&b()});return a},clearImmediate:function(c){delete Ha[c]}},Yc=function(c){function a(b,a){var d=c.call(this,b,a)||this;d.scheduler=b;d.work=a;return d}h(a,c);a.prototype.requestAsyncId=function(b,a,e){void 0===e&&(e=0);if(null!==e&&0a.index?1:-1:b.delay>a.delay?1:-1};return a}(fa);K.prototype=Object.create(Error.prototype);Ra.prototype=Object.create(Error.prototype);var ca=Ra;ya.prototype=Object.create(Error.prototype);var Qb=function(){function c(a,b){this.project=a;this.thisArg=b}c.prototype.call=function(a, +b){return b.subscribe(new ad(a,this.project,this.thisArg))};return c}(),ad=function(c){function a(b,a,e){b=c.call(this,b)||this;b.project=a;b.count=0;b.thisArg=e||b;return b}h(a,c);a.prototype._next=function(b){var a;try{a=this.project.call(this.thisArg,b,this.count++)}catch(e){this.destination.error(e);return}this.destination.next(a)};return a}(m),q=function(c){function a(){return null!==c&&c.apply(this,arguments)||this}h(a,c);a.prototype.notifyNext=function(b,a,c,f,g){this.destination.next(a)}; +a.prototype.notifyError=function(b,a){this.destination.error(b)};a.prototype.notifyComplete=function(b){this.destination.complete()};return a}(m),H=function(c){function a(b,a,e){var d=c.call(this)||this;d.parent=b;d.outerValue=a;d.outerIndex=e;d.index=0;return d}h(a,c);a.prototype._next=function(b){this.parent.notifyNext(this.outerValue,b,this.outerIndex,this.index++,this)};a.prototype._error=function(b){this.parent.notifyError(b,this);this.unsubscribe()};a.prototype._complete=function(){this.parent.notifyComplete(this); +this.unsubscribe()};return a}(m),bd=function(c){return function(a){c.then(function(b){a.closed||(a.next(b),a.complete())},function(b){return a.error(b)}).then(null,R);return a}},F;F="function"===typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator";var cd=function(c){return function(a){var b=c[F]();do{var d=b.next();if(d.done){a.complete();break}a.next(d.value);if(a.closed)break}while(1);"function"===typeof b.return&&a.add(function(){b.return&&b.return()});return a}},dd=function(c){return function(a){var b= +c[V]();if("function"!==typeof b.subscribe)throw new TypeError("Provided object does not correctly implement Symbol.observable");return b.subscribe(a)}},Xa=function(c){return c&&"number"===typeof c.length&&"function"!==typeof c},ia=function(c){if(c&&"function"===typeof c[V])return dd(c);if(Xa(c))return Qa(c);if(Va(c))return bd(c);if(c&&"function"===typeof c[F])return cd(c);c=sa(c)?"an invalid object":"'"+c+"'";throw new TypeError("You provided "+c+" where a stream was expected. You can provide an Observable, Promise, Array, or Iterable."); +},Bb={},Ja=function(){function c(a){this.resultSelector=a}c.prototype.call=function(a,b){return b.subscribe(new ed(a,this.resultSelector))};return c}(),ed=function(c){function a(b,a){b=c.call(this,b)||this;b.resultSelector=a;b.active=0;b.values=[];b.observables=[];return b}h(a,c);a.prototype._next=function(b){this.values.push(Bb);this.observables.push(b)};a.prototype._complete=function(){var b=this.observables,a=b.length;if(0===a)this.destination.complete();else{this.toRespond=this.active=a;for(var c= +0;cthis.index};c.prototype.hasCompleted=function(){return this.array.length===this.index};return c}(),ld=function(c){function a(b,a,e){b=c.call(this,b)||this;b.parent=a;b.observable=e; +b.stillUnsubscribed=!0;b.buffer=[];b.isComplete=!1;return b}h(a,c);a.prototype[F]=function(){return this};a.prototype.next=function(){var b=this.buffer;return 0===b.length&&this.isComplete?{value:null,done:!0}:{value:b.shift(),done:!1}};a.prototype.hasValue=function(){return 0e;if(b.timespanOnly)b.add(f.closeAction=g.schedule(ib,a,{subscriber:b,context:f,bufferTimeSpan:a}));else{var d={bufferTimeSpan:a,bufferCreationInterval:e,subscriber:b,scheduler:g};b.add(f.closeAction=g.schedule(jb,a,{subscriber:b,context:f}));b.add(g.schedule(jc,e,d))}return b}h(a,c);a.prototype._next=function(b){for(var a=this.contexts,c=a.length,f,g=0;g=c[0].time-f.now();)c.shift().notification.observe(g);0this.total)throw new K; +}c.prototype.call=function(a,b){return b.subscribe(new Ud(a,this.total))};return c}(),Ud=function(c){function a(b,a){b=c.call(this,b)||this;b.total=a;b.count=0;return b}h(a,c);a.prototype._next=function(b){var a=this.total,c=++this.count;c<=a&&(this.destination.next(b),c===a&&(this.destination.complete(),this.unsubscribe()))};return a}(m),Wd=function(){function c(a,b,c){this.predicate=a;this.thisArg=b;this.source=c}c.prototype.call=function(a,b){return b.subscribe(new Vd(a,this.predicate,this.thisArg, +this.source))};return c}(),Vd=function(c){function a(b,a,e,f){b=c.call(this,b)||this;b.predicate=a;b.thisArg=e;b.source=f;b.index=0;b.thisArg=e||b;return b}h(a,c);a.prototype.notifyComplete=function(b){this.destination.next(b);this.destination.complete()};a.prototype._next=function(b){var a=!1;try{a=this.predicate.call(this.thisArg,b,this.index++,this.source)}catch(e){this.destination.error(e);return}a||this.notifyComplete(!1)};a.prototype._complete=function(){this.notifyComplete(!0)};return a}(m), +Yd=function(){function c(){}c.prototype.call=function(a,b){return b.subscribe(new Xd(a))};return c}(),Xd=function(c){function a(b){b=c.call(this,b)||this;b.hasCompleted=!1;b.hasSubscription=!1;return b}h(a,c);a.prototype._next=function(b){this.hasSubscription||(this.hasSubscription=!0,this.add(p(this,b)))};a.prototype._complete=function(){this.hasCompleted=!0;this.hasSubscription||this.destination.complete()};a.prototype.notifyComplete=function(b){this.remove(b);this.hasSubscription=!1;this.hasCompleted&& +this.destination.complete()};return a}(q),qc=function(){function c(a){this.project=a}c.prototype.call=function(a,b){return b.subscribe(new Zd(a,this.project))};return c}(),Zd=function(c){function a(b,a){b=c.call(this,b)||this;b.project=a;b.hasSubscription=!1;b.hasCompleted=!1;b.index=0;return b}h(a,c);a.prototype._next=function(b){this.hasSubscription||this.tryNext(b)};a.prototype.tryNext=function(b){var a,c=this.index++;try{a=this.project(b,c)}catch(f){this.destination.error(f);return}this.hasSubscription= +!0;this._innerSub(a,b,c)};a.prototype._innerSub=function(b,a,c){var d=new H(this,void 0,void 0);this.destination.add(d);p(this,b,a,c,d)};a.prototype._complete=function(){this.hasCompleted=!0;this.hasSubscription||this.destination.complete();this.unsubscribe()};a.prototype.notifyNext=function(b,a,c,f,g){this.destination.next(a)};a.prototype.notifyError=function(b){this.destination.error(b)};a.prototype.notifyComplete=function(b){this.destination.remove(b);this.hasSubscription=!1;this.hasCompleted&& +this.destination.complete()};return a}(q),ae=function(){function c(a,b,c){this.project=a;this.concurrent=b;this.scheduler=c}c.prototype.call=function(a,b){return b.subscribe(new $d(a,this.project,this.concurrent,this.scheduler))};return c}(),$d=function(c){function a(b,a,e,f){b=c.call(this,b)||this;b.project=a;b.concurrent=e;b.scheduler=f;b.index=0;b.active=0;b.hasCompleted=!1;ethis.total)throw new K; +}c.prototype.call=function(a,b){return b.subscribe(new ie(a,this.total))};return c}(),ie=function(c){function a(b,a){b=c.call(this,b)||this;b.total=a;b.ring=[];b.count=0;return b}h(a,c);a.prototype._next=function(b){var a=this.ring,c=this.total,f=this.count++;a.length=this.total?this.total:this.count,f=this.ring,g=0;gthis.total&&this.destination.next(b)};return a}(m),Ne=function(){function c(a){this._skipCount=a;if(0>this._skipCount)throw new K;}c.prototype.call=function(a,b){return 0===this._skipCount?b.subscribe(new m(a)):b.subscribe(new Me(a,this._skipCount))};return c}(),Me=function(c){function a(b,a){b=c.call(this,b)||this;b._skipCount=a;b._count=0; +b._ring=Array(a);return b}h(a,c);a.prototype._next=function(b){var a=this._skipCount,c=this._count++;if(cd)b.delayTime=0;e&&"function"===typeof e.schedule||(b.scheduler=qa);return b}h(a,c);a.create=function(b,c,e){void 0=== +c&&(c=0);void 0===e&&(e=qa);return new a(b,c,e)};a.dispatch=function(a){return this.add(a.source.subscribe(a.subscriber))};a.prototype._subscribe=function(b){return this.scheduler.schedule(a.dispatch,this.delayTime,{source:this.source,subscriber:b})};return a}(n),Te=function(){function c(a,b){this.scheduler=a;this.delay=b}c.prototype.call=function(a,b){return(new Se(b,this.delay,this.scheduler)).subscribe(a)};return c}(),zc=function(){function c(a){this.project=a}c.prototype.call=function(a,b){return b.subscribe(new Ue(a, +this.project))};return c}(),Ue=function(c){function a(a,d){a=c.call(this,a)||this;a.project=d;a.index=0;return a}h(a,c);a.prototype._next=function(a){var b,c=this.index++;try{b=this.project(a,c)}catch(f){this.destination.error(f);return}this._innerSub(b,a,c)};a.prototype._innerSub=function(a,c,e){var b=this.innerSubscription;b&&b.unsubscribe();b=new H(this,void 0,void 0);this.destination.add(b);this.innerSubscription=p(this,a,c,e,b)};a.prototype._complete=function(){var a=this.innerSubscription;a&& +!a.closed||c.prototype._complete.call(this);this.unsubscribe()};a.prototype._unsubscribe=function(){this.innerSubscription=null};a.prototype.notifyComplete=function(a){this.destination.remove(a);this.innerSubscription=null;this.isStopped&&c.prototype._complete.call(this)};a.prototype.notifyNext=function(a,c,e,f,g){this.destination.next(c)};return a}(q),We=function(){function c(a){this.notifier=a}c.prototype.call=function(a,b){a=new Ve(a);var c=p(a,this.notifier);return c&&!a.seenValue?(a.add(c),b.subscribe(a)): +a};return c}(),Ve=function(c){function a(a){a=c.call(this,a)||this;a.seenValue=!1;return a}h(a,c);a.prototype.notifyNext=function(a,c,e,f,g){this.seenValue=!0;this.complete()};a.prototype.notifyComplete=function(){};return a}(q),Ye=function(){function c(a,b){this.predicate=a;this.inclusive=b}c.prototype.call=function(a,b){return b.subscribe(new Xe(a,this.predicate,this.inclusive))};return c}(),Xe=function(c){function a(a,d,e){a=c.call(this,a)||this;a.predicate=d;a.inclusive=e;a.index=0;return a}h(a, +c);a.prototype._next=function(a){var b=this.destination,c;try{c=this.predicate(a,this.index++)}catch(f){b.error(f);return}this.nextOrComplete(a,c)};a.prototype.nextOrComplete=function(a,c){var b=this.destination;c?b.next(a):(this.inclusive&&b.next(a),b.complete())};return a}(m),$e=function(){function c(a,b,c){this.nextOrObserver=a;this.error=b;this.complete=c}c.prototype.call=function(a,b){return b.subscribe(new Ze(a,this.nextOrObserver,this.error,this.complete))};return c}(),Ze=function(c){function a(a, +d,e,f){a=c.call(this,a)||this;a._tapNext=D;a._tapError=D;a._tapComplete=D;a._tapError=e||D;a._tapComplete=f||D;Q(d)?(a._context=a,a._tapNext=d):d&&(a._context=d,a._tapNext=d.next||D,a._tapError=d.error||D,a._tapComplete=d.complete||D);return a}h(a,c);a.prototype._next=function(a){try{this._tapNext.call(this._context,a)}catch(d){this.destination.error(d);return}this.destination.next(a)};a.prototype._error=function(a){try{this._tapError.call(this._context,a)}catch(d){this.destination.error(d);return}this.destination.error(a)}; +a.prototype._complete=function(){try{this._tapComplete.call(this._context)}catch(b){this.destination.error(b);return}return this.destination.complete()};return a}(m),Gb={leading:!0,trailing:!1},bf=function(){function c(a,b,c){this.durationSelector=a;this.leading=b;this.trailing=c}c.prototype.call=function(a,b){return b.subscribe(new af(a,this.durationSelector,this.leading,this.trailing))};return c}(),af=function(c){function a(a,d,e,f){var b=c.call(this,a)||this;b.destination=a;b.durationSelector= +d;b._leading=e;b._trailing=f;b._hasValue=!1;return b}h(a,c);a.prototype._next=function(a){this._hasValue=!0;this._sendValue=a;this._throttled||(this._leading?this.send():this.throttle(a))};a.prototype.send=function(){var a=this._sendValue;this._hasValue&&(this.destination.next(a),this.throttle(a));this._hasValue=!1;this._sendValue=null};a.prototype.throttle=function(a){(a=this.tryDurationSelector(a))&&this.add(this._throttled=p(this,a))};a.prototype.tryDurationSelector=function(a){try{return this.durationSelector(a)}catch(d){return this.destination.error(d), +null}};a.prototype.throttlingDone=function(){var a=this._throttled,c=this._trailing;a&&a.unsubscribe();this._throttled=null;c&&this.send()};a.prototype.notifyNext=function(a,c,e,f,g){this.throttlingDone()};a.prototype.notifyComplete=function(){this.throttlingDone()};return a}(q),df=function(){function c(a,b,c,e){this.duration=a;this.scheduler=b;this.leading=c;this.trailing=e}c.prototype.call=function(a,b){return b.subscribe(new cf(a,this.duration,this.scheduler,this.leading,this.trailing))};return c}(), +cf=function(c){function a(a,d,e,f,g){a=c.call(this,a)||this;a.duration=d;a.scheduler=e;a.leading=f;a.trailing=g;a._hasTrailingValue=!1;a._trailingValue=null;return a}h(a,c);a.prototype._next=function(a){this.throttled?this.trailing&&(this._trailingValue=a,this._hasTrailingValue=!0):(this.add(this.throttled=this.scheduler.schedule(Ac,this.duration,{subscriber:this})),this.leading?this.destination.next(a):this.trailing&&(this._trailingValue=a,this._hasTrailingValue=!0))};a.prototype._complete=function(){this._hasTrailingValue&& +this.destination.next(this._trailingValue);this.destination.complete()};a.prototype.clearThrottle=function(){var a=this.throttled;a&&(this.trailing&&this._hasTrailingValue&&(this.destination.next(this._trailingValue),this._trailingValue=null,this._hasTrailingValue=!1),a.unsubscribe(),this.remove(a),this.throttled=null)};return a}(m),ef=function(){return function(c,a){this.value=c;this.interval=a}}(),Bc=function(){function c(a,b,c,e){this.waitFor=a;this.absoluteTimeout=b;this.withObservable=c;this.scheduler= +e}c.prototype.call=function(a,b){return b.subscribe(new ff(a,this.absoluteTimeout,this.waitFor,this.withObservable,this.scheduler))};return c}(),ff=function(c){function a(a,d,e,f,g){a=c.call(this,a)||this;a.absoluteTimeout=d;a.waitFor=e;a.withObservable=f;a.scheduler=g;a.action=null;a.scheduleTimeout();return a}h(a,c);a.dispatchTimeout=function(a){var b=a.withObservable;a._unsubscribeAndRecycle();a.add(p(a,b))};a.prototype.scheduleTimeout=function(){var b=this.action;b?this.action=b.schedule(this, +this.waitFor):this.add(this.action=this.scheduler.schedule(a.dispatchTimeout,this.waitFor,this))};a.prototype._next=function(a){this.absoluteTimeout||this.scheduleTimeout();c.prototype._next.call(this,a)};a.prototype._unsubscribe=function(){this.withObservable=this.scheduler=this.action=null};return a}(q),gf=function(){return function(c,a){this.value=c;this.timestamp=a}}(),jf=function(){function c(a){this.windowBoundaries=a}c.prototype.call=function(a,b){a=new hf(a);b=b.subscribe(a);b.closed||a.add(p(a, +this.windowBoundaries));return b};return c}(),hf=function(c){function a(a){var b=c.call(this,a)||this;b.window=new v;a.next(b.window);return b}h(a,c);a.prototype.notifyNext=function(a,c,e,f,g){this.openWindow()};a.prototype.notifyError=function(a,c){this._error(a)};a.prototype.notifyComplete=function(a){this._complete()};a.prototype._next=function(a){this.window.next(a)};a.prototype._error=function(a){this.window.error(a);this.destination.error(a)};a.prototype._complete=function(){this.window.complete(); +this.destination.complete()};a.prototype._unsubscribe=function(){this.window=null};a.prototype.openWindow=function(){var a=this.window;a&&a.complete();var a=this.destination,c=this.window=new v;a.next(c)};return a}(q),lf=function(){function c(a,b){this.windowSize=a;this.startWindowEvery=b}c.prototype.call=function(a,b){return b.subscribe(new kf(a,this.windowSize,this.startWindowEvery))};return c}(),kf=function(c){function a(a,d,e){var b=c.call(this,a)||this;b.destination=a;b.windowSize=d;b.startWindowEvery= +e;b.windows=[new v];b.count=0;a.next(b.windows[0]);return b}h(a,c);a.prototype._next=function(a){for(var b=0=this.maxWindowSize&&this.closeWindow(g))}};a.prototype._error=function(a){for(var b= +this.windows;0c)throw new K;var b=2<=arguments.length;return function(d){return d.pipe(I(function(a,b){return b===c}),Ca(1),b?ba(a):ka(function(){return new K}))}},endWith:function(){for(var c=[],a=0;a(a||0)?Number.POSITIVE_INFINITY:a;return function(d){return d.lift(new ae(c,a,b))}},filter:I,finalize:function(c){return function(a){return a.lift(new ce(c))}},find:function(c,a){if("function"!==typeof c)throw new TypeError("predicate is not a function");return function(b){return b.lift(new Eb(c,b,!1,a))}},findIndex:function(c, +a){return function(b){return b.lift(new Eb(c,b,!0,a))}},first:function(c,a){var b=2<=arguments.length;return function(d){return d.pipe(c?I(function(a,b){return c(a,b,d)}):J,Ca(1),b?ba(a):ka(function(){return new ca}))}},groupBy:function(c,a,b,d){return function(e){return e.lift(new Qc(c,a,b,d))}},ignoreElements:function(){return function(c){return c.lift(new fe)}},isEmpty:function(){return function(c){return c.lift(new he)}},last:function(c,a){var b=2<=arguments.length;return function(d){return d.pipe(c? +I(function(a,b){return c(a,b,d)}):J,la(1),b?ba(a):ka(function(){return new ca}))}},map:B,mapTo:function(c){return function(a){return a.lift(new ke(c))}},materialize:function(){return function(c){return c.lift(new me)}},max:function(c){return na("function"===typeof c?function(a,b){return 0b?a:b})},merge:function(){for(var c=[],a=0;ac(a,b)?a:b}:function(a,b){return ac?a.lift(new Fb(-1,a)):a.lift(new Fb(c-1,a))}},repeatWhen:function(c){return function(a){return a.lift(new we(c))}},retry:function(c){void 0===c&&(c=-1);return function(a){return a.lift(new ye(c,a))}},retryWhen:function(c){return function(a){return a.lift(new Ae(c,a))}},refCount:va,sample:function(c){return function(a){return a.lift(new Ce(c))}},sampleTime:function(c, +a){void 0===a&&(a=y);return function(b){return b.lift(new Ee(c,a))}},scan:ma,sequenceEqual:function(c,a){return function(b){return b.lift(new Ge(c,a))}},share:function(){return function(c){return va()(N(xc)(c))}},shareReplay:function(c,a,b){var d;d=c&&"object"===typeof c?c:{bufferSize:c,windowTime:a,refCount:!1,scheduler:b};return function(a){return a.lift(yc(d))}},single:function(c){return function(a){return a.lift(new Je(c,a))}},skip:function(c){return function(a){return a.lift(new Le(c))}},skipLast:function(c){return function(a){return a.lift(new Ne(c))}}, +skipUntil:function(c){return function(a){return a.lift(new Pe(c))}},skipWhile:function(c){return function(a){return a.lift(new Re(c))}},startWith:function(){for(var c=[],a=0;ak?new ga(h):new ga(h,k)};a.parseMarbles=function(a,c,e,f,g){var b=this;void 0===f&&(f=!1);void 0===g&&(g=!1);if(-1!==a.indexOf("!"))throw Error('conventional marble diagrams cannot have the unsubscription marker "!"');for(var d=a.length,h=[],k=g?a.replace(/^[ ]+/,"").indexOf("^"):a.indexOf("^"),m=-1===k?0:k*-this.frameTimeFactor,n="object"!==typeof c?function(a){return a}:function(a){return f&&c[a]instanceof Ka?c[a].messages:c[a]},p=-1,k=function(c){var d= +m,f=function(a){d+=a*b.frameTimeFactor},l=void 0,k=a[c];switch(k){case " ":g||f(1);break;case "-":f(1);break;case "(":p=m;f(1);break;case ")":p=-1;f(1);break;case "|":l=w.createComplete();f(1);break;case "^":f(1);break;case "#":l=w.createError(e||"error");f(1);break;default:if(g&&k.match(/^[0-9]$/)&&(0===c||" "===a[c-1])){var u=a.slice(c).match(/^([0-9]+(?:\.[0-9]+)?)(ms|s|m) /);if(u){c+=u[0].length-1;var k=parseFloat(u[1]),r=void 0;switch(u[2]){case "ms":r=k;break;case "s":r=1E3*k;break;case "m":r= +6E4*k}f(r/q.frameTimeFactor);break}}l=w.createNext(n(k));f(1)}l&&h.push({frame:-1d;d++)try{b=c[d];new z.ActiveXObject(b);break}catch(r){}a=new z.ActiveXObject(b)}catch(r){throw Error("XMLHttpRequest is not supported by your browser"); +}}return a},crossDomain:!0,withCredentials:!1,headers:{},method:"GET",responseType:"json",timeout:0};if("string"===typeof a)e.url=a;else for(var f in a)a.hasOwnProperty(f)&&(e[f]=a[f]);b.request=e;return b}h(a,c);a.prototype._subscribe=function(a){return new Bf(a,this.request)};a.create=function(){var b=function(b){return new a(b)};b.get=Fc;b.post=Gc;b.delete=Hc;b.put=Ic;b.patch=Jc;b.getJSON=Kc;return b}();return a}(n),Bf=function(c){function a(a,d){a=c.call(this,a)||this;a.request=d;a.done=!1;var b= +d.headers=d.headers||{};d.crossDomain||a.getHeader(b,"X-Requested-With")||(b["X-Requested-With"]="XMLHttpRequest");a.getHeader(b,"Content-Type")||z.FormData&&d.body instanceof z.FormData||"undefined"===typeof d.body||(b["Content-Type"]="application/x-www-form-urlencoded; charset\x3dUTF-8");d.body=a.serializeBody(d.body,a.getHeader(d.headers,"Content-Type"));a.send();return a}h(a,c);a.prototype.next=function(a){this.done=!0;var b=this.xhr,c=this.request,f=this.destination,g;try{g=new Jb(a,b,c)}catch(l){return f.error(l)}f.next(g)}; +a.prototype.send=function(){var a=this.request,c=this.request,e=c.user,f=c.method,g=c.url,h=c.async,k=c.password,m=c.headers,c=c.body;try{var r=this.xhr=a.createXHR();this.setupEvents(r,a);e?r.open(f,g,h,e,k):r.open(f,g,h);h&&(r.timeout=a.timeout,r.responseType=a.responseType);"withCredentials"in r&&(r.withCredentials=!!a.withCredentials);this.setHeaders(r,m);c?r.send(c):r.send()}catch(Zb){this.error(Zb)}};a.prototype.serializeBody=function(a,c){if(!a||"string"===typeof a||z.FormData&&a instanceof +z.FormData)return a;if(c){var b=c.indexOf(";");-1!==b&&(c=c.substring(0,b))}switch(c){case "application/x-www-form-urlencoded":return Object.keys(a).map(function(b){return encodeURIComponent(b)+"\x3d"+encodeURIComponent(a[b])}).join("\x26");case "application/json":return JSON.stringify(a);default:return a}};a.prototype.setHeaders=function(a,c){for(var b in c)c.hasOwnProperty(b)&&a.setRequestHeader(b,c[b])};a.prototype.getHeader=function(a,c){for(var b in a)if(b.toLowerCase()===c.toLowerCase())return a[b]}; +a.prototype.setupEvents=function(a,c){function b(a){var c=b.subscriber,d=b.progressSubscriber,e=b.request;d&&d.error(a);var f;try{f=new Kb(this,e)}catch(La){f=La}c.error(f)}function d(a){}function g(a){var b=g.subscriber,c=g.progressSubscriber,d=g.request;if(4===this.readyState){var e=1223===this.status?204:this.status,f="text"===this.responseType?this.response||this.responseText:this.response;0===e&&(e=f?200:0);if(400>e)c&&c.complete(),b.next(a),b.complete();else{c&&c.error(a);a=void 0;try{a=new ra("ajax error "+ +e,this,d)}catch(wf){a=wf}b.error(a)}}}var h=c.progressSubscriber;a.ontimeout=b;b.request=c;b.subscriber=this;b.progressSubscriber=h;if(a.upload&&"withCredentials"in a){if(h){var k;k=function(a){k.progressSubscriber.next(a)};z.XDomainRequest?a.onprogress=k:a.upload.onprogress=k;k.progressSubscriber=h}var m;m=function(a){var b=m.progressSubscriber,c=m.subscriber,d=m.request;b&&b.error(a);var e;try{e=new ra("ajax error",this,d)}catch(La){e=La}c.error(e)};a.onerror=m;m.request=c;m.subscriber=this;m.progressSubscriber= +h}a.onreadystatechange=d;d.subscriber=this;d.progressSubscriber=h;d.request=c;a.onload=g;g.subscriber=this;g.progressSubscriber=h;g.request=c};a.prototype.unsubscribe=function(){var a=this.xhr;!this.done&&a&&4!==a.readyState&&"function"===typeof a.abort&&a.abort();c.prototype.unsubscribe.call(this)};return a}(m),Jb=function(){return function(c,a,b){this.originalEvent=c;this.xhr=a;this.request=b;this.status=a.status;this.responseType=a.responseType||b.responseType;this.response=rb(this.responseType, +a)}}();qb.prototype=Object.create(Error.prototype);var ra=qb,Kb=function(c,a){ra.call(this,"ajax timeout",c,a);this.name="AjaxTimeoutError";return this},Cf=Object.freeze({ajax:O.create,AjaxResponse:Jb,AjaxError:ra,AjaxTimeoutError:Kb}),Df={url:"",deserializer:function(c){return JSON.parse(c.data)},serializer:function(c){return JSON.stringify(c)}},Lb=function(c){function a(a,d){var b=c.call(this)||this;if(a instanceof n)b.destination=d,b.source=a;else{d=b._config=Mc({},Df);b._output=new v;if("string"=== +typeof a)d.url=a;else for(var f in a)a.hasOwnProperty(f)&&(d[f]=a[f]);if(!d.WebSocketCtor&&WebSocket)d.WebSocketCtor=WebSocket;else if(!d.WebSocketCtor)throw Error("no WebSocket constructor can be found");b.destination=new X}return b}h(a,c);a.prototype.lift=function(b){var c=new a(this._config,this.destination);c.operator=b;c.source=this;return c};a.prototype._resetState=function(){this._socket=null;this.source||(this.destination=new X);this._output=new v};a.prototype.multiplex=function(a,c,e){var b= +this;return new n(function(d){try{b.next(a())}catch(u){d.error(u)}var f=b.subscribe(function(a){try{e(a)&&d.next(a)}catch(L){d.error(L)}},function(a){return d.error(a)},function(){return d.complete()});return function(){try{b.next(c())}catch(u){d.error(u)}f.unsubscribe()}})};a.prototype._connectSocket=function(){var a=this,c=this._config,e=c.WebSocketCtor,f=c.protocol,g=c.url,c=c.binaryType,h=this._output,k=null;try{this._socket=k=f?new e(g,f):new e(g),c&&(this._socket.binaryType=c)}catch(r){h.error(r); +return}var n=new t(function(){a._socket=null;k&&1===k.readyState&&k.close()});k.onopen=function(b){if(a._socket){var c=a._config.openObserver;c&&c.next(b);b=a.destination;a.destination=m.create(function(b){if(1===k.readyState)try{var c=a._config.serializer;k.send(c(b))}catch(ac){a.destination.error(ac)}},function(b){var c=a._config.closingObserver;c&&c.next(void 0);b&&b.code?k.close(b.code,b.reason):h.error(new TypeError("WebSocketSubject.error must be called with an object with an error code, and an optional reason: { code: number, reason: string }")); +a._resetState()},function(){var b=a._config.closingObserver;b&&b.next(void 0);k.close();a._resetState()});b&&b instanceof X&&n.add(b.subscribe(a.destination))}else k.close(),a._resetState()};k.onerror=function(b){a._resetState();h.error(b)};k.onclose=function(b){a._resetState();var c=a._config.closeObserver;c&&c.next(b);b.wasClean?h.complete():h.error(b)};k.onmessage=function(b){try{var c=a._config.deserializer;h.next(c(b))}catch($b){h.error($b)}}};a.prototype._subscribe=function(a){var b=this,c= +this.source;if(c)return c.subscribe(a);this._socket||this._connectSocket();this._output.subscribe(a);a.add(function(){var a=b._socket;0===b._output.observers.length&&(a&&1===a.readyState&&a.close(),b._resetState())});return a};a.prototype.unsubscribe=function(){var a=this._socket;a&&1===a.readyState&&a.close();this._resetState();c.prototype.unsubscribe.call(this)};return a}(Ea),Ef=Object.freeze({webSocket:function(c){return new Lb(c)},WebSocketSubject:Lb}),Ff=Object.freeze({fromFetch:function(c,a){return new n(function(b){var d= +new AbortController,e=d.signal,f=!0,g=!1;a?(a.signal&&a.signal.addEventListener("abort",function(){e.aborted||d.abort()}),a.signal=e):a={signal:e};fetch(c,a).then(function(a){f=!1;b.next(a);b.complete()}).catch(function(a){f=!1;g||b.error(a)});return function(){g=!0;f&&d.abort()}})}});k.operators=vf;k.testing=yf;k.ajax=Cf;k.webSocket=Ef;k.fetch=Ff;k.Observable=n;k.ConnectableObservable=vb;k.GroupedObservable=Fa;k.observable=V;k.Subject=v;k.BehaviorSubject=wb;k.ReplaySubject=X;k.AsyncSubject=U;k.asapScheduler= +qa;k.asyncScheduler=y;k.queueScheduler=xb;k.animationFrameScheduler=$c;k.VirtualTimeScheduler=Ab;k.VirtualAction=Ia;k.Scheduler=Ga;k.Subscription=t;k.Subscriber=m;k.Notification=w;k.pipe=ua;k.noop=D;k.identity=J;k.isObservable=function(c){return!!c&&(c instanceof n||"function"===typeof c.lift&&"function"===typeof c.subscribe)};k.ArgumentOutOfRangeError=K;k.EmptyError=ca;k.ObjectUnsubscribedError=E;k.UnsubscriptionError=Y;k.TimeoutError=ya;k.bindCallback=Sa;k.bindNodeCallback=Ta;k.combineLatest=function(){for(var c= +[],a=0;ac)c=0;a&&"function"===typeof a.schedule||(a=y);return new n(function(b){b.add(a.schedule(cc,c,{subscriber:b,counter:0,period:c}));return b})};k.merge= +bb;k.never=function(){return Cb};k.of=ha;k.onErrorResumeNext=Ba;k.pairs=function(c,a){return a?new n(function(b){var d=Object.keys(c),e=new t;e.add(a.schedule(dc,0,{keys:d,index:0,subscriber:b,subscription:e,obj:c}));return e}):new n(function(a){for(var b=Object.keys(c),e=0;e=a){d.complete();break}d.next(f++);if(d.closed)break}while(1)})};k.throwError=xa;k.timer=eb;k.using=function(c,a){return new n(function(b){var d;try{d=c()}catch(g){b.error(g);return}var e;try{e=a(d)}catch(g){b.error(g);return}var f=(e?G(e):T).subscribe(b);return function(){f.unsubscribe();d&&d.unsubscribe()}})};k.zip=fb;k.scheduled=Wa;k.EMPTY=T;k.NEVER=Cb;k.config= +C;Object.defineProperty(k,"__esModule",{value:!0})}); //# sourceMappingURL=rxjs.umd.min.js.map diff --git a/tools/node_modules/eslint/node_modules/rxjs/fetch/index.js b/tools/node_modules/eslint/node_modules/rxjs/fetch/index.js new file mode 100644 index 00000000000000..ca5d62f1a3dd60 --- /dev/null +++ b/tools/node_modules/eslint/node_modules/rxjs/fetch/index.js @@ -0,0 +1,5 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var fetch_1 = require("../internal/observable/dom/fetch"); +exports.fromFetch = fetch_1.fromFetch; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/rxjs/index.js b/tools/node_modules/eslint/node_modules/rxjs/index.js index f6d4852ff54d52..042b7e6e719a16 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/index.js +++ b/tools/node_modules/eslint/node_modules/rxjs/index.js @@ -35,6 +35,7 @@ var Subscriber_1 = require("./internal/Subscriber"); exports.Subscriber = Subscriber_1.Subscriber; var Notification_1 = require("./internal/Notification"); exports.Notification = Notification_1.Notification; +exports.NotificationKind = Notification_1.NotificationKind; var pipe_1 = require("./internal/util/pipe"); exports.pipe = pipe_1.pipe; var noop_1 = require("./internal/util/noop"); @@ -89,6 +90,8 @@ var onErrorResumeNext_1 = require("./internal/observable/onErrorResumeNext"); exports.onErrorResumeNext = onErrorResumeNext_1.onErrorResumeNext; var pairs_1 = require("./internal/observable/pairs"); exports.pairs = pairs_1.pairs; +var partition_1 = require("./internal/observable/partition"); +exports.partition = partition_1.partition; var race_1 = require("./internal/observable/race"); exports.race = race_1.race; var range_1 = require("./internal/observable/range"); @@ -101,6 +104,8 @@ var using_1 = require("./internal/observable/using"); exports.using = using_1.using; var zip_1 = require("./internal/observable/zip"); exports.zip = zip_1.zip; +var scheduled_1 = require("./internal/scheduled/scheduled"); +exports.scheduled = scheduled_1.scheduled; var empty_2 = require("./internal/observable/empty"); exports.EMPTY = empty_2.EMPTY; var never_2 = require("./internal/observable/never"); diff --git a/tools/node_modules/eslint/node_modules/rxjs/internal/Notification.js b/tools/node_modules/eslint/node_modules/rxjs/internal/Notification.js index fdd6c74933ee24..dc3eeb68968547 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/internal/Notification.js +++ b/tools/node_modules/eslint/node_modules/rxjs/internal/Notification.js @@ -14,26 +14,26 @@ var Notification = (function () { this.kind = kind; this.value = value; this.error = error; - this.hasValue = kind === "N"; + this.hasValue = kind === 'N'; } Notification.prototype.observe = function (observer) { switch (this.kind) { - case "N": + case 'N': return observer.next && observer.next(this.value); - case "E": + case 'E': return observer.error && observer.error(this.error); - case "C": + case 'C': return observer.complete && observer.complete(); } }; Notification.prototype.do = function (next, error, complete) { var kind = this.kind; switch (kind) { - case "N": + case 'N': return next && next(this.value); - case "E": + case 'E': return error && error(this.error); - case "C": + case 'C': return complete && complete(); } }; @@ -48,29 +48,29 @@ var Notification = (function () { Notification.prototype.toObservable = function () { var kind = this.kind; switch (kind) { - case "N": + case 'N': return of_1.of(this.value); - case "E": + case 'E': return throwError_1.throwError(this.error); - case "C": + case 'C': return empty_1.empty(); } throw new Error('unexpected notification kind value'); }; Notification.createNext = function (value) { if (typeof value !== 'undefined') { - return new Notification("N", value); + return new Notification('N', value); } return Notification.undefinedValueNotification; }; Notification.createError = function (err) { - return new Notification("E", undefined, err); + return new Notification('E', undefined, err); }; Notification.createComplete = function () { return Notification.completeNotification; }; - Notification.completeNotification = new Notification("C"); - Notification.undefinedValueNotification = new Notification("N", undefined); + Notification.completeNotification = new Notification('C'); + Notification.undefinedValueNotification = new Notification('N', undefined); return Notification; }()); exports.Notification = Notification; diff --git a/tools/node_modules/eslint/node_modules/rxjs/internal/Observable.js b/tools/node_modules/eslint/node_modules/rxjs/internal/Observable.js index 7764db0c87aae0..780998b85774f0 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/internal/Observable.js +++ b/tools/node_modules/eslint/node_modules/rxjs/internal/Observable.js @@ -2,7 +2,7 @@ Object.defineProperty(exports, "__esModule", { value: true }); var canReportError_1 = require("./util/canReportError"); var toSubscriber_1 = require("./util/toSubscriber"); -var observable_1 = require("../internal/symbol/observable"); +var observable_1 = require("./symbol/observable"); var pipe_1 = require("./util/pipe"); var config_1 = require("./config"); var Observable = (function () { diff --git a/tools/node_modules/eslint/node_modules/rxjs/internal/Subscriber.js b/tools/node_modules/eslint/node_modules/rxjs/internal/Subscriber.js index 607b7055c9d211..08a57fd69940a1 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/internal/Subscriber.js +++ b/tools/node_modules/eslint/node_modules/rxjs/internal/Subscriber.js @@ -97,14 +97,12 @@ var Subscriber = (function (_super) { this.unsubscribe(); }; Subscriber.prototype._unsubscribeAndRecycle = function () { - var _a = this, _parent = _a._parent, _parents = _a._parents; - this._parent = null; - this._parents = null; + var _parentOrParents = this._parentOrParents; + this._parentOrParents = null; this.unsubscribe(); this.closed = false; this.isStopped = false; - this._parent = _parent; - this._parents = _parents; + this._parentOrParents = _parentOrParents; return this; }; return Subscriber; diff --git a/tools/node_modules/eslint/node_modules/rxjs/internal/Subscription.js b/tools/node_modules/eslint/node_modules/rxjs/internal/Subscription.js index 8902082e744e5f..d2d68a5a45f1e5 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/internal/Subscription.js +++ b/tools/node_modules/eslint/node_modules/rxjs/internal/Subscription.js @@ -7,42 +7,41 @@ var UnsubscriptionError_1 = require("./util/UnsubscriptionError"); var Subscription = (function () { function Subscription(unsubscribe) { this.closed = false; - this._parent = null; - this._parents = null; + this._parentOrParents = null; this._subscriptions = null; if (unsubscribe) { this._unsubscribe = unsubscribe; } } Subscription.prototype.unsubscribe = function () { - var hasErrors = false; var errors; if (this.closed) { return; } - var _a = this, _parent = _a._parent, _parents = _a._parents, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions; + var _a = this, _parentOrParents = _a._parentOrParents, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions; this.closed = true; - this._parent = null; - this._parents = null; + this._parentOrParents = null; this._subscriptions = null; - var index = -1; - var len = _parents ? _parents.length : 0; - while (_parent) { - _parent.remove(this); - _parent = ++index < len && _parents[index] || null; + if (_parentOrParents instanceof Subscription) { + _parentOrParents.remove(this); + } + else if (_parentOrParents !== null) { + for (var index = 0; index < _parentOrParents.length; ++index) { + var parent_1 = _parentOrParents[index]; + parent_1.remove(this); + } } if (isFunction_1.isFunction(_unsubscribe)) { try { _unsubscribe.call(this); } catch (e) { - hasErrors = true; errors = e instanceof UnsubscriptionError_1.UnsubscriptionError ? flattenUnsubscriptionErrors(e.errors) : [e]; } } if (isArray_1.isArray(_subscriptions)) { - index = -1; - len = _subscriptions.length; + var index = -1; + var len = _subscriptions.length; while (++index < len) { var sub = _subscriptions[index]; if (isObject_1.isObject(sub)) { @@ -50,7 +49,6 @@ var Subscription = (function () { sub.unsubscribe(); } catch (e) { - hasErrors = true; errors = errors || []; if (e instanceof UnsubscriptionError_1.UnsubscriptionError) { errors = errors.concat(flattenUnsubscriptionErrors(e.errors)); @@ -62,12 +60,15 @@ var Subscription = (function () { } } } - if (hasErrors) { + if (errors) { throw new UnsubscriptionError_1.UnsubscriptionError(errors); } }; Subscription.prototype.add = function (teardown) { var subscription = teardown; + if (!teardown) { + return Subscription.EMPTY; + } switch (typeof teardown) { case 'function': subscription = new Subscription(teardown); @@ -86,20 +87,31 @@ var Subscription = (function () { } break; default: { - if (!teardown) { - return Subscription.EMPTY; - } throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.'); } } - if (subscription._addParent(this)) { - var subscriptions = this._subscriptions; - if (subscriptions) { - subscriptions.push(subscription); - } - else { - this._subscriptions = [subscription]; + var _parentOrParents = subscription._parentOrParents; + if (_parentOrParents === null) { + subscription._parentOrParents = this; + } + else if (_parentOrParents instanceof Subscription) { + if (_parentOrParents === this) { + return subscription; } + subscription._parentOrParents = [_parentOrParents, this]; + } + else if (_parentOrParents.indexOf(this) === -1) { + _parentOrParents.push(this); + } + else { + return subscription; + } + var subscriptions = this._subscriptions; + if (subscriptions === null) { + this._subscriptions = [subscription]; + } + else { + subscriptions.push(subscription); } return subscription; }; @@ -112,25 +124,6 @@ var Subscription = (function () { } } }; - Subscription.prototype._addParent = function (parent) { - var _a = this, _parent = _a._parent, _parents = _a._parents; - if (_parent === parent) { - return false; - } - else if (!_parent) { - this._parent = parent; - return true; - } - else if (!_parents) { - this._parents = [parent]; - return true; - } - else if (_parents.indexOf(parent) === -1) { - _parents.push(parent); - return true; - } - return false; - }; Subscription.EMPTY = (function (empty) { empty.closed = true; return empty; diff --git a/tools/node_modules/eslint/node_modules/rxjs/internal/observable/ConnectableObservable.js b/tools/node_modules/eslint/node_modules/rxjs/internal/observable/ConnectableObservable.js index 668868bce0c073..8ffe3f2f1cbc6e 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/internal/observable/ConnectableObservable.js +++ b/tools/node_modules/eslint/node_modules/rxjs/internal/observable/ConnectableObservable.js @@ -49,9 +49,6 @@ var ConnectableObservable = (function (_super) { this._connection = null; connection = Subscription_1.Subscription.EMPTY; } - else { - this._connection = connection; - } } return connection; }; diff --git a/tools/node_modules/eslint/node_modules/rxjs/internal/observable/dom/fetch.js b/tools/node_modules/eslint/node_modules/rxjs/internal/observable/dom/fetch.js new file mode 100644 index 00000000000000..97a04d90f18ba2 --- /dev/null +++ b/tools/node_modules/eslint/node_modules/rxjs/internal/observable/dom/fetch.js @@ -0,0 +1,44 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var Observable_1 = require("../../Observable"); +function fromFetch(input, init) { + return new Observable_1.Observable(function (subscriber) { + var controller = new AbortController(); + var signal = controller.signal; + var outerSignalHandler; + var abortable = true; + var unsubscribed = false; + if (init) { + if (init.signal) { + outerSignalHandler = function () { + if (!signal.aborted) { + controller.abort(); + } + }; + init.signal.addEventListener('abort', outerSignalHandler); + } + init.signal = signal; + } + else { + init = { signal: signal }; + } + fetch(input, init).then(function (response) { + abortable = false; + subscriber.next(response); + subscriber.complete(); + }).catch(function (err) { + abortable = false; + if (!unsubscribed) { + subscriber.error(err); + } + }); + return function () { + unsubscribed = true; + if (abortable) { + controller.abort(); + } + }; + }); +} +exports.fromFetch = fromFetch; +//# sourceMappingURL=fetch.js.map \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/rxjs/internal/observable/empty.js b/tools/node_modules/eslint/node_modules/rxjs/internal/observable/empty.js index 401f0759f0ef6b..cfa90b64264bed 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/internal/observable/empty.js +++ b/tools/node_modules/eslint/node_modules/rxjs/internal/observable/empty.js @@ -9,5 +9,4 @@ exports.empty = empty; function emptyScheduled(scheduler) { return new Observable_1.Observable(function (subscriber) { return scheduler.schedule(function () { return subscriber.complete(); }); }); } -exports.emptyScheduled = emptyScheduled; //# sourceMappingURL=empty.js.map \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/rxjs/internal/observable/forkJoin.js b/tools/node_modules/eslint/node_modules/rxjs/internal/observable/forkJoin.js index c115df29be21b2..40870ad6c4c743 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/internal/observable/forkJoin.js +++ b/tools/node_modules/eslint/node_modules/rxjs/internal/observable/forkJoin.js @@ -1,88 +1,71 @@ "use strict"; -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - } - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); Object.defineProperty(exports, "__esModule", { value: true }); var Observable_1 = require("../Observable"); var isArray_1 = require("../util/isArray"); -var empty_1 = require("./empty"); -var subscribeToResult_1 = require("../util/subscribeToResult"); -var OuterSubscriber_1 = require("../OuterSubscriber"); var map_1 = require("../operators/map"); +var isObject_1 = require("../util/isObject"); +var from_1 = require("./from"); function forkJoin() { var sources = []; for (var _i = 0; _i < arguments.length; _i++) { sources[_i] = arguments[_i]; } - var resultSelector; - if (typeof sources[sources.length - 1] === 'function') { - resultSelector = sources.pop(); - } - if (sources.length === 1 && isArray_1.isArray(sources[0])) { - sources = sources[0]; - } - if (sources.length === 0) { - return empty_1.EMPTY; + if (sources.length === 1) { + var first_1 = sources[0]; + if (isArray_1.isArray(first_1)) { + return forkJoinInternal(first_1, null); + } + if (isObject_1.isObject(first_1) && Object.getPrototypeOf(first_1) === Object.prototype) { + var keys = Object.keys(first_1); + return forkJoinInternal(keys.map(function (key) { return first_1[key]; }), keys); + } } - if (resultSelector) { - return forkJoin(sources).pipe(map_1.map(function (args) { return resultSelector.apply(void 0, args); })); + if (typeof sources[sources.length - 1] === 'function') { + var resultSelector_1 = sources.pop(); + sources = (sources.length === 1 && isArray_1.isArray(sources[0])) ? sources[0] : sources; + return forkJoinInternal(sources, null).pipe(map_1.map(function (args) { return resultSelector_1.apply(void 0, args); })); } - return new Observable_1.Observable(function (subscriber) { - return new ForkJoinSubscriber(subscriber, sources); - }); + return forkJoinInternal(sources, null); } exports.forkJoin = forkJoin; -var ForkJoinSubscriber = (function (_super) { - __extends(ForkJoinSubscriber, _super); - function ForkJoinSubscriber(destination, sources) { - var _this = _super.call(this, destination) || this; - _this.sources = sources; - _this.completed = 0; - _this.haveValues = 0; +function forkJoinInternal(sources, keys) { + return new Observable_1.Observable(function (subscriber) { var len = sources.length; - _this.values = new Array(len); - for (var i = 0; i < len; i++) { - var source = sources[i]; - var innerSubscription = subscribeToResult_1.subscribeToResult(_this, source, null, i); - if (innerSubscription) { - _this.add(innerSubscription); - } - } - return _this; - } - ForkJoinSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { - this.values[outerIndex] = innerValue; - if (!innerSub._hasValue) { - innerSub._hasValue = true; - this.haveValues++; - } - }; - ForkJoinSubscriber.prototype.notifyComplete = function (innerSub) { - var _a = this, destination = _a.destination, haveValues = _a.haveValues, values = _a.values; - var len = values.length; - if (!innerSub._hasValue) { - destination.complete(); + if (len === 0) { + subscriber.complete(); return; } - this.completed++; - if (this.completed !== len) { - return; - } - if (haveValues === len) { - destination.next(values); + var values = new Array(len); + var completed = 0; + var emitted = 0; + var _loop_1 = function (i) { + var source = from_1.from(sources[i]); + var hasValue = false; + subscriber.add(source.subscribe({ + next: function (value) { + if (!hasValue) { + hasValue = true; + emitted++; + } + values[i] = value; + }, + error: function (err) { return subscriber.error(err); }, + complete: function () { + completed++; + if (completed === len || !hasValue) { + if (emitted === len) { + subscriber.next(keys ? + keys.reduce(function (result, key, i) { return (result[key] = values[i], result); }, {}) : + values); + } + subscriber.complete(); + } + } + })); + }; + for (var i = 0; i < len; i++) { + _loop_1(i); } - destination.complete(); - }; - return ForkJoinSubscriber; -}(OuterSubscriber_1.OuterSubscriber)); + }); +} //# sourceMappingURL=forkJoin.js.map \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/rxjs/internal/observable/from.js b/tools/node_modules/eslint/node_modules/rxjs/internal/observable/from.js index a0d02d0ab30a30..4f6069f6245146 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/internal/observable/from.js +++ b/tools/node_modules/eslint/node_modules/rxjs/internal/observable/from.js @@ -1,15 +1,8 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var Observable_1 = require("../Observable"); -var isPromise_1 = require("../util/isPromise"); -var isArrayLike_1 = require("../util/isArrayLike"); -var isInteropObservable_1 = require("../util/isInteropObservable"); -var isIterable_1 = require("../util/isIterable"); -var fromArray_1 = require("./fromArray"); -var fromPromise_1 = require("./fromPromise"); -var fromIterable_1 = require("./fromIterable"); -var fromObservable_1 = require("./fromObservable"); var subscribeTo_1 = require("../util/subscribeTo"); +var scheduled_1 = require("../scheduled/scheduled"); function from(input, scheduler) { if (!scheduler) { if (input instanceof Observable_1.Observable) { @@ -17,21 +10,9 @@ function from(input, scheduler) { } return new Observable_1.Observable(subscribeTo_1.subscribeTo(input)); } - if (input != null) { - if (isInteropObservable_1.isInteropObservable(input)) { - return fromObservable_1.fromObservable(input, scheduler); - } - else if (isPromise_1.isPromise(input)) { - return fromPromise_1.fromPromise(input, scheduler); - } - else if (isArrayLike_1.isArrayLike(input)) { - return fromArray_1.fromArray(input, scheduler); - } - else if (isIterable_1.isIterable(input) || typeof input === 'string') { - return fromIterable_1.fromIterable(input, scheduler); - } + else { + return scheduled_1.scheduled(input, scheduler); } - throw new TypeError((input !== null && typeof input || input) + ' is not observable'); } exports.from = from; //# sourceMappingURL=from.js.map \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/rxjs/internal/observable/fromArray.js b/tools/node_modules/eslint/node_modules/rxjs/internal/observable/fromArray.js index 98ca7460c35069..545e58742f34a9 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/internal/observable/fromArray.js +++ b/tools/node_modules/eslint/node_modules/rxjs/internal/observable/fromArray.js @@ -1,28 +1,14 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var Observable_1 = require("../Observable"); -var Subscription_1 = require("../Subscription"); var subscribeToArray_1 = require("../util/subscribeToArray"); +var scheduleArray_1 = require("../scheduled/scheduleArray"); function fromArray(input, scheduler) { if (!scheduler) { return new Observable_1.Observable(subscribeToArray_1.subscribeToArray(input)); } else { - return new Observable_1.Observable(function (subscriber) { - var sub = new Subscription_1.Subscription(); - var i = 0; - sub.add(scheduler.schedule(function () { - if (i === input.length) { - subscriber.complete(); - return; - } - subscriber.next(input[i++]); - if (!subscriber.closed) { - sub.add(this.schedule()); - } - })); - return sub; - }); + return scheduleArray_1.scheduleArray(input, scheduler); } } exports.fromArray = fromArray; diff --git a/tools/node_modules/eslint/node_modules/rxjs/internal/observable/fromIterable.js b/tools/node_modules/eslint/node_modules/rxjs/internal/observable/fromIterable.js index 25766ba057cec8..8d319a47cbf73e 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/internal/observable/fromIterable.js +++ b/tools/node_modules/eslint/node_modules/rxjs/internal/observable/fromIterable.js @@ -1,9 +1,8 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var Observable_1 = require("../Observable"); -var Subscription_1 = require("../Subscription"); -var iterator_1 = require("../symbol/iterator"); var subscribeToIterable_1 = require("../util/subscribeToIterable"); +var scheduleIterable_1 = require("../scheduled/scheduleIterable"); function fromIterable(input, scheduler) { if (!input) { throw new Error('Iterable cannot be null'); @@ -12,42 +11,7 @@ function fromIterable(input, scheduler) { return new Observable_1.Observable(subscribeToIterable_1.subscribeToIterable(input)); } else { - return new Observable_1.Observable(function (subscriber) { - var sub = new Subscription_1.Subscription(); - var iterator; - sub.add(function () { - if (iterator && typeof iterator.return === 'function') { - iterator.return(); - } - }); - sub.add(scheduler.schedule(function () { - iterator = input[iterator_1.iterator](); - sub.add(scheduler.schedule(function () { - if (subscriber.closed) { - return; - } - var value; - var done; - try { - var result = iterator.next(); - value = result.value; - done = result.done; - } - catch (err) { - subscriber.error(err); - return; - } - if (done) { - subscriber.complete(); - } - else { - subscriber.next(value); - this.schedule(); - } - })); - })); - return sub; - }); + return scheduleIterable_1.scheduleIterable(input, scheduler); } } exports.fromIterable = fromIterable; diff --git a/tools/node_modules/eslint/node_modules/rxjs/internal/observable/fromObservable.js b/tools/node_modules/eslint/node_modules/rxjs/internal/observable/fromObservable.js deleted file mode 100644 index 1fc2396adce305..00000000000000 --- a/tools/node_modules/eslint/node_modules/rxjs/internal/observable/fromObservable.js +++ /dev/null @@ -1,27 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var Observable_1 = require("../Observable"); -var Subscription_1 = require("../Subscription"); -var observable_1 = require("../symbol/observable"); -var subscribeToObservable_1 = require("../util/subscribeToObservable"); -function fromObservable(input, scheduler) { - if (!scheduler) { - return new Observable_1.Observable(subscribeToObservable_1.subscribeToObservable(input)); - } - else { - return new Observable_1.Observable(function (subscriber) { - var sub = new Subscription_1.Subscription(); - sub.add(scheduler.schedule(function () { - var observable = input[observable_1.observable](); - sub.add(observable.subscribe({ - next: function (value) { sub.add(scheduler.schedule(function () { return subscriber.next(value); })); }, - error: function (err) { sub.add(scheduler.schedule(function () { return subscriber.error(err); })); }, - complete: function () { sub.add(scheduler.schedule(function () { return subscriber.complete(); })); }, - })); - })); - return sub; - }); - } -} -exports.fromObservable = fromObservable; -//# sourceMappingURL=fromObservable.js.map \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/rxjs/internal/observable/fromPromise.js b/tools/node_modules/eslint/node_modules/rxjs/internal/observable/fromPromise.js index 07763b9d755186..2d15d4ca66691c 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/internal/observable/fromPromise.js +++ b/tools/node_modules/eslint/node_modules/rxjs/internal/observable/fromPromise.js @@ -1,25 +1,14 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var Observable_1 = require("../Observable"); -var Subscription_1 = require("../Subscription"); var subscribeToPromise_1 = require("../util/subscribeToPromise"); +var schedulePromise_1 = require("../scheduled/schedulePromise"); function fromPromise(input, scheduler) { if (!scheduler) { return new Observable_1.Observable(subscribeToPromise_1.subscribeToPromise(input)); } else { - return new Observable_1.Observable(function (subscriber) { - var sub = new Subscription_1.Subscription(); - sub.add(scheduler.schedule(function () { return input.then(function (value) { - sub.add(scheduler.schedule(function () { - subscriber.next(value); - sub.add(scheduler.schedule(function () { return subscriber.complete(); })); - })); - }, function (err) { - sub.add(scheduler.schedule(function () { return subscriber.error(err); })); - }); })); - return sub; - }); + return schedulePromise_1.schedulePromise(input, scheduler); } } exports.fromPromise = fromPromise; diff --git a/tools/node_modules/eslint/node_modules/rxjs/internal/observable/of.js b/tools/node_modules/eslint/node_modules/rxjs/internal/observable/of.js index e48882edd2a206..05ab045bd48fb9 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/internal/observable/of.js +++ b/tools/node_modules/eslint/node_modules/rxjs/internal/observable/of.js @@ -2,8 +2,7 @@ Object.defineProperty(exports, "__esModule", { value: true }); var isScheduler_1 = require("../util/isScheduler"); var fromArray_1 = require("./fromArray"); -var empty_1 = require("./empty"); -var scalar_1 = require("./scalar"); +var scheduleArray_1 = require("../scheduled/scheduleArray"); function of() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { @@ -12,17 +11,10 @@ function of() { var scheduler = args[args.length - 1]; if (isScheduler_1.isScheduler(scheduler)) { args.pop(); + return scheduleArray_1.scheduleArray(args, scheduler); } else { - scheduler = undefined; - } - switch (args.length) { - case 0: - return empty_1.empty(scheduler); - case 1: - return scheduler ? fromArray_1.fromArray(args, scheduler) : scalar_1.scalar(args[0]); - default: - return fromArray_1.fromArray(args, scheduler); + return fromArray_1.fromArray(args); } } exports.of = of; diff --git a/tools/node_modules/eslint/node_modules/rxjs/internal/observable/partition.js b/tools/node_modules/eslint/node_modules/rxjs/internal/observable/partition.js new file mode 100644 index 00000000000000..dc33aff9d3669a --- /dev/null +++ b/tools/node_modules/eslint/node_modules/rxjs/internal/observable/partition.js @@ -0,0 +1,14 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var not_1 = require("../util/not"); +var subscribeTo_1 = require("../util/subscribeTo"); +var filter_1 = require("../operators/filter"); +var Observable_1 = require("../Observable"); +function partition(source, predicate, thisArg) { + return [ + filter_1.filter(predicate, thisArg)(new Observable_1.Observable(subscribeTo_1.subscribeTo(source))), + filter_1.filter(not_1.not(predicate, thisArg))(new Observable_1.Observable(subscribeTo_1.subscribeTo(source))) + ]; +} +exports.partition = partition; +//# sourceMappingURL=partition.js.map \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/rxjs/internal/observable/scalar.js b/tools/node_modules/eslint/node_modules/rxjs/internal/observable/scalar.js deleted file mode 100644 index 15c1f46e71338e..00000000000000 --- a/tools/node_modules/eslint/node_modules/rxjs/internal/observable/scalar.js +++ /dev/null @@ -1,14 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var Observable_1 = require("../Observable"); -function scalar(value) { - var result = new Observable_1.Observable(function (subscriber) { - subscriber.next(value); - subscriber.complete(); - }); - result._isScalar = true; - result.value = value; - return result; -} -exports.scalar = scalar; -//# sourceMappingURL=scalar.js.map \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/rxjs/internal/operators/endWith.js b/tools/node_modules/eslint/node_modules/rxjs/internal/operators/endWith.js index 602f8bdc4136a6..028bd4e6655783 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/internal/operators/endWith.js +++ b/tools/node_modules/eslint/node_modules/rxjs/internal/operators/endWith.js @@ -1,34 +1,13 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -var fromArray_1 = require("../observable/fromArray"); -var scalar_1 = require("../observable/scalar"); -var empty_1 = require("../observable/empty"); var concat_1 = require("../observable/concat"); -var isScheduler_1 = require("../util/isScheduler"); +var of_1 = require("../observable/of"); function endWith() { var array = []; for (var _i = 0; _i < arguments.length; _i++) { array[_i] = arguments[_i]; } - return function (source) { - var scheduler = array[array.length - 1]; - if (isScheduler_1.isScheduler(scheduler)) { - array.pop(); - } - else { - scheduler = null; - } - var len = array.length; - if (len === 1 && !scheduler) { - return concat_1.concat(source, scalar_1.scalar(array[0])); - } - else if (len > 0) { - return concat_1.concat(source, fromArray_1.fromArray(array, scheduler)); - } - else { - return concat_1.concat(source, empty_1.empty(scheduler)); - } - }; + return function (source) { return concat_1.concat(source, of_1.of.apply(void 0, array)); }; } exports.endWith = endWith; //# sourceMappingURL=endWith.js.map \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/rxjs/internal/operators/pairwise.js b/tools/node_modules/eslint/node_modules/rxjs/internal/operators/pairwise.js index 72484a66f445a4..1311dfef4288d9 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/internal/operators/pairwise.js +++ b/tools/node_modules/eslint/node_modules/rxjs/internal/operators/pairwise.js @@ -34,13 +34,17 @@ var PairwiseSubscriber = (function (_super) { return _this; } PairwiseSubscriber.prototype._next = function (value) { + var pair; if (this.hasPrev) { - this.destination.next([this.prev, value]); + pair = [this.prev, value]; } else { this.hasPrev = true; } this.prev = value; + if (pair) { + this.destination.next(pair); + } }; return PairwiseSubscriber; }(Subscriber_1.Subscriber)); diff --git a/tools/node_modules/eslint/node_modules/rxjs/internal/operators/startWith.js b/tools/node_modules/eslint/node_modules/rxjs/internal/operators/startWith.js index dda6719c84594b..fd72f0c6ff7c25 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/internal/operators/startWith.js +++ b/tools/node_modules/eslint/node_modules/rxjs/internal/operators/startWith.js @@ -1,8 +1,5 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -var fromArray_1 = require("../observable/fromArray"); -var scalar_1 = require("../observable/scalar"); -var empty_1 = require("../observable/empty"); var concat_1 = require("../observable/concat"); var isScheduler_1 = require("../util/isScheduler"); function startWith() { @@ -10,25 +7,14 @@ function startWith() { for (var _i = 0; _i < arguments.length; _i++) { array[_i] = arguments[_i]; } - return function (source) { - var scheduler = array[array.length - 1]; - if (isScheduler_1.isScheduler(scheduler)) { - array.pop(); - } - else { - scheduler = null; - } - var len = array.length; - if (len === 1 && !scheduler) { - return concat_1.concat(scalar_1.scalar(array[0]), source); - } - else if (len > 0) { - return concat_1.concat(fromArray_1.fromArray(array, scheduler), source); - } - else { - return concat_1.concat(empty_1.empty(scheduler), source); - } - }; + var scheduler = array[array.length - 1]; + if (isScheduler_1.isScheduler(scheduler)) { + array.pop(); + return function (source) { return concat_1.concat(array, source, scheduler); }; + } + else { + return function (source) { return concat_1.concat(array, source); }; + } } exports.startWith = startWith; //# sourceMappingURL=startWith.js.map \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/rxjs/internal/operators/throttleTime.js b/tools/node_modules/eslint/node_modules/rxjs/internal/operators/throttleTime.js index b8b734ca1b9bc4..156c44b9a9769d 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/internal/operators/throttleTime.js +++ b/tools/node_modules/eslint/node_modules/rxjs/internal/operators/throttleTime.js @@ -58,6 +58,10 @@ var ThrottleTimeSubscriber = (function (_super) { if (this.leading) { this.destination.next(value); } + else if (this.trailing) { + this._trailingValue = value; + this._hasTrailingValue = true; + } } }; ThrottleTimeSubscriber.prototype._complete = function () { diff --git a/tools/node_modules/eslint/node_modules/rxjs/internal/operators/throwIfEmpty.js b/tools/node_modules/eslint/node_modules/rxjs/internal/operators/throwIfEmpty.js index 6896351e16248e..7722c349bcb390 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/internal/operators/throwIfEmpty.js +++ b/tools/node_modules/eslint/node_modules/rxjs/internal/operators/throwIfEmpty.js @@ -1,19 +1,65 @@ "use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + } + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); Object.defineProperty(exports, "__esModule", { value: true }); -var tap_1 = require("./tap"); var EmptyError_1 = require("../util/EmptyError"); -exports.throwIfEmpty = function (errorFactory) { +var Subscriber_1 = require("../Subscriber"); +function throwIfEmpty(errorFactory) { if (errorFactory === void 0) { errorFactory = defaultErrorFactory; } - return tap_1.tap({ - hasValue: false, - next: function () { this.hasValue = true; }, - complete: function () { - if (!this.hasValue) { - throw errorFactory(); + return function (source) { + return source.lift(new ThrowIfEmptyOperator(errorFactory)); + }; +} +exports.throwIfEmpty = throwIfEmpty; +var ThrowIfEmptyOperator = (function () { + function ThrowIfEmptyOperator(errorFactory) { + this.errorFactory = errorFactory; + } + ThrowIfEmptyOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new ThrowIfEmptySubscriber(subscriber, this.errorFactory)); + }; + return ThrowIfEmptyOperator; +}()); +var ThrowIfEmptySubscriber = (function (_super) { + __extends(ThrowIfEmptySubscriber, _super); + function ThrowIfEmptySubscriber(destination, errorFactory) { + var _this = _super.call(this, destination) || this; + _this.errorFactory = errorFactory; + _this.hasValue = false; + return _this; + } + ThrowIfEmptySubscriber.prototype._next = function (value) { + this.hasValue = true; + this.destination.next(value); + }; + ThrowIfEmptySubscriber.prototype._complete = function () { + if (!this.hasValue) { + var err = void 0; + try { + err = this.errorFactory(); + } + catch (e) { + err = e; } + this.destination.error(err); + } + else { + return this.destination.complete(); } - }); -}; + }; + return ThrowIfEmptySubscriber; +}(Subscriber_1.Subscriber)); function defaultErrorFactory() { return new EmptyError_1.EmptyError(); } diff --git a/tools/node_modules/eslint/node_modules/rxjs/internal/scheduled/scheduleArray.js b/tools/node_modules/eslint/node_modules/rxjs/internal/scheduled/scheduleArray.js new file mode 100644 index 00000000000000..31938d2353322f --- /dev/null +++ b/tools/node_modules/eslint/node_modules/rxjs/internal/scheduled/scheduleArray.js @@ -0,0 +1,23 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var Observable_1 = require("../Observable"); +var Subscription_1 = require("../Subscription"); +function scheduleArray(input, scheduler) { + return new Observable_1.Observable(function (subscriber) { + var sub = new Subscription_1.Subscription(); + var i = 0; + sub.add(scheduler.schedule(function () { + if (i === input.length) { + subscriber.complete(); + return; + } + subscriber.next(input[i++]); + if (!subscriber.closed) { + sub.add(this.schedule()); + } + })); + return sub; + }); +} +exports.scheduleArray = scheduleArray; +//# sourceMappingURL=scheduleArray.js.map \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/rxjs/internal/scheduled/scheduleIterable.js b/tools/node_modules/eslint/node_modules/rxjs/internal/scheduled/scheduleIterable.js new file mode 100644 index 00000000000000..3cf6bc097c0c7b --- /dev/null +++ b/tools/node_modules/eslint/node_modules/rxjs/internal/scheduled/scheduleIterable.js @@ -0,0 +1,48 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var Observable_1 = require("../Observable"); +var Subscription_1 = require("../Subscription"); +var iterator_1 = require("../symbol/iterator"); +function scheduleIterable(input, scheduler) { + if (!input) { + throw new Error('Iterable cannot be null'); + } + return new Observable_1.Observable(function (subscriber) { + var sub = new Subscription_1.Subscription(); + var iterator; + sub.add(function () { + if (iterator && typeof iterator.return === 'function') { + iterator.return(); + } + }); + sub.add(scheduler.schedule(function () { + iterator = input[iterator_1.iterator](); + sub.add(scheduler.schedule(function () { + if (subscriber.closed) { + return; + } + var value; + var done; + try { + var result = iterator.next(); + value = result.value; + done = result.done; + } + catch (err) { + subscriber.error(err); + return; + } + if (done) { + subscriber.complete(); + } + else { + subscriber.next(value); + this.schedule(); + } + })); + })); + return sub; + }); +} +exports.scheduleIterable = scheduleIterable; +//# sourceMappingURL=scheduleIterable.js.map \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/rxjs/internal/scheduled/scheduleObservable.js b/tools/node_modules/eslint/node_modules/rxjs/internal/scheduled/scheduleObservable.js new file mode 100644 index 00000000000000..83e49c8a2f703e --- /dev/null +++ b/tools/node_modules/eslint/node_modules/rxjs/internal/scheduled/scheduleObservable.js @@ -0,0 +1,21 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var Observable_1 = require("../Observable"); +var Subscription_1 = require("../Subscription"); +var observable_1 = require("../symbol/observable"); +function scheduleObservable(input, scheduler) { + return new Observable_1.Observable(function (subscriber) { + var sub = new Subscription_1.Subscription(); + sub.add(scheduler.schedule(function () { + var observable = input[observable_1.observable](); + sub.add(observable.subscribe({ + next: function (value) { sub.add(scheduler.schedule(function () { return subscriber.next(value); })); }, + error: function (err) { sub.add(scheduler.schedule(function () { return subscriber.error(err); })); }, + complete: function () { sub.add(scheduler.schedule(function () { return subscriber.complete(); })); }, + })); + })); + return sub; + }); +} +exports.scheduleObservable = scheduleObservable; +//# sourceMappingURL=scheduleObservable.js.map \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/rxjs/internal/scheduled/schedulePromise.js b/tools/node_modules/eslint/node_modules/rxjs/internal/scheduled/schedulePromise.js new file mode 100644 index 00000000000000..826910d5dc37ef --- /dev/null +++ b/tools/node_modules/eslint/node_modules/rxjs/internal/scheduled/schedulePromise.js @@ -0,0 +1,20 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var Observable_1 = require("../Observable"); +var Subscription_1 = require("../Subscription"); +function schedulePromise(input, scheduler) { + return new Observable_1.Observable(function (subscriber) { + var sub = new Subscription_1.Subscription(); + sub.add(scheduler.schedule(function () { return input.then(function (value) { + sub.add(scheduler.schedule(function () { + subscriber.next(value); + sub.add(scheduler.schedule(function () { return subscriber.complete(); })); + })); + }, function (err) { + sub.add(scheduler.schedule(function () { return subscriber.error(err); })); + }); })); + return sub; + }); +} +exports.schedulePromise = schedulePromise; +//# sourceMappingURL=schedulePromise.js.map \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/rxjs/internal/scheduled/scheduled.js b/tools/node_modules/eslint/node_modules/rxjs/internal/scheduled/scheduled.js new file mode 100644 index 00000000000000..4fd1554a93a846 --- /dev/null +++ b/tools/node_modules/eslint/node_modules/rxjs/internal/scheduled/scheduled.js @@ -0,0 +1,29 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var scheduleObservable_1 = require("./scheduleObservable"); +var schedulePromise_1 = require("./schedulePromise"); +var scheduleArray_1 = require("./scheduleArray"); +var scheduleIterable_1 = require("./scheduleIterable"); +var isInteropObservable_1 = require("../util/isInteropObservable"); +var isPromise_1 = require("../util/isPromise"); +var isArrayLike_1 = require("../util/isArrayLike"); +var isIterable_1 = require("../util/isIterable"); +function scheduled(input, scheduler) { + if (input != null) { + if (isInteropObservable_1.isInteropObservable(input)) { + return scheduleObservable_1.scheduleObservable(input, scheduler); + } + else if (isPromise_1.isPromise(input)) { + return schedulePromise_1.schedulePromise(input, scheduler); + } + else if (isArrayLike_1.isArrayLike(input)) { + return scheduleArray_1.scheduleArray(input, scheduler); + } + else if (isIterable_1.isIterable(input) || typeof input === 'string') { + return scheduleIterable_1.scheduleIterable(input, scheduler); + } + } + throw new TypeError((input !== null && typeof input || input) + ' is not observable'); +} +exports.scheduled = scheduled; +//# sourceMappingURL=scheduled.js.map \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/rxjs/internal/util/hostReportError.js b/tools/node_modules/eslint/node_modules/rxjs/internal/util/hostReportError.js index ffc06b01f5f448..2fb7fa5accc4d0 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/internal/util/hostReportError.js +++ b/tools/node_modules/eslint/node_modules/rxjs/internal/util/hostReportError.js @@ -1,7 +1,7 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function hostReportError(err) { - setTimeout(function () { throw err; }); + setTimeout(function () { throw err; }, 0); } exports.hostReportError = hostReportError; //# sourceMappingURL=hostReportError.js.map \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/rxjs/internal/util/subscribeTo.js b/tools/node_modules/eslint/node_modules/rxjs/internal/util/subscribeTo.js index b1a0e6c123d2ac..b5ffb5764733ea 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/internal/util/subscribeTo.js +++ b/tools/node_modules/eslint/node_modules/rxjs/internal/util/subscribeTo.js @@ -1,6 +1,5 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -var Observable_1 = require("../Observable"); var subscribeToArray_1 = require("./subscribeToArray"); var subscribeToPromise_1 = require("./subscribeToPromise"); var subscribeToIterable_1 = require("./subscribeToIterable"); @@ -11,19 +10,7 @@ var isObject_1 = require("./isObject"); var iterator_1 = require("../symbol/iterator"); var observable_1 = require("../symbol/observable"); exports.subscribeTo = function (result) { - if (result instanceof Observable_1.Observable) { - return function (subscriber) { - if (result._isScalar) { - subscriber.next(result.value); - subscriber.complete(); - return undefined; - } - else { - return result.subscribe(subscriber); - } - }; - } - else if (!!result && typeof result[observable_1.observable] === 'function') { + if (!!result && typeof result[observable_1.observable] === 'function') { return subscribeToObservable_1.subscribeToObservable(result); } else if (isArrayLike_1.isArrayLike(result)) { diff --git a/tools/node_modules/eslint/node_modules/rxjs/internal/util/subscribeToArray.js b/tools/node_modules/eslint/node_modules/rxjs/internal/util/subscribeToArray.js index 381192a255740b..029c2327570bdb 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/internal/util/subscribeToArray.js +++ b/tools/node_modules/eslint/node_modules/rxjs/internal/util/subscribeToArray.js @@ -4,8 +4,6 @@ exports.subscribeToArray = function (array) { return function (subscriber) { for (var i = 0, len = array.length; i < len && !subscriber.closed; i++) { subscriber.next(array[i]); } - if (!subscriber.closed) { - subscriber.complete(); - } + subscriber.complete(); }; }; //# sourceMappingURL=subscribeToArray.js.map \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/rxjs/internal/util/subscribeToResult.js b/tools/node_modules/eslint/node_modules/rxjs/internal/util/subscribeToResult.js index a7950ce4e9af20..721d64049d4228 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/internal/util/subscribeToResult.js +++ b/tools/node_modules/eslint/node_modules/rxjs/internal/util/subscribeToResult.js @@ -2,10 +2,14 @@ Object.defineProperty(exports, "__esModule", { value: true }); var InnerSubscriber_1 = require("../InnerSubscriber"); var subscribeTo_1 = require("./subscribeTo"); +var Observable_1 = require("../Observable"); function subscribeToResult(outerSubscriber, result, outerValue, outerIndex, destination) { if (destination === void 0) { destination = new InnerSubscriber_1.InnerSubscriber(outerSubscriber, outerValue, outerIndex); } if (destination.closed) { - return; + return undefined; + } + if (result instanceof Observable_1.Observable) { + return result.subscribe(destination); } return subscribeTo_1.subscribeTo(result)(destination); } diff --git a/tools/node_modules/eslint/node_modules/rxjs/package.json b/tools/node_modules/eslint/node_modules/rxjs/package.json index fc352d891ab946..dd576ea6764e38 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/package.json +++ b/tools/node_modules/eslint/node_modules/rxjs/package.json @@ -66,6 +66,7 @@ "danger": "1.1.0", "dependency-cruiser": "2.13.0", "doctoc": "1.3.0", + "dtslint": "0.6.1", "escape-string-regexp": "1.0.5", "esdoc": "0.4.7", "eslint": "4.17.0", @@ -177,5 +178,5 @@ }, "sideEffects": false, "typings": "./index.d.ts", - "version": "6.4.0" + "version": "6.5.2" } \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/rxjs/src/BUILD.bazel b/tools/node_modules/eslint/node_modules/rxjs/src/BUILD.bazel deleted file mode 100644 index 75a58ae0bc4df4..00000000000000 --- a/tools/node_modules/eslint/node_modules/rxjs/src/BUILD.bazel +++ /dev/null @@ -1,43 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -exports_files(["tsconfig.json"]) - -load("@build_bazel_rules_typescript//:defs.bzl", "ts_library") - -ts_library( - name = "lib", - srcs = glob( - ["internal/**/*.ts"], - # exclude all backwards compatibility code because we don't have a bazel target setup for that - exclude = [ - "internal/Rx.ts", - "internal-compatibility/**", - "internal/patching/**", - "internal/umd.ts", - ], - ), - # Specify the compile-time dependencies to run the compilation (eg. typescript) - # The default value assumes that the end-user has a target //:node_modules - # but not all users do. - # This also makes the build more reproducible, in case the user's TypeScript - # version isn't compatible. - node_modules = "@build_bazel_rules_typescript_tsc_wrapped_deps//:node_modules", - tsconfig = "tsconfig.json", -) - -ts_library( - name = "rxjs", - srcs = ["index.ts"], - module_name = "rxjs", - module_root = "index.d.ts", - # See comment above - node_modules = "@build_bazel_rules_typescript_tsc_wrapped_deps//:node_modules", - tsconfig = "tsconfig.json", - deps = [ - ":lib", - "//ajax", - "//operators", - "//testing", - "//webSocket", - ], -) diff --git a/tools/node_modules/eslint/node_modules/rxjs/src/README.md b/tools/node_modules/eslint/node_modules/rxjs/src/README.md index df22c904342017..20e4d8bcba3f0e 100644 --- a/tools/node_modules/eslint/node_modules/rxjs/src/README.md +++ b/tools/node_modules/eslint/node_modules/rxjs/src/README.md @@ -27,7 +27,7 @@ Reactive Extensions Library for JavaScript. This is a rewrite of [Reactive-Exten - [Contribution Guidelines](CONTRIBUTING.md) - [Maintainer Guidelines](doc/maintainer-guidelines.md) - [Creating Operators](doc/operator-creation.md) -- [API Documentation (WIP)](https://rxjs-dev.firebaseapp.com/) +- [API Documentation (WIP)](https://rxjs.dev/) ## Versions In This Repository diff --git a/tools/node_modules/eslint/node_modules/rxjs/src/WORKSPACE b/tools/node_modules/eslint/node_modules/rxjs/src/WORKSPACE deleted file mode 100644 index 034c99e579fd2f..00000000000000 --- a/tools/node_modules/eslint/node_modules/rxjs/src/WORKSPACE +++ /dev/null @@ -1 +0,0 @@ -workspace(name = "rxjs") diff --git a/tools/node_modules/eslint/node_modules/rxjs/src/ajax/BUILD.bazel b/tools/node_modules/eslint/node_modules/rxjs/src/ajax/BUILD.bazel deleted file mode 100644 index ec2cf4988a39e7..00000000000000 --- a/tools/node_modules/eslint/node_modules/rxjs/src/ajax/BUILD.bazel +++ /dev/null @@ -1,13 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load("@build_bazel_rules_typescript//:defs.bzl", "ts_library") - -ts_library( - name = "ajax", - srcs = ["index.ts"], - module_name = "rxjs/ajax", - module_root = "index.d.ts", - node_modules = "@build_bazel_rules_typescript_tsc_wrapped_deps//:node_modules", - tsconfig = "//:tsconfig.json", - deps = ["//:lib"], -) diff --git a/tools/node_modules/eslint/node_modules/rxjs/src/fetch/package.json b/tools/node_modules/eslint/node_modules/rxjs/src/fetch/package.json new file mode 100644 index 00000000000000..dff5519633b960 --- /dev/null +++ b/tools/node_modules/eslint/node_modules/rxjs/src/fetch/package.json @@ -0,0 +1,8 @@ +{ + "name": "rxjs/fetch", + "typings": "./index.d.ts", + "main": "./index.js", + "module": "../_esm5/fetch/index.js", + "es2015": "../_esm2015/fetch/index.js", + "sideEffects": false +} diff --git a/tools/node_modules/eslint/node_modules/rxjs/src/operators/BUILD.bazel b/tools/node_modules/eslint/node_modules/rxjs/src/operators/BUILD.bazel deleted file mode 100644 index 19066843078577..00000000000000 --- a/tools/node_modules/eslint/node_modules/rxjs/src/operators/BUILD.bazel +++ /dev/null @@ -1,13 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load("@build_bazel_rules_typescript//:defs.bzl", "ts_library") - -ts_library( - name = "operators", - srcs = ["index.ts"], - module_name = "rxjs/operators", - module_root = "index.d.ts", - node_modules = "@build_bazel_rules_typescript_tsc_wrapped_deps//:node_modules", - tsconfig = "//:tsconfig.json", - deps = ["//:lib"], -) diff --git a/tools/node_modules/eslint/node_modules/rxjs/src/webSocket/BUILD.bazel b/tools/node_modules/eslint/node_modules/rxjs/src/webSocket/BUILD.bazel deleted file mode 100644 index d95d8be5dbec55..00000000000000 --- a/tools/node_modules/eslint/node_modules/rxjs/src/webSocket/BUILD.bazel +++ /dev/null @@ -1,13 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load("@build_bazel_rules_typescript//:defs.bzl", "ts_library") - -ts_library( - name = "webSocket", - srcs = ["index.ts"], - module_name = "rxjs/webSocket", - module_root = "index.d.ts", - node_modules = "@build_bazel_rules_typescript_tsc_wrapped_deps//:node_modules", - tsconfig = "//:tsconfig.json", - deps = ["//:lib"], -) diff --git a/tools/node_modules/eslint/node_modules/state-toggle/index.js b/tools/node_modules/eslint/node_modules/state-toggle/index.js index 8fda5118165b00..aceee00d1db789 100644 --- a/tools/node_modules/eslint/node_modules/state-toggle/index.js +++ b/tools/node_modules/eslint/node_modules/state-toggle/index.js @@ -2,9 +2,9 @@ module.exports = factory -/* Construct a state `toggler`: a function which inverses - * `property` in context based on its current value. - * The by `toggler` returned function restores that value. */ +// Construct a state `toggler`: a function which inverses `property` in context +// based on its current value. +// The by `toggler` returned function restores that value. function factory(key, state, ctx) { return enter diff --git a/tools/node_modules/eslint/node_modules/state-toggle/LICENSE b/tools/node_modules/eslint/node_modules/state-toggle/license similarity index 100% rename from tools/node_modules/eslint/node_modules/state-toggle/LICENSE rename to tools/node_modules/eslint/node_modules/state-toggle/license diff --git a/tools/node_modules/eslint/node_modules/state-toggle/package.json b/tools/node_modules/eslint/node_modules/state-toggle/package.json index 40aabaa8e132bf..19cb1446496178 100644 --- a/tools/node_modules/eslint/node_modules/state-toggle/package.json +++ b/tools/node_modules/eslint/node_modules/state-toggle/package.json @@ -2,7 +2,7 @@ "author": { "name": "Titus Wormer", "email": "tituswormer@gmail.com", - "url": "http://wooorm.com" + "url": "https://wooorm.com" }, "bugs": { "url": "https://github.com/wooorm/state-toggle/issues" @@ -12,7 +12,7 @@ { "name": "Titus Wormer", "email": "tituswormer@gmail.com", - "url": "http://wooorm.com" + "url": "https://wooorm.com" } ], "dependencies": {}, @@ -20,13 +20,13 @@ "description": "Enter/exit a state", "devDependencies": { "browserify": "^16.0.0", - "esmangle": "^1.0.1", - "nyc": "^11.0.0", + "nyc": "^14.0.0", "prettier": "^1.12.1", - "remark-cli": "^5.0.0", + "remark-cli": "^6.0.0", "remark-preset-wooorm": "^4.0.0", "tape": "^4.0.0", - "xo": "^0.20.0" + "tinyify": "^2.5.0", + "xo": "^0.24.0" }, "files": [ "index.js" @@ -64,21 +64,17 @@ }, "scripts": { "build": "npm run build-bundle && npm run build-mangle", - "build-bundle": "browserify index.js --bare -s stateToggle > state-toggle.js", - "build-mangle": "esmangle < state-toggle.js > state-toggle.min.js", - "format": "remark . -qfo && prettier --write '**/*.js' && xo --fix", + "build-bundle": "browserify . -s stateToggle -o state-toggle.js", + "build-mangle": "browserify . -s stateToggle -p tinyify -o state-toggle.min.js", + "format": "remark . -qfo && prettier --write \"**/*.js\" && xo --fix", "test": "npm run format && npm run build && npm run test-coverage", "test-api": "node test", "test-coverage": "nyc --reporter lcov tape test.js" }, - "version": "1.0.1", + "version": "1.0.2", "xo": { "prettier": true, "esnext": false, - "rules": { - "no-var": "off", - "prefer-arrow-callback": "off" - }, "ignores": [ "state-toggle.js" ] diff --git a/tools/node_modules/eslint/node_modules/state-toggle/readme.md b/tools/node_modules/eslint/node_modules/state-toggle/readme.md index 071a022123e447..30e5ea96c77b9b 100644 --- a/tools/node_modules/eslint/node_modules/state-toggle/readme.md +++ b/tools/node_modules/eslint/node_modules/state-toggle/readme.md @@ -1,4 +1,9 @@ -# state-toggle [![Build Status][travis-badge]][travis] [![Coverage Status][codecov-badge]][codecov] +# state-toggle + +[![Build][build-badge]][build] +[![Coverage][coverage-badge]][coverage] +[![Downloads][downloads-badge]][downloads] +[![Size][size-badge]][size] Enter/exit a state. @@ -63,19 +68,27 @@ Exit the state, reverting `key` to the value it had before entering. -[travis-badge]: https://img.shields.io/travis/wooorm/state-toggle.svg +[build-badge]: https://img.shields.io/travis/wooorm/state-toggle.svg + +[build]: https://travis-ci.org/wooorm/state-toggle + +[coverage-badge]: https://img.shields.io/codecov/c/github/wooorm/state-toggle.svg + +[coverage]: https://codecov.io/github/wooorm/state-toggle + +[downloads-badge]: https://img.shields.io/npm/dm/state-toggle.svg -[travis]: https://travis-ci.org/wooorm/state-toggle +[downloads]: https://www.npmjs.com/package/state-toggle -[codecov-badge]: https://img.shields.io/codecov/c/github/wooorm/state-toggle.svg +[size-badge]: https://img.shields.io/bundlephobia/minzip/state-toggle.svg -[codecov]: https://codecov.io/github/wooorm/state-toggle +[size]: https://bundlephobia.com/result?p=state-toggle [npm]: https://docs.npmjs.com/cli/install -[license]: LICENSE +[license]: license -[author]: http://wooorm.com +[author]: https://wooorm.com [enter]: #enter diff --git a/tools/node_modules/eslint/node_modules/table/README.md b/tools/node_modules/eslint/node_modules/table/README.md index 1e47185c170563..b64dbd20e18441 100644 --- a/tools/node_modules/eslint/node_modules/table/README.md +++ b/tools/node_modules/eslint/node_modules/table/README.md @@ -1,6 +1,7 @@ # Table +[![GitSpo Mentions](https://gitspo.com/badges/mentions/gajus/table?style=flat-square)](https://gitspo.com/mentions/gajus/table) [![Travis build status](http://img.shields.io/travis/gajus/table/master.svg?style=flat-square)](https://travis-ci.org/gajus/table) [![Coveralls](https://img.shields.io/coveralls/gajus/table.svg?style=flat-square)](https://coveralls.io/github/gajus/table) [![NPM version](http://img.shields.io/npm/v/table.svg?style=flat-square)](https://www.npmjs.org/package/table) @@ -9,11 +10,13 @@ * [Table](#table) * [Features](#table-features) + * [Install](#table-install) * [Usage](#table-usage) * [Cell Content Alignment](#table-usage-cell-content-alignment) * [Column Width](#table-usage-column-width) * [Custom Border](#table-usage-custom-border) * [Draw Horizontal Line](#table-usage-draw-horizontal-line) + * [Single Line Mode](#table-usage-single-line-mode) * [Padding Cell Content](#table-usage-padding-cell-content) * [Predefined Border Templates](#table-usage-predefined-border-templates) * [Streaming](#table-usage-streaming) @@ -36,6 +39,17 @@ Produces a string that represents array data in a text table. * Configurable column width. * Text wrapping. + +## Install + +```bash +npm install table + +``` + +[![Buy Me A Coffee](https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png)](https://www.buymeacoffee.com/gajus) +[![Become a Patron](https://c5.patreon.com/external/logo/become_a_patron_button.png)](https://www.patreon.com/gajus) + ## Usage @@ -132,6 +146,7 @@ console.log(output); ╟────┼────┼────╢ ║ 2A │ 2B │ 2C ║ ╚════╧════╧════╝ + ``` @@ -144,30 +159,30 @@ Valid values are: "left", "right" and "center". ```js let config, - data, - output; + data, + output; data = [ - ['0A', '0B', '0C'], - ['1A', '1B', '1C'], - ['2A', '2B', '2C'] + ['0A', '0B', '0C'], + ['1A', '1B', '1C'], + ['2A', '2B', '2C'] ]; config = { - columns: { - 0: { - alignment: 'left', - minWidth: 10 - }, - 1: { - alignment: 'center', - minWidth: 10 - }, - 2: { - alignment: 'right', - minWidth: 10 - } + columns: { + 0: { + alignment: 'left', + minWidth: 10 + }, + 1: { + alignment: 'center', + minWidth: 10 + }, + 2: { + alignment: 'right', + minWidth: 10 } + } }; output = table(data, config); @@ -192,21 +207,21 @@ console.log(output); ```js let data, - output, - options; + output, + options; data = [ - ['0A', '0B', '0C'], - ['1A', '1B', '1C'], - ['2A', '2B', '2C'] + ['0A', '0B', '0C'], + ['1A', '1B', '1C'], + ['2A', '2B', '2C'] ]; options = { - columns: { - 1: { - width: 10 - } + columns: { + 1: { + width: 10 } + } }; output = table(data, options); @@ -231,36 +246,36 @@ console.log(output); ```js let config, - data, - output; + data, + output; data = [ - ['0A', '0B', '0C'], - ['1A', '1B', '1C'], - ['2A', '2B', '2C'] + ['0A', '0B', '0C'], + ['1A', '1B', '1C'], + ['2A', '2B', '2C'] ]; config = { - border: { - topBody: `─`, - topJoin: `┬`, - topLeft: `┌`, - topRight: `┐`, - - bottomBody: `─`, - bottomJoin: `┴`, - bottomLeft: `└`, - bottomRight: `┘`, - - bodyLeft: `│`, - bodyRight: `│`, - bodyJoin: `│`, - - joinBody: `─`, - joinLeft: `├`, - joinRight: `┤`, - joinJoin: `┼` - } + border: { + topBody: `─`, + topJoin: `┬`, + topLeft: `┌`, + topRight: `┐`, + + bottomBody: `─`, + bottomJoin: `┴`, + bottomLeft: `└`, + bottomRight: `┘`, + + bodyLeft: `│`, + bodyRight: `│`, + bodyJoin: `│`, + + joinBody: `─`, + joinLeft: `├`, + joinRight: `┤`, + joinJoin: `┼` + } }; output = table(data, config); @@ -285,27 +300,27 @@ console.log(output); ```js let data, - output, - options; + output, + options; data = [ - ['0A', '0B', '0C'], - ['1A', '1B', '1C'], - ['2A', '2B', '2C'], - ['3A', '3B', '3C'], - ['4A', '4B', '4C'] + ['0A', '0B', '0C'], + ['1A', '1B', '1C'], + ['2A', '2B', '2C'], + ['3A', '3B', '3C'], + ['4A', '4B', '4C'] ]; options = { - /** - * @typedef {function} drawHorizontalLine - * @param {number} index - * @param {number} size - * @return {boolean} - */ - drawHorizontalLine: (index, size) => { - return index === 0 || index === 1 || index === size - 1 || index === size; - } + /** + * @typedef {function} drawHorizontalLine + * @param {number} index + * @param {number} size + * @return {boolean} + */ + drawHorizontalLine: (index, size) => { + return index === 0 || index === 1 || index === size - 1 || index === size; + } }; output = table(data, options); @@ -327,6 +342,49 @@ console.log(output); ``` + +### Single Line Mode + +Horizontal lines inside the table are not drawn. + +```js +import { + table, + getBorderCharacters +} from 'table'; + +const data = [ + ['-rw-r--r--', '1', 'pandorym', 'staff', '1529', 'May 23 11:25', 'LICENSE'], + ['-rw-r--r--', '1', 'pandorym', 'staff', '16327', 'May 23 11:58', 'README.md'], + ['drwxr-xr-x', '76', 'pandorym', 'staff', '2432', 'May 23 12:02', 'dist'], + ['drwxr-xr-x', '634', 'pandorym', 'staff', '20288', 'May 23 11:54', 'node_modules'], + ['-rw-r--r--', '1,', 'pandorym', 'staff', '525688', 'May 23 11:52', 'package-lock.json'], + ['-rw-r--r--@', '1', 'pandorym', 'staff', '2440', 'May 23 11:25', 'package.json'], + ['drwxr-xr-x', '27', 'pandorym', 'staff', '864', 'May 23 11:25', 'src'], + ['drwxr-xr-x', '20', 'pandorym', 'staff', '640', 'May 23 11:25', 'test'], +]; + +const config = { + singleLine: true +}; + +const output = table(data, config); +console.log(output); +``` + +``` +╔═════════════╤═════╤══════════╤═══════╤════════╤══════════════╤═══════════════════╗ +║ -rw-r--r-- │ 1 │ pandorym │ staff │ 1529 │ May 23 11:25 │ LICENSE ║ +║ -rw-r--r-- │ 1 │ pandorym │ staff │ 16327 │ May 23 11:58 │ README.md ║ +║ drwxr-xr-x │ 76 │ pandorym │ staff │ 2432 │ May 23 12:02 │ dist ║ +║ drwxr-xr-x │ 634 │ pandorym │ staff │ 20288 │ May 23 11:54 │ node_modules ║ +║ -rw-r--r-- │ 1, │ pandorym │ staff │ 525688 │ May 23 11:52 │ package-lock.json ║ +║ -rw-r--r--@ │ 1 │ pandorym │ staff │ 2440 │ May 23 11:25 │ package.json ║ +║ drwxr-xr-x │ 27 │ pandorym │ staff │ 864 │ May 23 11:25 │ src ║ +║ drwxr-xr-x │ 20 │ pandorym │ staff │ 640 │ May 23 11:25 │ test ║ +╚═════════════╧═════╧══════════╧═══════╧════════╧══════════════╧═══════════════════╝ +``` + ### Padding Cell Content @@ -334,25 +392,25 @@ console.log(output); ```js let config, - data, - output; + data, + output; data = [ - ['0A', 'AABBCC', '0C'], - ['1A', '1B', '1C'], - ['2A', '2B', '2C'] + ['0A', 'AABBCC', '0C'], + ['1A', '1B', '1C'], + ['2A', '2B', '2C'] ]; config = { - columns: { - 0: { - paddingLeft: 3 - }, - 1: { - width: 2, - paddingRight: 3 - } + columns: { + 0: { + paddingLeft: 3 + }, + 1: { + width: 2, + paddingRight: 3 } + } }; output = table(data, config); @@ -379,21 +437,21 @@ You can load one of the predefined border templates using `getBorderCharacters` ```js import { - table, - getBorderCharacters + table, + getBorderCharacters } from 'table'; let config, - data; + data; data = [ - ['0A', '0B', '0C'], - ['1A', '1B', '1C'], - ['2A', '2B', '2C'] + ['0A', '0B', '0C'], + ['1A', '1B', '1C'], + ['2A', '2B', '2C'] ]; config = { - border: getBorderCharacters(`name of the template`) + border: getBorderCharacters(`name of the template`) }; table(data, config); @@ -481,23 +539,23 @@ console.log(output); ```js import { - createStream + createStream } from 'table'; let config, - stream; + stream; config = { - columnDefault: { - width: 50 - }, - columnCount: 1 + columnDefault: { + width: 50 + }, + columnCount: 1 }; stream = createStream(config); setInterval(() => { - stream.write([new Date()]); + stream.write([new Date()]); }, 500); ``` @@ -505,38 +563,38 @@ setInterval(() => { `table` package uses ANSI escape codes to overwrite the output of the last line when a new row is printed. -The underlying implementation is explained in this [Stack Overflow answer](http://stackoverflow.com/a/32938658/368691). +The underlying implementation is explained in this [Stack Overflow answer](http://stackoverflow.com/a/32938658/368691). Streaming supports all of the configuration properties and functionality of a static table (such as auto text wrapping, alignment and padding), e.g. ```js import { - createStream + createStream } from 'table'; import _ from 'lodash'; let config, - stream, - i; + stream, + i; config = { - columnDefault: { - width: 50 + columnDefault: { + width: 50 + }, + columnCount: 3, + columns: { + 0: { + width: 10, + alignment: 'right' + }, + 1: { + alignment: 'center', }, - columnCount: 3, - columns: { - 0: { - width: 10, - alignment: 'right' - }, - 1: { - alignment: 'center', - }, - 2: { - width: 10 - } + 2: { + width: 10 } + } }; stream = createStream(config); @@ -544,15 +602,16 @@ stream = createStream(config); i = 0; setInterval(() => { - let random; + let random; - random = _.sample('abcdefghijklmnopqrstuvwxyz', _.random(1, 30)).join(''); + random = _.sample('abcdefghijklmnopqrstuvwxyz', _.random(1, 30)).join(''); - stream.write([i++, new Date(), random]); + stream.write([i++, new Date(), random]); }, 500); ``` ![Streaming random data.](./.README/streaming-random.gif) + ### Text Truncation @@ -562,20 +621,20 @@ To handle a content that overflows the container width, `table` package implemen ```js let config, - data, - output; + data, + output; data = [ - ['Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus pulvinar nibh sed mauris convallis dapibus. Nunc venenatis tempus nulla sit amet viverra.'] + ['Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus pulvinar nibh sed mauris convallis dapibus. Nunc venenatis tempus nulla sit amet viverra.'] ]; config = { - columns: { - 0: { - width: 20, - truncate: 100 - } + columns: { + 0: { + width: 20, + truncate: 100 } + } }; output = table(data, config); @@ -600,19 +659,19 @@ console.log(output); ```js let config, - data, - output; + data, + output; data = [ ['Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus pulvinar nibh sed mauris convallis dapibus. Nunc venenatis tempus nulla sit amet viverra.'] ]; config = { - columns: { - 0: { - width: 20 - } + columns: { + 0: { + width: 20 } + } }; output = table(data, config); @@ -637,20 +696,20 @@ When `wrapWord` is `true` the text is broken at the nearest space or one of the ```js let config, - data, - output; + data, + output; data = [ - ['Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus pulvinar nibh sed mauris convallis dapibus. Nunc venenatis tempus nulla sit amet viverra.'] + ['Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus pulvinar nibh sed mauris convallis dapibus. Nunc venenatis tempus nulla sit amet viverra.'] ]; config = { - columns: { - 0: { - width: 20, - wrapWord: true - } + columns: { + 0: { + width: 20, + wrapWord: true } + } }; output = table(data, config); @@ -671,5 +730,6 @@ console.log(output); ║ tempus nulla sit ║ ║ amet viverra. ║ ╚══════════════════════╝ + ``` diff --git a/tools/node_modules/eslint/node_modules/table/dist/drawTable.js b/tools/node_modules/eslint/node_modules/table/dist/drawTable.js index 5585af888f6612..fbfdc2016138d8 100644 --- a/tools/node_modules/eslint/node_modules/table/dist/drawTable.js +++ b/tools/node_modules/eslint/node_modules/table/dist/drawTable.js @@ -17,9 +17,10 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @param {Array} columnSizeIndex * @param {Array} rowSpanIndex * @param {Function} drawHorizontalLine + * @param {boolean} singleLine * @returns {string} */ -const drawTable = (rows, border, columnSizeIndex, rowSpanIndex, drawHorizontalLine) => { +const drawTable = (rows, border, columnSizeIndex, rowSpanIndex, drawHorizontalLine, singleLine) => { let output; let realRowIndex; let rowHeight; @@ -41,7 +42,7 @@ const drawTable = (rows, border, columnSizeIndex, rowSpanIndex, drawHorizontalLi rowHeight--; - if (rowHeight === 0 && index0 !== rowCount - 1 && drawHorizontalLine(realRowIndex, rowCount)) { + if (!singleLine && rowHeight === 0 && index0 !== rowCount - 1 && drawHorizontalLine(realRowIndex, rowCount)) { output += (0, _drawBorder.drawBorderJoin)(columnSizeIndex, border); } }); diff --git a/tools/node_modules/eslint/node_modules/table/dist/drawTable.js.flow b/tools/node_modules/eslint/node_modules/table/dist/drawTable.js.flow index 15ad14cfa2ba12..cffe956f2009dd 100644 --- a/tools/node_modules/eslint/node_modules/table/dist/drawTable.js.flow +++ b/tools/node_modules/eslint/node_modules/table/dist/drawTable.js.flow @@ -11,9 +11,10 @@ import drawRow from './drawRow'; * @param {Array} columnSizeIndex * @param {Array} rowSpanIndex * @param {Function} drawHorizontalLine + * @param {boolean} singleLine * @returns {string} */ -export default (rows, border, columnSizeIndex, rowSpanIndex, drawHorizontalLine) => { +export default (rows, border, columnSizeIndex, rowSpanIndex, drawHorizontalLine, singleLine) => { let output; let realRowIndex; let rowHeight; @@ -39,7 +40,7 @@ export default (rows, border, columnSizeIndex, rowSpanIndex, drawHorizontalLine) rowHeight--; - if (rowHeight === 0 && index0 !== rowCount - 1 && drawHorizontalLine(realRowIndex, rowCount)) { + if (!singleLine && rowHeight === 0 && index0 !== rowCount - 1 && drawHorizontalLine(realRowIndex, rowCount)) { output += drawBorderJoin(columnSizeIndex, border); } }); diff --git a/tools/node_modules/eslint/node_modules/table/dist/makeConfig.js b/tools/node_modules/eslint/node_modules/table/dist/makeConfig.js index 0ec93b8628161b..2828e453d93933 100644 --- a/tools/node_modules/eslint/node_modules/table/dist/makeConfig.js +++ b/tools/node_modules/eslint/node_modules/table/dist/makeConfig.js @@ -82,6 +82,10 @@ const makeConfig = (rows, userConfig = {}) => { }; } + if (config.singleLine === undefined) { + config.singleLine = false; + } + return config; }; diff --git a/tools/node_modules/eslint/node_modules/table/dist/makeConfig.js.flow b/tools/node_modules/eslint/node_modules/table/dist/makeConfig.js.flow index 9a0ee0afade046..1471afc57f47ca 100644 --- a/tools/node_modules/eslint/node_modules/table/dist/makeConfig.js.flow +++ b/tools/node_modules/eslint/node_modules/table/dist/makeConfig.js.flow @@ -68,5 +68,9 @@ export default (rows, userConfig = {}) => { }; } + if (config.singleLine === undefined) { + config.singleLine = false; + } + return config; }; diff --git a/tools/node_modules/eslint/node_modules/table/dist/table.js b/tools/node_modules/eslint/node_modules/table/dist/table.js index b4aac0167e3deb..bd4e8055b17018 100644 --- a/tools/node_modules/eslint/node_modules/table/dist/table.js +++ b/tools/node_modules/eslint/node_modules/table/dist/table.js @@ -81,6 +81,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @property {table~columns[]} columns Column specific configuration. * @property {table~columns} columnDefault Default values for all columns. Column specific settings overwrite the default values. * @property {table~drawHorizontalLine} drawHorizontalLine + * @property {table~singleLine} singleLine Horizontal lines inside the table are not drawn. */ /** @@ -101,7 +102,7 @@ const table = (data, userConfig = {}) => { rows = (0, _alignTableData.default)(rows, config); rows = (0, _padTableData.default)(rows, config); const cellWidthIndex = (0, _calculateCellWidthIndex.default)(rows[0]); - return (0, _drawTable.default)(rows, config.border, cellWidthIndex, rowHeightIndex, config.drawHorizontalLine); + return (0, _drawTable.default)(rows, config.border, cellWidthIndex, rowHeightIndex, config.drawHorizontalLine, config.singleLine); }; var _default = table; diff --git a/tools/node_modules/eslint/node_modules/table/dist/table.js.flow b/tools/node_modules/eslint/node_modules/table/dist/table.js.flow index 1b68a51a29488e..86af744bd1eafe 100644 --- a/tools/node_modules/eslint/node_modules/table/dist/table.js.flow +++ b/tools/node_modules/eslint/node_modules/table/dist/table.js.flow @@ -63,6 +63,7 @@ import truncateTableData from './truncateTableData'; * @property {table~columns[]} columns Column specific configuration. * @property {table~columns} columnDefault Default values for all columns. Column specific settings overwrite the default values. * @property {table~drawHorizontalLine} drawHorizontalLine + * @property {table~singleLine} singleLine Horizontal lines inside the table are not drawn. */ /** @@ -91,5 +92,5 @@ export default (data, userConfig = {}) => { const cellWidthIndex = calculateCellWidthIndex(rows[0]); - return drawTable(rows, config.border, cellWidthIndex, rowHeightIndex, config.drawHorizontalLine); + return drawTable(rows, config.border, cellWidthIndex, rowHeightIndex, config.drawHorizontalLine, config.singleLine); }; diff --git a/tools/node_modules/eslint/node_modules/table/dist/validateTableData.js b/tools/node_modules/eslint/node_modules/table/dist/validateTableData.js index 7fbd5ec1f561ae..bbd51ffb0775e9 100644 --- a/tools/node_modules/eslint/node_modules/table/dist/validateTableData.js +++ b/tools/node_modules/eslint/node_modules/table/dist/validateTableData.js @@ -56,7 +56,7 @@ const validateTableData = rows => { const cell = _step2.value; // eslint-disable-next-line no-control-regex - if (/[\u0001-\u0009\u000B-\u001A]/.test(cell)) { + if (/[\u0001-\u0006\u0008-\u0009\u000B-\u001A]/.test(cell)) { throw new Error('Table data must not contain control characters.'); } } diff --git a/tools/node_modules/eslint/node_modules/table/dist/validateTableData.js.flow b/tools/node_modules/eslint/node_modules/table/dist/validateTableData.js.flow index 4100f3773c5af7..304ab0dd05b995 100644 --- a/tools/node_modules/eslint/node_modules/table/dist/validateTableData.js.flow +++ b/tools/node_modules/eslint/node_modules/table/dist/validateTableData.js.flow @@ -36,7 +36,7 @@ export default (rows) => { for (const cell of cells) { // eslint-disable-next-line no-control-regex - if (/[\u0001-\u0009\u000B-\u001A]/.test(cell)) { + if (/[\u0001-\u0006\u0008-\u0009\u000B-\u001A]/.test(cell)) { throw new Error('Table data must not contain control characters.'); } } diff --git a/tools/node_modules/eslint/node_modules/table/package.json b/tools/node_modules/eslint/node_modules/table/package.json index 0068c152dc0f5f..25c326b40fdee4 100644 --- a/tools/node_modules/eslint/node_modules/table/package.json +++ b/tools/node_modules/eslint/node_modules/table/package.json @@ -85,5 +85,5 @@ "lint": "npm run build && eslint ./src ./test && flow", "test": "mocha --require @babel/register" }, - "version": "5.2.3" + "version": "5.4.0" } \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/trim-trailing-lines/index.js b/tools/node_modules/eslint/node_modules/trim-trailing-lines/index.js index ad536dd0c46211..0f2d48b52fc567 100644 --- a/tools/node_modules/eslint/node_modules/trim-trailing-lines/index.js +++ b/tools/node_modules/eslint/node_modules/trim-trailing-lines/index.js @@ -4,13 +4,13 @@ module.exports = trimTrailingLines var line = '\n' -/* Remove final newline characters from `value`. */ +// Remove final newline characters from `value`. function trimTrailingLines(value) { var val = String(value) var index = val.length while (val.charAt(--index) === line) { - /* Empty */ + // Empty } return val.slice(0, index + 1) diff --git a/tools/node_modules/eslint/node_modules/trim-trailing-lines/LICENSE b/tools/node_modules/eslint/node_modules/trim-trailing-lines/license similarity index 100% rename from tools/node_modules/eslint/node_modules/trim-trailing-lines/LICENSE rename to tools/node_modules/eslint/node_modules/trim-trailing-lines/license diff --git a/tools/node_modules/eslint/node_modules/trim-trailing-lines/package.json b/tools/node_modules/eslint/node_modules/trim-trailing-lines/package.json index ef58090d0f2a3e..c9920df6d31922 100644 --- a/tools/node_modules/eslint/node_modules/trim-trailing-lines/package.json +++ b/tools/node_modules/eslint/node_modules/trim-trailing-lines/package.json @@ -2,7 +2,7 @@ "author": { "name": "Titus Wormer", "email": "tituswormer@gmail.com", - "url": "http://wooorm.com" + "url": "https://wooorm.com" }, "bugs": { "url": "https://github.com/wooorm/trim-trailing-lines/issues" @@ -12,7 +12,7 @@ { "name": "Titus Wormer", "email": "tituswormer@gmail.com", - "url": "http://wooorm.com" + "url": "https://wooorm.com" } ], "dependencies": {}, @@ -20,13 +20,13 @@ "description": "Remove final newline characters from a string", "devDependencies": { "browserify": "^16.0.0", - "esmangle": "^1.0.0", - "nyc": "^11.0.0", + "nyc": "^14.0.0", "prettier": "^1.12.1", - "remark-cli": "^5.0.0", + "remark-cli": "^6.0.0", "remark-preset-wooorm": "^4.0.0", "tape": "^4.6.3", - "xo": "^0.20.0" + "tinyify": "^2.5.0", + "xo": "^0.24.0" }, "files": [ "index.js" @@ -66,21 +66,17 @@ }, "scripts": { "build": "npm run build-bundle && npm run build-mangle", - "build-bundle": "browserify index.js -s trimTrailingLines > trim-trailing-lines.js", - "build-mangle": "esmangle trim-trailing-lines.js > trim-trailing-lines.min.js", - "format": "remark . -qfo && prettier --write '**/*.js' && xo --fix", + "build-bundle": "browserify . -s trimTrailingLines -o trim-trailing-lines.js", + "build-mangle": "browserify . -s trimTrailingLines -p tinyify -o trim-trailing-lines.min.js", + "format": "remark . -qfo && prettier --write \"**/*.js\" && xo --fix", "test": "npm run format && npm run build && npm run test-coverage", "test-api": "node test", "test-coverage": "nyc --reporter lcov tape test.js" }, - "version": "1.1.1", + "version": "1.1.2", "xo": { "prettier": true, "esnext": false, - "rules": { - "no-var": "off", - "prefer-arrow-callback": "off" - }, "ignores": [ "trim-trailing-lines.js" ] diff --git a/tools/node_modules/eslint/node_modules/trim-trailing-lines/readme.md b/tools/node_modules/eslint/node_modules/trim-trailing-lines/readme.md index e8e9d3798f9af8..813a0b5344bca1 100644 --- a/tools/node_modules/eslint/node_modules/trim-trailing-lines/readme.md +++ b/tools/node_modules/eslint/node_modules/trim-trailing-lines/readme.md @@ -1,4 +1,9 @@ -# trim-trailing-lines [![Build Status][travtrim-trailing-lines]][travis] [![Coverage Status][codecov-badge]][codecov] +# trim-trailing-lines + +[![Build][build-badge]][build] +[![Coverage][coverage-badge]][coverage] +[![Downloads][downloads-badge]][downloads] +[![Size][size-badge]][size] Remove final newline characters from a string. @@ -40,16 +45,24 @@ Remove final newline characters from `value`. -[travtrim-trailing-lines]: https://img.shields.io/travis/wooorm/trim-trailing-lines.svg +[build-badge]: https://img.shields.io/travis/wooorm/trim-trailing-lines.svg + +[build]: https://travis-ci.org/wooorm/trim-trailing-lines + +[coverage-badge]: https://img.shields.io/codecov/c/github/wooorm/trim-trailing-lines.svg + +[coverage]: https://codecov.io/github/wooorm/trim-trailing-lines + +[downloads-badge]: https://img.shields.io/npm/dm/trim-trailing-lines.svg -[travis]: https://travis-ci.org/wooorm/trim-trailing-lines +[downloads]: https://www.npmjs.com/package/trim-trailing-lines -[codecov-badge]: https://img.shields.io/codecov/c/github/wooorm/trim-trailing-lines.svg +[size-badge]: https://img.shields.io/bundlephobia/minzip/trim-trailing-lines.svg -[codecov]: https://codecov.io/github/wooorm/trim-trailing-lines +[size]: https://bundlephobia.com/result?p=trim-trailing-lines [npm]: https://docs.npmjs.com/cli/install -[license]: LICENSE +[license]: license -[author]: http://wooorm.com +[author]: https://wooorm.com diff --git a/tools/node_modules/eslint/node_modules/trough/index.js b/tools/node_modules/eslint/node_modules/trough/index.js index 9b60e3c8a87cef..2b73d868056525 100644 --- a/tools/node_modules/eslint/node_modules/trough/index.js +++ b/tools/node_modules/eslint/node_modules/trough/index.js @@ -8,7 +8,7 @@ trough.wrap = wrap var slice = [].slice -/* Create new middleware. */ +// Create new middleware. function trough() { var fns = [] var middleware = {} @@ -18,8 +18,7 @@ function trough() { return middleware - /* Run `fns`. Last argument must be - * a completion handler. */ + // Run `fns`. Last argument must be a completion handler. function run() { var index = -1 var input = slice.call(arguments, 0, -1) @@ -31,7 +30,7 @@ function trough() { next.apply(null, [null].concat(input)) - /* Run the next `fn`, if any. */ + // Run the next `fn`, if any. function next(err) { var fn = fns[++index] var params = slice.call(arguments, 0) @@ -44,7 +43,7 @@ function trough() { return } - /* Copy non-nully input into values. */ + // Copy non-nully input into values. while (++pos < length) { if (values[pos] === null || values[pos] === undefined) { values[pos] = input[pos] @@ -53,7 +52,7 @@ function trough() { input = values - /* Next or done. */ + // Next or done. if (fn) { wrap(fn, next).apply(null, input) } else { @@ -62,7 +61,7 @@ function trough() { } } - /* Add `fn` to the list. */ + // Add `fn` to the list. function use(fn) { if (typeof fn !== 'function') { throw new Error('Expected `fn` to be a function, not ' + fn) diff --git a/tools/node_modules/eslint/node_modules/trough/LICENSE b/tools/node_modules/eslint/node_modules/trough/license similarity index 100% rename from tools/node_modules/eslint/node_modules/trough/LICENSE rename to tools/node_modules/eslint/node_modules/trough/license diff --git a/tools/node_modules/eslint/node_modules/trough/package.json b/tools/node_modules/eslint/node_modules/trough/package.json index dd5bea77dbc333..ad3a3f7081df46 100644 --- a/tools/node_modules/eslint/node_modules/trough/package.json +++ b/tools/node_modules/eslint/node_modules/trough/package.json @@ -2,7 +2,7 @@ "author": { "name": "Titus Wormer", "email": "tituswormer@gmail.com", - "url": "http://wooorm.com" + "url": "https://wooorm.com" }, "bugs": { "url": "https://github.com/wooorm/trough/issues" @@ -12,7 +12,7 @@ { "name": "Titus Wormer", "email": "tituswormer@gmail.com", - "url": "http://wooorm.com" + "url": "https://wooorm.com" } ], "dependencies": {}, @@ -20,13 +20,13 @@ "description": "Middleware: a channel used to convey a liquid", "devDependencies": { "browserify": "^16.0.0", - "nyc": "^11.0.0", + "nyc": "^14.0.0", "prettier": "^1.12.0", - "remark-cli": "^5.0.0", + "remark-cli": "^6.0.0", "remark-preset-wooorm": "^4.0.0", "tape": "^4.4.0", "tinyify": "^2.4.3", - "xo": "^0.20.0" + "xo": "^0.24.0" }, "files": [ "index.js", @@ -66,20 +66,18 @@ "build": "npm run build-bundle && npm run build-mangle", "build-bundle": "browserify index.js -s trough > trough.js", "build-mangle": "browserify index.js -s trough -p tinyify > trough.min.js", - "format": "remark . -qfo && prettier --write '**/*.js' && xo --fix", + "format": "remark . -qfo && prettier --write \"**/*.js\" && xo --fix", "test": "npm run format && npm run build && npm run test-coverage", "test-api": "node test", "test-coverage": "nyc --reporter lcov tape test.js" }, - "version": "1.0.3", + "version": "1.0.4", "xo": { "prettier": true, "esnext": false, "rules": { "guard-for-in": "off", - "unicorn/prefer-type-error": "off", - "no-var": "off", - "prefer-arrow-callback": "off" + "unicorn/prefer-type-error": "off" }, "ignores": [ "trough.js" diff --git a/tools/node_modules/eslint/node_modules/trough/readme.md b/tools/node_modules/eslint/node_modules/trough/readme.md index c4a96c5ba60e55..f91e814a0a2f9e 100644 --- a/tools/node_modules/eslint/node_modules/trough/readme.md +++ b/tools/node_modules/eslint/node_modules/trough/readme.md @@ -1,4 +1,9 @@ -# trough [![Build Status][travis-badge]][travis] [![Coverage Status][codecov-badge]][codecov] +# trough + +[![Build][build-badge]][build] +[![Coverage][coverage-badge]][coverage] +[![Downloads][downloads-badge]][downloads] +[![Size][size-badge]][size] > **trough** /trôf/ — a channel used to convey a liquid. @@ -289,19 +294,27 @@ null 'some' 'values' -[travis-badge]: https://img.shields.io/travis/wooorm/trough.svg +[build-badge]: https://img.shields.io/travis/wooorm/trough.svg + +[build]: https://travis-ci.org/wooorm/trough + +[coverage-badge]: https://img.shields.io/codecov/c/github/wooorm/trough.svg + +[coverage]: https://codecov.io/github/wooorm/trough + +[downloads-badge]: https://img.shields.io/npm/dm/trough.svg -[travis]: https://travis-ci.org/wooorm/trough +[downloads]: https://www.npmjs.com/package/trough -[codecov-badge]: https://img.shields.io/codecov/c/github/wooorm/trough.svg +[size-badge]: https://img.shields.io/bundlephobia/minzip/trough.svg -[codecov]: https://codecov.io/github/wooorm/trough +[size]: https://bundlephobia.com/result?p=trough [npm]: https://docs.npmjs.com/cli/install -[license]: LICENSE +[license]: license -[author]: http://wooorm.com +[author]: https://wooorm.com [ware]: https://github.com/segmentio/ware diff --git a/tools/node_modules/eslint/node_modules/trough/wrap.js b/tools/node_modules/eslint/node_modules/trough/wrap.js index febdc98cd3fbab..cf568c07adfa34 100644 --- a/tools/node_modules/eslint/node_modules/trough/wrap.js +++ b/tools/node_modules/eslint/node_modules/trough/wrap.js @@ -4,9 +4,9 @@ var slice = [].slice module.exports = wrap -/* Wrap `fn`. Can be sync or async; return a promise, - * receive a completion handler, return new values and - * errors. */ +// Wrap `fn`. +// Can be sync or async; return a promise, receive a completion handler, return +// new values and errors. function wrap(fn, callback) { var invoked @@ -23,18 +23,17 @@ function wrap(fn, callback) { try { result = fn.apply(null, params) - } catch (err) { - /* Well, this is quite the pickle. `fn` received - * a callback and invoked it (thus continuing the - * pipeline), but later also threw an error. - * We’re not about to restart the pipeline again, - * so the only thing left to do is to throw the - * thing instea. */ + } catch (error) { + // Well, this is quite the pickle. + // `fn` received a callback and invoked it (thus continuing the pipeline), + // but later also threw an error. + // We’re not about to restart the pipeline again, so the only thing left + // to do is to throw the thing instead. if (callback && invoked) { - throw err + throw error } - return done(err) + return done(error) } if (!callback) { @@ -48,7 +47,7 @@ function wrap(fn, callback) { } } - /* Invoke `next`, only once. */ + // Invoke `next`, only once. function done() { if (!invoked) { invoked = true @@ -57,8 +56,8 @@ function wrap(fn, callback) { } } - /* Invoke `done` with one value. - * Tracks if an error is passed, too. */ + // Invoke `done` with one value. + // Tracks if an error is passed, too. function then(value) { done(null, value) } diff --git a/tools/node_modules/eslint/node_modules/unherit/index.js b/tools/node_modules/eslint/node_modules/unherit/index.js index e156c6197482ea..32ead7770fa2c9 100644 --- a/tools/node_modules/eslint/node_modules/unherit/index.js +++ b/tools/node_modules/eslint/node_modules/unherit/index.js @@ -5,8 +5,8 @@ var inherits = require('inherits') module.exports = unherit -/* Create a custom constructor which can be modified - * without affecting the original class. */ +// Create a custom constructor which can be modified without affecting the +// original class. function unherit(Super) { var result var key @@ -15,7 +15,7 @@ function unherit(Super) { inherits(Of, Super) inherits(From, Of) - /* Clone values. */ + // Clone values. result = Of.prototype for (key in result) { @@ -28,13 +28,13 @@ function unherit(Super) { return Of - /* Constructor accepting a single argument, - * which itself is an `arguments` object. */ + // Constructor accepting a single argument, which itself is an `arguments` + // object. function From(parameters) { return Super.apply(this, parameters) } - /* Constructor accepting variadic arguments. */ + // Constructor accepting variadic arguments. function Of() { if (!(this instanceof Of)) { return new From(arguments) diff --git a/tools/node_modules/eslint/node_modules/unherit/LICENSE b/tools/node_modules/eslint/node_modules/unherit/license similarity index 100% rename from tools/node_modules/eslint/node_modules/unherit/LICENSE rename to tools/node_modules/eslint/node_modules/unherit/license diff --git a/tools/node_modules/eslint/node_modules/unherit/package.json b/tools/node_modules/eslint/node_modules/unherit/package.json index 00ae793ec86e25..c0aaa416d83563 100644 --- a/tools/node_modules/eslint/node_modules/unherit/package.json +++ b/tools/node_modules/eslint/node_modules/unherit/package.json @@ -2,7 +2,7 @@ "author": { "name": "Titus Wormer", "email": "tituswormer@gmail.com", - "url": "http://wooorm.com" + "url": "https://wooorm.com" }, "bugs": { "url": "https://github.com/wooorm/unherit/issues" @@ -12,7 +12,7 @@ { "name": "Titus Wormer", "email": "tituswormer@gmail.com", - "url": "http://wooorm.com" + "url": "https://wooorm.com" } ], "dependencies": { @@ -23,13 +23,13 @@ "description": "Clone a constructor without affecting the super-class", "devDependencies": { "browserify": "^16.0.0", - "esmangle": "^1.0.1", - "nyc": "^11.0.0", + "nyc": "^14.0.0", "prettier": "^1.12.1", - "remark-cli": "^5.0.0", + "remark-cli": "^6.0.0", "remark-preset-wooorm": "^4.0.0", "tape": "^4.0.0", - "xo": "^0.20.0" + "tinyify": "^2.5.0", + "xo": "^0.24.0" }, "files": [ "index.js" @@ -62,20 +62,18 @@ }, "scripts": { "build": "npm run build-bundle && npm run build-mangle", - "build-bundle": "browserify index.js --bare -s unherit > unherit.js", - "build-mangle": "esmangle unherit.js > unherit.min.js", - "format": "remark . -qfo && prettier --write '**/*.js' && xo --fix", + "build-bundle": "browserify . -s unherit -o unherit.js", + "build-mangle": "browserify . -s unherit -p tinyify -o unherit.min.js", + "format": "remark . -qfo && prettier --write \"**/*.js\" && xo --fix", "test": "npm run format && npm run build && npm run test-coverage", "test-api": "node test", "test-coverage": "nyc --reporter lcov tape test.js" }, - "version": "1.1.1", + "version": "1.1.2", "xo": { "prettier": true, "esnext": false, "rules": { - "no-var": "off", - "prefer-arrow-callback": "off", "guard-for-in": "off" }, "ignores": [ diff --git a/tools/node_modules/eslint/node_modules/unherit/readme.md b/tools/node_modules/eslint/node_modules/unherit/readme.md index 3b5091d5c284e2..674a2092d5b710 100644 --- a/tools/node_modules/eslint/node_modules/unherit/readme.md +++ b/tools/node_modules/eslint/node_modules/unherit/readme.md @@ -1,4 +1,9 @@ -# unherit [![Build Status][travis-badge]][travis] [![Coverage Status][codecov-badge]][codecov] +# unherit + +[![Build][build-badge]][build] +[![Coverage][coverage-badge]][coverage] +[![Downloads][downloads-badge]][downloads] +[![Size][size-badge]][size] Create a custom constructor which can be modified without affecting the original class. @@ -17,13 +22,12 @@ npm install unherit var EventEmitter = require('events').EventEmitter var unherit = require('unherit') -/* Create a private class which acts just like - * `EventEmitter`. */ +// Create a private class which acts just like `EventEmitter`. var Emitter = unherit(EventEmitter) Emitter.prototype.defaultMaxListeners = 0 -/* Now, all instances of `Emitter` have no maximum - * listeners, without affecting other `EventEmitter`s. */ +// Now, all instances of `Emitter` have no maximum listeners, without affecting +// other `EventEmitter`s. new Emitter().defaultMaxListeners === 0 // => true new EventEmitter().defaultMaxListeners === undefined // => true @@ -52,16 +56,24 @@ without affecting the original class. -[travis-badge]: https://img.shields.io/travis/wooorm/unherit.svg +[build-badge]: https://img.shields.io/travis/wooorm/unherit.svg + +[build]: https://travis-ci.org/wooorm/unherit + +[coverage-badge]: https://img.shields.io/codecov/c/github/wooorm/unherit.svg + +[coverage]: https://codecov.io/github/wooorm/unherit + +[downloads-badge]: https://img.shields.io/npm/dm/unherit.svg -[travis]: https://travis-ci.org/wooorm/unherit +[downloads]: https://www.npmjs.com/package/unherit -[codecov-badge]: https://img.shields.io/codecov/c/github/wooorm/unherit.svg +[size-badge]: https://img.shields.io/bundlephobia/minzip/unherit.svg -[codecov]: https://codecov.io/github/wooorm/unherit +[size]: https://bundlephobia.com/result?p=unherit [npm-install]: https://docs.npmjs.com/cli/install -[license]: LICENSE +[license]: license -[author]: http://wooorm.com +[author]: https://wooorm.com diff --git a/tools/node_modules/eslint/node_modules/unist-util-is/index.js b/tools/node_modules/eslint/node_modules/unist-util-is/index.js index 775cf252f97f27..184115024c1f58 100644 --- a/tools/node_modules/eslint/node_modules/unist-util-is/index.js +++ b/tools/node_modules/eslint/node_modules/unist-util-is/index.js @@ -1,12 +1,10 @@ 'use strict' -/* eslint-disable max-params */ - -/* Expose. */ module.exports = is -/* Assert if `test` passes for `node`. - * When a `parent` node is known the `index` of node */ +// Assert if `test` passes for `node`. When a `parent` node is known the +// `index` of node. +// eslint-disable-next-line max-params function is(test, node, index, parent, context) { var hasParent = parent !== null && parent !== undefined var hasIndex = index !== null && index !== undefined @@ -66,8 +64,8 @@ function convertAll(tests) { return results } -/* Utility assert each property in `test` is represented - * in `node`, and each values are strictly equal. */ +// Utility assert each property in `test` is represented in `node`, and each +// values are strictly equal. function matchesFactory(test) { return matches @@ -103,8 +101,8 @@ function anyFactory(tests) { } } -/* Utility to convert a string into a function which checks - * a given node’s type for said string. */ +// Utility to convert a string into a function which checks a given node’s type +// for said string. function typeFactory(test) { return type @@ -113,7 +111,7 @@ function typeFactory(test) { } } -/* Utility to return true. */ +// Utility to return true. function ok() { return true } diff --git a/tools/node_modules/eslint/node_modules/unist-util-visit/LICENSE b/tools/node_modules/eslint/node_modules/unist-util-is/license similarity index 98% rename from tools/node_modules/eslint/node_modules/unist-util-visit/LICENSE rename to tools/node_modules/eslint/node_modules/unist-util-is/license index 32e7a3d93ca5a2..cfa79e66cfc072 100644 --- a/tools/node_modules/eslint/node_modules/unist-util-visit/LICENSE +++ b/tools/node_modules/eslint/node_modules/unist-util-is/license @@ -1,4 +1,4 @@ -(The MIT License) +(The MIT license) Copyright (c) 2015 Titus Wormer diff --git a/tools/node_modules/eslint/node_modules/unist-util-is/package.json b/tools/node_modules/eslint/node_modules/unist-util-is/package.json index e841568f7e0c4c..eea876c97270a3 100644 --- a/tools/node_modules/eslint/node_modules/unist-util-is/package.json +++ b/tools/node_modules/eslint/node_modules/unist-util-is/package.json @@ -2,7 +2,7 @@ "author": { "name": "Titus Wormer", "email": "tituswormer@gmail.com", - "url": "http://wooorm.com" + "url": "https://wooorm.com" }, "bugs": { "url": "https://github.com/syntax-tree/hast-util-to-html/issues" @@ -12,7 +12,7 @@ { "name": "Titus Wormer", "email": "tituswormer@gmail.com", - "url": "http://wooorm.com" + "url": "https://wooorm.com" } ], "dependencies": {}, @@ -20,13 +20,13 @@ "description": "Utility to check if a node passes a test", "devDependencies": { "browserify": "^16.0.0", - "esmangle": "^1.0.1", - "nyc": "^11.0.0", - "prettier": "^1.12.1", - "remark-cli": "^5.0.0", - "remark-preset-wooorm": "^4.0.0", + "nyc": "^14.0.0", + "prettier": "^1.0.0", + "remark-cli": "^6.0.0", + "remark-preset-wooorm": "^5.0.0", "tape": "^4.0.0", - "xo": "^0.20.0" + "tinyify": "^2.0.0", + "xo": "^0.24.0" }, "files": [ "index.js" @@ -69,21 +69,18 @@ }, "scripts": { "build": "npm run build-bundle && npm run build-mangle", - "build-bundle": "browserify index.js --bare -s unistUtilIs > unist-util-is.js", - "build-mangle": "esmangle < unist-util-is.js > unist-util-is.min.js", - "format": "remark . -qfo && prettier --write '**/*.js' && xo --fix", + "build-bundle": "browserify . -s unistUtilIs > unist-util-is.js", + "build-mangle": "browserify . -s unistUtilIs -p tinyify > unist-util-is.min.js", + "format": "remark . -qfo && prettier --write \"**/*.js\" && xo --fix", "test": "npm run format && npm run build && npm run test-coverage", "test-api": "node test", "test-coverage": "nyc --reporter lcov tape test.js" }, - "version": "2.1.2", + "version": "2.1.3", "xo": { "prettier": true, "esnext": false, "rules": { - "guard-for-in": "off", - "no-var": "off", - "prefer-arrow-callback": "off", "unicorn/prefer-type-error": "off" }, "ignore": [ diff --git a/tools/node_modules/eslint/node_modules/unist-util-is/readme.md b/tools/node_modules/eslint/node_modules/unist-util-is/readme.md index 88fa6d396ce01b..3ed2fce8dfb012 100644 --- a/tools/node_modules/eslint/node_modules/unist-util-is/readme.md +++ b/tools/node_modules/eslint/node_modules/unist-util-is/readme.md @@ -1,12 +1,20 @@ -# unist-util-is [![Build Status][travis-badge]][travis] [![Coverage Status][codecov-badge]][codecov] +# unist-util-is -[**Unist**][unist] utility to check if a node passes a test. +[![Build][build-badge]][build] +[![Coverage][coverage-badge]][coverage] +[![Downloads][downloads-badge]][downloads] +[![Size][size-badge]][size] +[![Sponsors][sponsors-badge]][collective] +[![Backers][backers-badge]][collective] +[![Chat][chat-badge]][chat] -## Installation +[**unist**][unist] utility to check if a node passes a test. + +## Install [npm][]: -```bash +```sh npm install unist-util-is ``` @@ -45,20 +53,19 @@ is(test, node, 5, parent) // => true * `test` ([`Function`][test], `string`, `Object`, or `Array.`, optional) — When not given, checks if `node` is a [`Node`][node]. - When `string`, works like passing `function (node) {return - node.type === test}`. - When `array`, checks any one of the subtests pass. + When `string`, works like passing `node => node.type === test`. + When `array`, checks if any one of the subtests pass. When `object`, checks that all keys in `test` are in `node`, - and that they have (strictly) equal values + and that they have strictly equal values * `node` ([`Node`][node]) — Node to check. `false` is returned -* `index` (`number`, optional) — Position of `node` in `parent` -* `parent` (`Node`, optional) — Parent of `node` +* `index` (`number`, optional) — [Index][] of `node` in `parent` +* `parent` ([`Node`][node], optional) — [Parent][] of `node` * `context` (`*`, optional) — Context object to invoke `test` with ###### Returns -`boolean` — Whether `test` passed _and_ `node` is a [`Node`][node] (object -with `type` set to non-empty `string`). +`boolean` — Whether `test` passed *and* `node` is a [`Node`][node] (object +with `type` set to a non-empty `string`). #### `function test(node[, index, parent])` @@ -97,11 +104,13 @@ with `type` set to non-empty `string`). ## Contribute -See [`contributing.md` in `syntax-tree/unist`][contributing] for ways to get +See [`contributing.md` in `syntax-tree/.github`][contributing] for ways to get started. +See [`support.md`][support] for ways to get help. -This organisation has a [Code of Conduct][coc]. By interacting with this -repository, organisation, or community you agree to abide by its terms. +This project has a [Code of Conduct][coc]. +By interacting with this repository, organisation, or community you agree to +abide by its terms. ## License @@ -109,26 +118,50 @@ repository, organisation, or community you agree to abide by its terms. -[travis-badge]: https://img.shields.io/travis/syntax-tree/unist-util-is.svg +[build-badge]: https://img.shields.io/travis/syntax-tree/unist-util-is.svg + +[build]: https://travis-ci.org/syntax-tree/unist-util-is + +[coverage-badge]: https://img.shields.io/codecov/c/github/syntax-tree/unist-util-is.svg + +[coverage]: https://codecov.io/github/syntax-tree/unist-util-is + +[downloads-badge]: https://img.shields.io/npm/dm/unist-util-is.svg + +[downloads]: https://www.npmjs.com/package/unist-util-is + +[size-badge]: https://img.shields.io/bundlephobia/minzip/unist-util-is.svg + +[size]: https://bundlephobia.com/result?p=unist-util-is -[travis]: https://travis-ci.org/syntax-tree/unist-util-is +[sponsors-badge]: https://opencollective.com/unified/sponsors/badge.svg -[codecov-badge]: https://img.shields.io/codecov/c/github/syntax-tree/unist-util-is.svg +[backers-badge]: https://opencollective.com/unified/backers/badge.svg -[codecov]: https://codecov.io/github/syntax-tree/unist-util-is +[collective]: https://opencollective.com/unified + +[chat-badge]: https://img.shields.io/badge/join%20the%20community-on%20spectrum-7b16ff.svg + +[chat]: https://spectrum.chat/unified/syntax-tree [npm]: https://docs.npmjs.com/cli/install -[license]: LICENSE +[license]: license + +[author]: https://wooorm.com + +[contributing]: https://github.com/syntax-tree/.github/blob/master/contributing.md -[author]: http://wooorm.com +[support]: https://github.com/syntax-tree/.github/blob/master/support.md + +[coc]: https://github.com/syntax-tree/.github/blob/master/code-of-conduct.md [unist]: https://github.com/syntax-tree/unist [node]: https://github.com/syntax-tree/unist#node -[test]: #function-testnode-index-parent +[parent]: https://github.com/syntax-tree/unist#parent-1 -[contributing]: https://github.com/syntax-tree/unist/blob/master/contributing.md +[index]: https://github.com/syntax-tree/unist#index -[coc]: https://github.com/syntax-tree/unist/blob/master/code-of-conduct.md +[test]: #function-testnode-index-parent diff --git a/tools/node_modules/eslint/node_modules/unist-util-remove-position/index.js b/tools/node_modules/eslint/node_modules/unist-util-remove-position/index.js index fbb0c2fcc68884..096395981793d9 100644 --- a/tools/node_modules/eslint/node_modules/unist-util-remove-position/index.js +++ b/tools/node_modules/eslint/node_modules/unist-util-remove-position/index.js @@ -4,7 +4,6 @@ var visit = require('unist-util-visit') module.exports = removePosition -/* Remove `position`s from `tree`. */ function removePosition(node, force) { visit(node, force ? hard : soft) return node diff --git a/tools/node_modules/eslint/node_modules/unist-util-remove-position/LICENSE b/tools/node_modules/eslint/node_modules/unist-util-remove-position/license similarity index 100% rename from tools/node_modules/eslint/node_modules/unist-util-remove-position/LICENSE rename to tools/node_modules/eslint/node_modules/unist-util-remove-position/license diff --git a/tools/node_modules/eslint/node_modules/unist-util-remove-position/package.json b/tools/node_modules/eslint/node_modules/unist-util-remove-position/package.json index e62c5e513eb51b..671af505b33478 100644 --- a/tools/node_modules/eslint/node_modules/unist-util-remove-position/package.json +++ b/tools/node_modules/eslint/node_modules/unist-util-remove-position/package.json @@ -2,7 +2,7 @@ "author": { "name": "Titus Wormer", "email": "tituswormer@gmail.com", - "url": "http://wooorm.com" + "url": "https://wooorm.com" }, "bugs": { "url": "https://github.com/syntax-tree/unist-util-remove-position/issues" @@ -12,7 +12,7 @@ { "name": "Titus Wormer", "email": "tituswormer@gmail.com", - "url": "http://wooorm.com" + "url": "https://wooorm.com" } ], "dependencies": { @@ -22,15 +22,15 @@ "description": "Remove `position`s from a unist tree", "devDependencies": { "browserify": "^16.0.0", - "esmangle": "^1.0.1", - "nyc": "^11.0.0", - "prettier": "^1.12.1", - "remark": "^9.0.0", - "remark-cli": "^5.0.0", - "remark-preset-wooorm": "^4.0.0", + "nyc": "^14.0.0", + "prettier": "^1.0.0", + "remark": "^10.0.0", + "remark-cli": "^6.0.0", + "remark-preset-wooorm": "^5.0.0", "tape": "^4.0.0", - "unist-builder": "^1.0.2", - "xo": "^0.20.0" + "tinyify": "^2.0.0", + "unist-builder": "^1.0.0", + "xo": "^0.24.0" }, "files": [ "index.js" @@ -70,22 +70,17 @@ }, "scripts": { "build": "npm run build-bundle && npm run build-mangle", - "build-bundle": "browserify index.js --bare -s unistUtilRemovePosition > unist-util-remove-position.js", - "build-mangle": "esmangle < unist-util-remove-position.js > unist-util-remove-position.min.js", - "format": "remark . -qfo && prettier --write '**/*.js' && xo --fix", + "build-bundle": "browserify . -s unistUtilRemovePosition > unist-util-remove-position.js", + "build-mangle": "browserify . -s unistUtilRemovePosition -p tinyify > unist-util-remove-position.min.js", + "format": "remark . -qfo && prettier --write \"**/*.js\" && xo --fix", "test": "npm run format && npm run build && npm run test-coverage", "test-api": "node test", "test-coverage": "nyc --reporter lcov tape test.js" }, - "version": "1.1.2", + "version": "1.1.3", "xo": { "prettier": true, "esnext": false, - "rules": { - "guard-for-in": "off", - "no-var": "off", - "prefer-arrow-callback": "off" - }, "ignores": [ "unist-util-remove-position.js" ] diff --git a/tools/node_modules/eslint/node_modules/unist-util-remove-position/readme.md b/tools/node_modules/eslint/node_modules/unist-util-remove-position/readme.md index 40ccfa1ce7e087..e79ed14b35084f 100644 --- a/tools/node_modules/eslint/node_modules/unist-util-remove-position/readme.md +++ b/tools/node_modules/eslint/node_modules/unist-util-remove-position/readme.md @@ -1,50 +1,70 @@ -# unist-util-remove-position [![Build Status][travis-badge]][travis] [![Coverage Status][codecov-badge]][codecov] +# unist-util-remove-position -Remove [`position`][position]s from a [Unist][] tree. +[![Build][build-badge]][build] +[![Coverage][coverage-badge]][coverage] +[![Downloads][downloads-badge]][downloads] +[![Size][size-badge]][size] +[![Sponsors][sponsors-badge]][collective] +[![Backers][backers-badge]][collective] +[![Chat][chat-badge]][chat] -## Installation +[**unist**][unist] utility to remove [`position`][position]s from tree. + +## Install [npm][]: -```bash +```sh npm install unist-util-remove-position ``` ## Usage -```javascript +```js var remark = require('remark') var removePosition = require('unist-util-remove-position') var tree = remark().parse('Some _emphasis_, **importance**, and `code`.') -console.dir(removePosition(tree, true), {depth: null}) +removePosition(tree, true) + +console.dir(tree, {depth: null}) ``` Yields: ```js -{ type: 'root', - children: - [ { type: 'paragraph', - children: - [ { type: 'text', value: 'Some ' }, - { type: 'emphasis', - children: [ { type: 'text', value: 'emphasis' } ] }, - { type: 'text', value: ', ' }, - { type: 'strong', - children: [ { type: 'text', value: 'importance' } ] }, - { type: 'text', value: ', and ' }, - { type: 'inlineCode', value: 'code' }, - { type: 'text', value: '.' } ] } ] } +{ + type: 'root', + children: [ + { + type: 'paragraph', + children: [ + { type: 'text', value: 'Some ' }, + { + type: 'emphasis', + children: [ { type: 'text', value: 'emphasis' } ] + }, + { type: 'text', value: ', ' }, + { + type: 'strong', + children: [ { type: 'text', value: 'importance' } ] + }, + { type: 'text', value: ', and ' }, + { type: 'inlineCode', value: 'code' }, + { type: 'text', value: '.' } + ] + } + ] +} ``` ## API ### `removePosition(node[, force])` -Remove [`position`][position]s from [`node`][node]. If `force` is given, -uses `delete`, otherwise, sets `position`s to `undefined`. +Remove [`position`][position]s from [`node`][node]. +If `force` is given, uses `delete`, otherwise, sets `position`s to `undefined`. ###### Returns @@ -52,11 +72,13 @@ The given `node`. ## Contribute -See [`contributing.md` in `syntax-tree/unist`][contributing] for ways to get +See [`contributing.md` in `syntax-tree/.github`][contributing] for ways to get started. +See [`support.md`][support] for ways to get help. -This organisation has a [Code of Conduct][coc]. By interacting with this -repository, organisation, or community you agree to abide by its terms. +This project has a [Code of Conduct][coc]. +By interacting with this repository, organisation, or community you agree to +abide by its terms. ## License @@ -64,26 +86,46 @@ repository, organisation, or community you agree to abide by its terms. -[travis-badge]: https://img.shields.io/travis/syntax-tree/unist-util-remove-position.svg +[build-badge]: https://img.shields.io/travis/syntax-tree/unist-util-remove-position.svg + +[build]: https://travis-ci.org/syntax-tree/unist-util-remove-position + +[coverage-badge]: https://img.shields.io/codecov/c/github/syntax-tree/unist-util-remove-position.svg + +[coverage]: https://codecov.io/github/syntax-tree/unist-util-remove-position + +[downloads-badge]: https://img.shields.io/npm/dm/unist-util-remove-position.svg + +[downloads]: https://www.npmjs.com/package/unist-util-remove-position + +[size-badge]: https://img.shields.io/bundlephobia/minzip/unist-util-remove-position.svg -[travis]: https://travis-ci.org/syntax-tree/unist-util-remove-position +[size]: https://bundlephobia.com/result?p=unist-util-remove-position -[codecov-badge]: https://img.shields.io/codecov/c/github/syntax-tree/unist-util-remove-position.svg +[sponsors-badge]: https://opencollective.com/unified/sponsors/badge.svg -[codecov]: https://codecov.io/github/syntax-tree/unist-util-remove-position +[backers-badge]: https://opencollective.com/unified/backers/badge.svg + +[collective]: https://opencollective.com/unified + +[chat-badge]: https://img.shields.io/badge/join%20the%20community-on%20spectrum-7b16ff.svg + +[chat]: https://spectrum.chat/unified/syntax-tree [npm]: https://docs.npmjs.com/cli/install -[license]: LICENSE +[license]: license + +[author]: https://wooorm.com -[author]: http://wooorm.com +[contributing]: https://github.com/syntax-tree/.github/blob/master/contributing.md + +[support]: https://github.com/syntax-tree/.github/blob/master/support.md + +[coc]: https://github.com/syntax-tree/.github/blob/master/code-of-conduct.md [unist]: https://github.com/syntax-tree/unist [position]: https://github.com/syntax-tree/unist#position [node]: https://github.com/syntax-tree/unist#node - -[contributing]: https://github.com/syntax-tree/unist/blob/master/contributing.md - -[coc]: https://github.com/syntax-tree/unist/blob/master/code-of-conduct.md diff --git a/tools/node_modules/eslint/node_modules/unist-util-visit-parents/index.js b/tools/node_modules/eslint/node_modules/unist-util-visit-parents/index.js index 39e5b9bafec08e..1f2270f6c99d28 100644 --- a/tools/node_modules/eslint/node_modules/unist-util-visit-parents/index.js +++ b/tools/node_modules/eslint/node_modules/unist-util-visit-parents/index.js @@ -23,18 +23,20 @@ function visitParents(tree, test, visitor, reverse) { // Visit a single node. function one(node, index, parents) { - var result + var result = [] + var subresult if (!test || is(test, node, index, parents[parents.length - 1] || null)) { - result = visitor(node, parents) + result = toResult(visitor(node, parents)) - if (result === EXIT) { + if (result[0] === EXIT) { return result } } - if (node.children && result !== SKIP) { - return all(node.children, parents.concat(node)) === EXIT ? EXIT : result + if (node.children && result[0] !== SKIP) { + subresult = toResult(all(node.children, parents.concat(node))) + return subresult[0] === EXIT ? subresult : result } return result @@ -45,18 +47,28 @@ function visitParents(tree, test, visitor, reverse) { var min = -1 var step = reverse ? -1 : 1 var index = (reverse ? children.length : min) + step - var child var result while (index > min && index < children.length) { - child = children[index] - result = child && one(child, index, parents) + result = one(children[index], index, parents) - if (result === EXIT) { + if (result[0] === EXIT) { return result } - index = typeof result === 'number' ? result : index + step + index = typeof result[1] === 'number' ? result[1] : index + step } } } + +function toResult(value) { + if (value !== null && typeof value === 'object' && 'length' in value) { + return value + } + + if (typeof value === 'number') { + return [CONTINUE, value] + } + + return [value] +} diff --git a/tools/node_modules/eslint/node_modules/unist-util-visit-parents/LICENSE b/tools/node_modules/eslint/node_modules/unist-util-visit-parents/license similarity index 100% rename from tools/node_modules/eslint/node_modules/unist-util-visit-parents/LICENSE rename to tools/node_modules/eslint/node_modules/unist-util-visit-parents/license diff --git a/tools/node_modules/eslint/node_modules/unist-util-visit-parents/package.json b/tools/node_modules/eslint/node_modules/unist-util-visit-parents/package.json index 777057ad57fd2d..bd8d72f2d4a174 100644 --- a/tools/node_modules/eslint/node_modules/unist-util-visit-parents/package.json +++ b/tools/node_modules/eslint/node_modules/unist-util-visit-parents/package.json @@ -2,7 +2,7 @@ "author": { "name": "Titus Wormer", "email": "tituswormer@gmail.com", - "url": "http://wooorm.com" + "url": "https://wooorm.com" }, "bugs": { "url": "https://github.com/syntax-tree/unist-util-visit-parents/issues" @@ -12,7 +12,7 @@ { "name": "Titus Wormer", "email": "tituswormer@gmail.com", - "url": "http://wooorm.com" + "url": "https://wooorm.com" } ], "dependencies": { @@ -22,14 +22,14 @@ "description": "Recursively walk over unist nodes, with ancestral information", "devDependencies": { "browserify": "^16.0.0", - "nyc": "^12.0.0", - "prettier": "^1.12.1", - "remark": "^9.0.0", - "remark-cli": "^5.0.0", - "remark-preset-wooorm": "^4.0.0", - "tape": "^4.5.1", - "tinyify": "^2.4.3", - "xo": "^0.21.0" + "nyc": "^14.0.0", + "prettier": "^1.0.0", + "remark": "^10.0.0", + "remark-cli": "^6.0.0", + "remark-preset-wooorm": "^5.0.0", + "tape": "^4.0.0", + "tinyify": "^2.0.0", + "xo": "^0.24.0" }, "files": [ "index.js" @@ -70,20 +70,15 @@ "build": "npm run build-bundle && npm run build-mangle", "build-bundle": "browserify index.js -s unistUtilVisitParents > unist-util-visit-parents.js", "build-mangle": "browserify index.js -s unistUtilVisitParents -p tinyify > unist-util-visit-parents.min.js", - "format": "remark . -qfo && prettier --write '**/*.js' && xo --fix", + "format": "remark . -qfo && prettier --write \"**/*.js\" && xo --fix", "test": "npm run format && npm run build && npm run test-coverage", "test-api": "node test", "test-coverage": "nyc --reporter lcov tape test.js" }, - "version": "2.0.1", + "version": "2.1.1", "xo": { "prettier": true, "esnext": false, - "rules": { - "guard-for-in": "off", - "no-var": "off", - "prefer-arrow-callback": "off" - }, "ignores": [ "unist-util-visit-parents.js" ] diff --git a/tools/node_modules/eslint/node_modules/unist-util-visit-parents/readme.md b/tools/node_modules/eslint/node_modules/unist-util-visit-parents/readme.md index 02ad0a1d726824..ec7efc7bd03402 100644 --- a/tools/node_modules/eslint/node_modules/unist-util-visit-parents/readme.md +++ b/tools/node_modules/eslint/node_modules/unist-util-visit-parents/readme.md @@ -1,18 +1,26 @@ -# unist-util-visit-parents [![Build Status][build-badge]][build-page] [![Coverage Status][coverage-badge]][coverage-page] +# unist-util-visit-parents -[Unist][] node visitor, with ancestral information. +[![Build][build-badge]][build] +[![Coverage][coverage-badge]][coverage] +[![Downloads][downloads-badge]][downloads] +[![Size][size-badge]][size] +[![Sponsors][sponsors-badge]][collective] +[![Backers][backers-badge]][collective] +[![Chat][chat-badge]][chat] -## Installation +[**unist**][unist] utility to visit nodes, with ancestral information. + +## Install [npm][]: -```bash +```sh npm install unist-util-visit-parents ``` ## Usage -```javascript +```js var remark = require('remark') var visit = require('unist-util-visit-parents') @@ -49,9 +57,9 @@ ancestral information. Optionally filtering nodes. Optionally in reverse. ###### Parameters -* `tree` ([`Node`][node]) — Tree to traverse +* `tree` ([`Node`][node]) — [Tree][] to traverse * `test` ([`Test`][is], optional) — [`is`][is]-compatible test (such as a - node type) + [type][]) * `visitor` ([Function][visitor]) — Function invoked when a node is found that passes `test` * `reverse` (`boolean`, default: `false`) — The tree is walked in [preorder][] @@ -80,20 +88,36 @@ traversed. * `node` ([`Node`][node]) — Found node * `ancestors` (`Array.`) — [Ancestor][]s of `node` -###### Returns +##### Returns + +The return value can have the following forms: + +* [`index`][index] (`number`) — Treated as a tuple of `[CONTINUE, index]` +* `action` (`*`) — Treated as a tuple of `[action]` +* `tuple` (`Array.<*>`) — List with one or two values, the first an `action`, + the second and `index`. + Note that passing a tuple only makes sense if the `action` is `SKIP`. + If the `action` is `EXIT`, that action can be returned. + If the `action` is `CONTINUE`, `index` can be returned. + +###### `action` + +An action can have the following values: * `visit.EXIT` (`false`) — Stop traversing immediately * `visit.CONTINUE` (`true`) — Continue traversing as normal (same behaviour as not returning anything) * `visit.SKIP` (`'skip'`) — Do not traverse this node’s children; continue - with the next sibling -* [`index`][index] (`number`) — Move to the sibling at `index` next (after - `node` itself is completely traversed). - Useful if mutating the tree, such as removing the node the visitor is - currently on, or any of its previous siblings (or next siblings, in case of - `reverse`) - Results less than `0` or greater than or equal to `children.length` stop - traversing the parent + with the specified index + +###### `index` + +[`index`][index] (`number`) — Move to the sibling at `index` next (after `node` +itself is completely traversed). +Useful if mutating the tree, such as removing the node the visitor is currently +on, or any of its previous siblings (or next siblings, in case of `reverse`) +Results less than `0` or greater than or equal to `children.length` stop +traversing the parent ## Related @@ -113,11 +137,13 @@ traversed. ## Contribute -See [`contributing.md` in `syntax-tree/unist`][contributing] for ways to get +See [`contributing.md` in `syntax-tree/.github`][contributing] for ways to get started. +See [`support.md`][support] for ways to get help. -This organisation has a [Code of Conduct][coc]. By interacting with this -repository, organisation, or community you agree to abide by its terms. +This project has a [Code of Conduct][coc]. +By interacting with this repository, organisation, or community you agree to +abide by its terms. ## License @@ -127,17 +153,35 @@ repository, organisation, or community you agree to abide by its terms. [build-badge]: https://img.shields.io/travis/syntax-tree/unist-util-visit-parents.svg -[build-page]: https://travis-ci.org/syntax-tree/unist-util-visit-parents +[build]: https://travis-ci.org/syntax-tree/unist-util-visit-parents [coverage-badge]: https://img.shields.io/codecov/c/github/syntax-tree/unist-util-visit-parents.svg -[coverage-page]: https://codecov.io/github/syntax-tree/unist-util-visit-parents?branch=master +[coverage]: https://codecov.io/github/syntax-tree/unist-util-visit-parents + +[downloads-badge]: https://img.shields.io/npm/dm/unist-util-visit-parents.svg + +[downloads]: https://www.npmjs.com/package/unist-util-visit-parents + +[size-badge]: https://img.shields.io/bundlephobia/minzip/unist-util-visit-parents.svg + +[size]: https://bundlephobia.com/result?p=unist-util-visit-parents + +[sponsors-badge]: https://opencollective.com/unified/sponsors/badge.svg + +[backers-badge]: https://opencollective.com/unified/backers/badge.svg + +[collective]: https://opencollective.com/unified + +[chat-badge]: https://img.shields.io/badge/join%20the%20community-on%20spectrum-7b16ff.svg + +[chat]: https://spectrum.chat/unified/syntax-tree [npm]: https://docs.npmjs.com/cli/install -[license]: LICENSE +[license]: license -[author]: http://wooorm.com +[author]: https://wooorm.com [unist]: https://github.com/syntax-tree/unist @@ -145,9 +189,11 @@ repository, organisation, or community you agree to abide by its terms. [visitor]: #next--visitornode-ancestors -[contributing]: https://github.com/syntax-tree/unist/blob/master/contributing.md +[contributing]: https://github.com/syntax-tree/.github/blob/master/contributing.md -[coc]: https://github.com/syntax-tree/unist/blob/master/code-of-conduct.md +[support]: https://github.com/syntax-tree/.github/blob/master/support.md + +[coc]: https://github.com/syntax-tree/.github/blob/master/code-of-conduct.md [is]: https://github.com/syntax-tree/unist-util-is @@ -168,3 +214,5 @@ repository, organisation, or community you agree to abide by its terms. [ancestor]: https://github.com/syntax-tree/unist#ancestor [tree]: https://github.com/syntax-tree/unist#tree + +[type]: https://github.com/syntax-tree/unist#type diff --git a/tools/node_modules/eslint/node_modules/unist-util-is/LICENSE b/tools/node_modules/eslint/node_modules/unist-util-visit/license similarity index 100% rename from tools/node_modules/eslint/node_modules/unist-util-is/LICENSE rename to tools/node_modules/eslint/node_modules/unist-util-visit/license diff --git a/tools/node_modules/eslint/node_modules/unist-util-visit/package.json b/tools/node_modules/eslint/node_modules/unist-util-visit/package.json index f420edafd25e0b..a0ef4a3cc172d3 100644 --- a/tools/node_modules/eslint/node_modules/unist-util-visit/package.json +++ b/tools/node_modules/eslint/node_modules/unist-util-visit/package.json @@ -2,7 +2,7 @@ "author": { "name": "Titus Wormer", "email": "tituswormer@gmail.com", - "url": "http://wooorm.com" + "url": "https://wooorm.com" }, "bugs": { "url": "https://github.com/syntax-tree/unist-util-visit/issues" @@ -12,7 +12,7 @@ { "name": "Titus Wormer", "email": "tituswormer@gmail.com", - "url": "http://wooorm.com" + "url": "https://wooorm.com" }, { "name": "Eugene Sharygin", @@ -30,14 +30,14 @@ "description": "Recursively walk over unist nodes", "devDependencies": { "browserify": "^16.0.0", - "nyc": "^12.0.0", - "prettier": "^1.12.1", - "remark": "^9.0.0", - "remark-cli": "^5.0.0", - "remark-preset-wooorm": "^4.0.0", - "tape": "^4.5.1", - "tinyify": "^2.4.3", - "xo": "^0.21.0" + "nyc": "^14.0.0", + "prettier": "^1.0.0", + "remark": "^10.0.0", + "remark-cli": "^6.0.0", + "remark-preset-wooorm": "^5.0.0", + "tape": "^4.0.0", + "tinyify": "^2.0.0", + "xo": "^0.24.0" }, "files": [ "index.js" @@ -85,20 +85,15 @@ "build": "npm run build-bundle && npm run build-mangle", "build-bundle": "browserify . -s unistUtilVisit > unist-util-visit.js", "build-mangle": "browserify . -s unistUtilVisit -p tinyify > unist-util-visit.min.js", - "format": "remark . -qfo && prettier --write '**/*.js' && xo --fix", + "format": "remark . -qfo && prettier --write \"**/*.js\" && xo --fix", "test": "npm run format && npm run build && npm run test-coverage", "test-api": "node test", "test-coverage": "nyc --reporter lcov tape test.js" }, - "version": "1.4.0", + "version": "1.4.1", "xo": { "prettier": true, "esnext": false, - "rules": { - "guard-for-in": "off", - "no-var": "off", - "prefer-arrow-callback": "off" - }, "ignores": [ "unist-util-visit.js" ] diff --git a/tools/node_modules/eslint/node_modules/unist-util-visit/readme.md b/tools/node_modules/eslint/node_modules/unist-util-visit/readme.md index 36fa46e3efa6a6..25808a27a543e5 100644 --- a/tools/node_modules/eslint/node_modules/unist-util-visit/readme.md +++ b/tools/node_modules/eslint/node_modules/unist-util-visit/readme.md @@ -1,9 +1,13 @@ -# unist-util-visit [![Build Status][build-badge]][build-page] [![Coverage Status][coverage-badge]][coverage-page] +# unist-util-visit -[unist][] node visitor. Useful when working with [**remark**][remark], -[**retext**][retext], or [**rehype**][rehype]. +[![Build][build-badge]][build] +[![Coverage][coverage-badge]][coverage] +[![Downloads][downloads-badge]][downloads] +[![Size][size-badge]][size] -## Installation +[**unist**][unist] utility to visit nodes. + +## Install [npm][]: @@ -14,27 +18,27 @@ npm install unist-util-visit ## Usage ```javascript -var remark = require('remark') +var u = require('unist-builder') var visit = require('unist-util-visit') -var tree = remark().parse('Some _emphasis_, **importance**, and `code`.') - -visit(tree, 'text', visitor) +var tree = u('tree', [ + u('leaf', '1'), + u('node', [u('leaf', '2')]), + u('void'), + u('leaf', '3') +]) -function visitor(node) { +visit(tree, 'leaf', function(node) { console.log(node) -} +}) ``` Yields: ```js -{type: 'text', value: 'Some '} -{type: 'text', value: 'emphasis'} -{type: 'text', value: ', '} -{type: 'text', value: 'importance'} -{type: 'text', value: ', and '} -{type: 'text', value: '.'} +{ type: 'leaf', value: '1' } +{ type: 'leaf', value: '2' } +{ type: 'leaf', value: '3' } ``` ## API @@ -66,11 +70,13 @@ Otherwise the same as [`unist-util-visit-parents`][vp]. ## Contribute -See [`contributing.md` in `syntax-tree/unist`][contributing] for ways to get +See [`contributing.md` in `syntax-tree/.github`][contributing] for ways to get started. +See [`support.md`][support] for ways to get help. -This organisation has a [Code of Conduct][coc]. By interacting with this -repository, organisation, or community you agree to abide by its terms. +This project has a [Code of Conduct][coc]. +By interacting with this repository, organisation, or community you agree to +abide by its terms. ## License @@ -80,29 +86,33 @@ repository, organisation, or community you agree to abide by its terms. [build-badge]: https://img.shields.io/travis/syntax-tree/unist-util-visit.svg -[build-page]: https://travis-ci.org/syntax-tree/unist-util-visit +[build]: https://travis-ci.org/syntax-tree/unist-util-visit [coverage-badge]: https://img.shields.io/codecov/c/github/syntax-tree/unist-util-visit.svg -[coverage-page]: https://codecov.io/github/syntax-tree/unist-util-visit?branch=master +[coverage]: https://codecov.io/github/syntax-tree/unist-util-visit -[npm]: https://docs.npmjs.com/cli/install +[downloads-badge]: https://img.shields.io/npm/dm/unist-util-visit.svg -[license]: LICENSE +[downloads]: https://www.npmjs.com/package/unist-util-visit -[author]: http://wooorm.com +[size-badge]: https://img.shields.io/bundlephobia/minzip/unist-util-visit.svg -[unist]: https://github.com/syntax-tree/unist +[size]: https://bundlephobia.com/result?p=unist-util-visit -[retext]: https://github.com/retextjs/retext +[npm]: https://docs.npmjs.com/cli/install + +[license]: license -[remark]: https://github.com/remarkjs/remark +[author]: https://wooorm.com -[rehype]: https://github.com/rehypejs/rehype +[contributing]: https://github.com/syntax-tree/.github/blob/master/contributing.md -[contributing]: https://github.com/syntax-tree/unist/blob/master/contributing.md +[support]: https://github.com/syntax-tree/.github/blob/master/support.md -[coc]: https://github.com/syntax-tree/unist/blob/master/code-of-conduct.md +[coc]: https://github.com/syntax-tree/.github/blob/master/code-of-conduct.md + +[unist]: https://github.com/syntax-tree/unist [vp]: https://github.com/syntax-tree/unist-util-visit-parents diff --git a/tools/node_modules/eslint/node_modules/vfile-location/LICENSE b/tools/node_modules/eslint/node_modules/vfile-location/license similarity index 100% rename from tools/node_modules/eslint/node_modules/vfile-location/LICENSE rename to tools/node_modules/eslint/node_modules/vfile-location/license diff --git a/tools/node_modules/eslint/node_modules/vfile-message/LICENSE b/tools/node_modules/eslint/node_modules/vfile-message/license similarity index 100% rename from tools/node_modules/eslint/node_modules/vfile-message/LICENSE rename to tools/node_modules/eslint/node_modules/vfile-message/license diff --git a/tools/node_modules/eslint/package.json b/tools/node_modules/eslint/package.json index 92267e9c4bfd21..68df20c7687b9f 100644 --- a/tools/node_modules/eslint/package.json +++ b/tools/node_modules/eslint/package.json @@ -12,7 +12,7 @@ "bundleDependencies": false, "dependencies": { "@babel/code-frame": "^7.0.0", - "ajv": "^6.9.1", + "ajv": "^6.10.0", "chalk": "^2.1.0", "cross-spawn": "^6.0.5", "debug": "^4.0.1", @@ -21,18 +21,19 @@ "eslint-scope": "^4.0.3", "eslint-utils": "^1.3.1", "eslint-visitor-keys": "^1.0.0", - "espree": "^5.0.1", + "espree": "^6.0.0-alpha.0", "esquery": "^1.0.1", "esutils": "^2.0.2", "file-entry-cache": "^5.0.1", "functional-red-black-tree": "^1.0.1", - "glob": "^7.1.2", + "glob-parent": "^3.1.0", "globals": "^11.7.0", "ignore": "^4.0.6", "import-fresh": "^3.0.0", "imurmurhash": "^0.1.4", "inquirer": "^6.2.2", - "js-yaml": "^3.13.0", + "is-glob": "^4.0.0", + "js-yaml": "^3.13.1", "json-stable-stringify-without-jsonify": "^1.0.1", "levn": "^0.3.0", "lodash": "^4.17.11", @@ -40,7 +41,6 @@ "mkdirp": "^0.5.1", "natural-compare": "^1.4.0", "optionator": "^0.8.2", - "path-is-inside": "^1.0.2", "progress": "^2.0.0", "regexpp": "^2.0.1", "semver": "^5.5.1", @@ -52,49 +52,56 @@ "deprecated": false, "description": "An AST-based pattern checker for JavaScript.", "devDependencies": { - "@babel/core": "^7.2.2", - "@babel/polyfill": "^7.2.5", - "@babel/preset-env": "^7.3.1", + "@babel/core": "^7.4.3", + "@babel/polyfill": "^7.4.3", + "@babel/preset-env": "^7.4.3", + "acorn": "^6.1.1", "babel-loader": "^8.0.5", "beefy": "^2.1.8", - "brfs": "^2.0.0", + "brfs": "^2.0.2", "chai": "^4.0.1", "cheerio": "^0.22.0", "common-tags": "^1.8.0", - "coveralls": "^3.0.1", + "coveralls": "^3.0.3", "dateformat": "^3.0.3", "ejs": "^2.6.1", + "eslint": "file:.", "eslint-config-eslint": "file:packages/eslint-config-eslint", "eslint-plugin-eslint-plugin": "^2.0.1", "eslint-plugin-internal-rules": "file:tools/internal-rules", - "eslint-plugin-node": "^8.0.0", + "eslint-plugin-node": "^9.0.0", "eslint-release": "^1.2.0", "eslump": "^2.0.0", "esprima": "^4.0.1", + "glob": "^7.1.3", "jsdoc": "^3.5.5", - "karma": "^3.1.4", + "karma": "^4.0.1", "karma-chrome-launcher": "^2.2.0", "karma-mocha": "^1.3.0", "karma-mocha-reporter": "^2.2.3", "karma-webpack": "^4.0.0-rc.6", "leche": "^2.2.3", + "lint-staged": "^8.1.5", "load-perf": "^0.2.0", - "markdownlint": "^0.12.0", - "mocha": "^5.0.5", - "mock-fs": "^4.8.0", + "markdownlint": "^0.13.0", + "markdownlint-cli": "^0.15.0", + "metro-memory-fs": "^0.53.1", + "mocha": "^6.1.2", "npm-license": "^0.3.3", "nyc": "^13.3.0", "proxyquire": "^2.0.1", - "puppeteer": "^1.12.2", + "puppeteer": "^1.14.0", + "recast": "^0.17.6", "shelljs": "^0.8.2", "sinon": "^3.3.0", "temp": "^0.9.0", "through": "^2.3.8", - "webpack": "^4.29.3", - "webpack-cli": "^3.2.3" + "webpack": "^4.29.6", + "webpack-cli": "^3.3.0", + "yorkie": "^2.0.0" }, "engines": { - "node": "^6.14.0 || ^8.10.0 || >=9.10.0" + "node": "^8.10.0 || ^10.13.0 || >=11.10.1" }, "files": [ "LICENSE", @@ -104,6 +111,9 @@ "lib", "messages" ], + "gitHooks": { + "pre-commit": "lint-staged" + }, "homepage": "https://eslint.org", "keywords": [ "ast", @@ -113,6 +123,13 @@ "espree" ], "license": "MIT", + "lint-staged": { + "*.js": [ + "eslint --fix", + "git add" + ], + "*.md": "markdownlint" + }, "main": "./lib/api.js", "name": "eslint", "repository": { @@ -135,5 +152,5 @@ "test": "node Makefile.js test", "webpack": "node Makefile.js webpack" }, - "version": "5.16.0" + "version": "6.0.0-alpha.2" } \ No newline at end of file diff --git a/tools/update-eslint.sh b/tools/update-eslint.sh index f877c0a9e48259..ca1e3299b520a2 100755 --- a/tools/update-eslint.sh +++ b/tools/update-eslint.sh @@ -13,7 +13,7 @@ mkdir eslint-tmp cd eslint-tmp npm init --yes -npm install --global-style --no-bin-links --production --no-package-lock eslint@latest +npm install --global-style --no-bin-links --production --no-package-lock eslint@next cd node_modules/eslint npm install --no-bin-links --production --no-package-lock eslint-plugin-markdown@latest