tools: update ESLint to 6.2.2

Update ESLint to 6.2.2

PR-URL: https://github.com/nodejs/node/pull/29320
Reviewed-By: Rich Trott <rtrott@gmail.com>
Reviewed-By: Daniel Bevenius <daniel.bevenius@gmail.com>
Reviewed-By: Yongsheng Zhang <zyszys98@gmail.com>
Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com>
Reviewed-By: Roman Reiss <me@silverwind.io>
This commit is contained in:
cjihrig 2019-08-25 23:54:42 -04:00
parent 0259aadc5a
commit 403dacf9ce
No known key found for this signature in database
GPG Key ID: 7434390BDBE9B9C5
85 changed files with 1694 additions and 745 deletions

11
tools/node_modules/eslint/README.md generated vendored
View File

@ -59,8 +59,6 @@ After that, you can run ESLint on any file or directory like this:
$ ./node_modules/.bin/eslint yourfile.js
```
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.
## <a name="configuration"></a>Configuration
After running `eslint --init`, you'll have a `.eslintrc` file in your directory. In it, you'll see some rules configured like this:
@ -246,6 +244,11 @@ The people who review and fix bugs and help triage issues.
<img src="https://github.com/g-plane.png?s=75" width="75" height="75"><br />
Pig Fang
</a>
</td><td align="center" valign="top" width="11%">
<a href="https://github.com/mdjermanovic">
<img src="https://github.com/mdjermanovic.png?s=75" width="75" height="75"><br />
Milos Djermanovic
</a>
</td></tr></tbody></table>
@ -258,9 +261,9 @@ The following companies, organizations, and individuals support ESLint's ongoing
<!-- NOTE: This section is autogenerated. Do not manually edit.-->
<!--sponsorsstart-->
<h3>Gold Sponsors</h3>
<p><a href="https://www.shopify.com"><img src="https://images.opencollective.com/shopify/eeb91aa/logo.png" alt="Shopify" height="96"></a> <a href="http://salesforce.com"><img src="https://images.opencollective.com/salesforce/853ecef/logo.png" alt="Salesforce" height="96"></a> <a href="https://badoo.com/team?utm_source=eslint"><img src="https://images.opencollective.com/badoo/2826a3b/logo.png" alt="Badoo" height="96"></a> <a href="https://www.airbnb.com/"><img src="https://images.opencollective.com/airbnb/001a341/logo.png" alt="Airbnb" height="96"></a> <a href="https://code.facebook.com/projects/"><img src="https://images.opencollective.com/fbopensource/fbb8a5b/logo.png" alt="Facebook Open Source" height="96"></a></p><h3>Silver Sponsors</h3>
<p><a href="https://www.shopify.com"><img src="https://images.opencollective.com/shopify/eeb91aa/logo.png" alt="Shopify" height="96"></a> <a href="http://engineering.salesforce.com"><img src="https://images.opencollective.com/salesforce/d1b37c4/logo.png" alt="Salesforce" height="96"></a> <a href="https://badoo.com/team?utm_source=eslint"><img src="https://images.opencollective.com/badoo/2826a3b/logo.png" alt="Badoo" height="96"></a> <a href="https://www.airbnb.com/"><img src="https://images.opencollective.com/airbnb/001a341/logo.png" alt="Airbnb" height="96"></a> <a href="https://code.facebook.com/projects/"><img src="https://images.opencollective.com/fbopensource/fbb8a5b/logo.png" alt="Facebook Open Source" height="96"></a></p><h3>Silver Sponsors</h3>
<p><a href="https://www.ampproject.org/"><img src="https://images.opencollective.com/amp/c8a3b25/logo.png" alt="AMP Project" height="64"></a></p><h3>Bronze Sponsors</h3>
<p><a href="https://clay.global"><img src="https://images.opencollective.com/clayglobal/2468f34/logo.png" alt="clay" height="32"></a> <a href="https://discordapp.com"><img src="https://images.opencollective.com/discordapp/7e3d9a9/logo.png" alt="Discord" height="32"></a> <a href="https://themeisle.com"><img src="https://images.opencollective.com/themeisle/logo.png" alt="ThemeIsle" height="32"></a> <a href="https://tekhattan.com"><img src="https://images.opencollective.com/tekhattan/bc73c28/logo.png" alt="TekHattan" height="32"></a> <a href="https://www.marfeel.com/"><img src="https://images.opencollective.com/marfeel/4b88e30/logo.png" alt="Marfeel" height="32"></a> <a href="http://www.firesticktricks.com"><img src="https://images.opencollective.com/fire-stick-tricks/b8fbe2c/logo.png" alt="Fire Stick Tricks" height="32"></a> <a href="https://jsheroes.io/"><img src="https://images.opencollective.com/jsheroes1/9fedf0b/logo.png" alt="JSHeroes " height="32"></a> <a href="https://faithlife.com/ref/about"><img src="https://images.opencollective.com/faithlife/534b832/logo.png" alt="Faithlife" height="32"></a></p>
<p><a href="https://www.vpsserver.com"><img src="https://images.opencollective.com/vpsservercom/logo.png" alt="VPS Server" height="32"></a> <a href="https://icons8.com"><img src="https://images.opencollective.com/icons8/0b37d14/logo.png" alt="Free Icons by Icons8" height="32"></a> <a href="https://uxplanet.org/top-ui-ux-design-agencies-user-experience-firms-8c54697e290"><img src="https://images.opencollective.com/ui-ux-design-agencies/cae5dfe/logo.png" alt="UI UX Design Agencies" height="32"></a> <a href="https://clay.global"><img src="https://images.opencollective.com/clayglobal/2468f34/logo.png" alt="clay" height="32"></a> <a href="https://discordapp.com"><img src="https://images.opencollective.com/discordapp/7e3d9a9/logo.png" alt="Discord" height="32"></a> <a href="https://themeisle.com"><img src="https://images.opencollective.com/themeisle/logo.png" alt="ThemeIsle" height="32"></a> <a href="https://tekhattan.com"><img src="https://images.opencollective.com/tekhattan/bc73c28/logo.png" alt="TekHattan" height="32"></a> <a href="https://www.marfeel.com/"><img src="https://images.opencollective.com/marfeel/4b88e30/logo.png" alt="Marfeel" height="32"></a> <a href="http://www.firesticktricks.com"><img src="https://images.opencollective.com/fire-stick-tricks/b8fbe2c/logo.png" alt="Fire Stick Tricks" height="32"></a> <a href="https://jsheroes.io/"><img src="https://images.opencollective.com/jsheroes1/9fedf0b/logo.png" alt="JSHeroes " height="32"></a></p>
<!--sponsorsend-->
## <a name="technology-sponsors"></a>Technology Sponsors

View File

@ -20,6 +20,7 @@ const baseConfigProperties = {
processor: { type: "string" },
rules: { type: "object" },
settings: { type: "object" },
noInlineConfig: { type: "boolean" },
ecmaFeatures: { type: "object" } // deprecated; logs a warning when used
};

View File

@ -10,15 +10,76 @@
const globals = require("globals");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* Get the object that has differentce.
* @param {Record<string,boolean>} current The newer object.
* @param {Record<string,boolean>} prev The older object.
* @returns {Record<string,boolean>} The difference object.
*/
function getDiff(current, prev) {
const retv = {};
for (const [key, value] of Object.entries(current)) {
if (!Object.hasOwnProperty.call(prev, key)) {
retv[key] = value;
}
}
return retv;
}
const newGlobals2015 = getDiff(globals.es2015, globals.es5); // 19 variables such as Promise, Map, ...
const newGlobals2017 = {
Atomics: false,
SharedArrayBuffer: false
};
const newGlobals2020 = {
BigInt: false,
BigInt64Array: false,
BigUint64Array: false
};
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
/** @type {Map<string, import("../lib/shared/types").Environment>} */
module.exports = new Map(Object.entries({
// Language
builtin: {
globals: globals.es5
},
es6: {
globals: newGlobals2015,
parserOptions: {
ecmaVersion: 6
}
},
es2015: {
globals: newGlobals2015,
parserOptions: {
ecmaVersion: 6
}
},
es2017: {
globals: { ...newGlobals2015, ...newGlobals2017 },
parserOptions: {
ecmaVersion: 8
}
},
es2020: {
globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020 },
parserOptions: {
ecmaVersion: 11
}
},
// Platforms
browser: {
globals: globals.browser
},
@ -30,6 +91,17 @@ module.exports = new Map(Object.entries({
}
}
},
"shared-node-browser": {
globals: globals["shared-node-browser"]
},
worker: {
globals: globals.worker
},
serviceworker: {
globals: globals.serviceworker
},
// Frameworks
commonjs: {
globals: globals.commonjs,
parserOptions: {
@ -38,12 +110,6 @@ module.exports = new Map(Object.entries({
}
}
},
"shared-node-browser": {
globals: globals["shared-node-browser"]
},
worker: {
globals: globals.worker
},
amd: {
globals: globals.amd
},
@ -86,9 +152,6 @@ module.exports = new Map(Object.entries({
nashorn: {
globals: globals.nashorn
},
serviceworker: {
globals: globals.serviceworker
},
atomtest: {
globals: globals.atomtest
},
@ -98,12 +161,6 @@ module.exports = new Map(Object.entries({
webextensions: {
globals: globals.webextensions
},
es6: {
globals: globals.es2015,
parserOptions: {
ecmaVersion: 6
}
},
greasemonkey: {
globals: globals.greasemonkey
}

View File

@ -526,6 +526,7 @@ class ConfigArrayFactory {
env,
extends: extend,
globals,
noInlineConfig,
parser: parserName,
parserOptions,
plugins: pluginList,
@ -567,6 +568,7 @@ class ConfigArrayFactory {
criteria: null,
env,
globals,
noInlineConfig,
parser,
parserOptions,
plugins,

View File

@ -54,6 +54,7 @@ const { ExtractedConfig } = require("./extracted-config");
* @property {InstanceType<OverrideTester>|null} criteria The tester for the `files` and `excludedFiles` of this config element.
* @property {Record<string, boolean>|undefined} env The environment settings.
* @property {Record<string, GlobalConf>|undefined} globals The global variable settings.
* @property {boolean|undefined} noInlineConfig The flag that disables directive comments.
* @property {DependentParser|undefined} parser The parser loader.
* @property {Object|undefined} parserOptions The parser options.
* @property {Record<string, DependentPlugin>|undefined} plugins The plugin loaders.
@ -250,6 +251,12 @@ function createConfig(instance, indices) {
config.processor = element.processor;
}
// Adopt the noInlineConfig which was found at first.
if (config.noInlineConfig === void 0 && element.noInlineConfig !== void 0) {
config.noInlineConfig = element.noInlineConfig;
config.configNameOfNoInlineConfig = element.name;
}
// Merge others.
mergeWithoutOverwrite(config.env, element.env);
mergeWithoutOverwrite(config.globals, element.globals);

View File

@ -29,6 +29,12 @@
class ExtractedConfig {
constructor() {
/**
* The config name what `noInlineConfig` setting came from.
* @type {string}
*/
this.configNameOfNoInlineConfig = "";
/**
* Environments.
* @type {Record<string, boolean>}
@ -41,6 +47,12 @@ class ExtractedConfig {
*/
this.globals = {};
/**
* The flag that disables directive comments.
* @type {boolean|undefined}
*/
this.noInlineConfig = void 0;
/**
* Parser definition.
* @type {DependentParser|null}
@ -84,7 +96,10 @@ class ExtractedConfig {
*/
toCompatibleObjectAsConfigFileContent() {
const {
processor: _ignore, // eslint-disable-line no-unused-vars
/* eslint-disable no-unused-vars */
configNameOfNoInlineConfig: _ignore1,
processor: _ignore2,
/* eslint-enable no-unused-vars */
...config
} = this;

View File

@ -135,7 +135,7 @@ function check(packages, opt) {
* Check whether node modules are included in the dependencies of a project's
* package.json.
*
* Convienience wrapper around check().
* Convenience wrapper around check().
*
* @param {string[]} packages Array of node modules to check.
* @param {string} rootDir The directory contianing a package.json
@ -150,7 +150,7 @@ function checkDeps(packages, rootDir) {
* Check whether node modules are included in the devDependencies of a project's
* package.json.
*
* Convienience wrapper around check().
* Convenience wrapper around check().
*
* @param {string[]} packages Array of node modules to check.
* @returns {Object} An object whose keys are the module names

View File

@ -526,6 +526,7 @@ function processCodePathToExit(analyzer, node) {
break;
case "CallExpression":
case "ImportExpression":
case "MemberExpression":
case "NewExpression":
state.makeFirstThrowablePathInTryBlock();

View File

@ -198,14 +198,20 @@ function createMissingRuleMessage(ruleId) {
/**
* 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.
* @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
* @param {string} [options.severity] the error message to report
* @returns {LintMessage} 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;
const {
ruleId = null,
loc = DEFAULT_ERROR_LOC,
message = createMissingRuleMessage(options.ruleId),
severity = 2
} = options;
return {
ruleId,
@ -214,7 +220,7 @@ function createLintingProblem(options) {
column: loc.start.column + 1,
endLine: loc.end.line,
endColumn: loc.end.column + 1,
severity: 2,
severity,
nodeType: null
};
}
@ -257,10 +263,11 @@ function createDisableDirectives(options) {
* @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
* @param {string|null} warnInlineConfig If a string then it should warn directive comments as disabled. The string value is the config name what the setting came from.
* @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) {
function getDirectiveComments(filename, ast, ruleMapper, warnInlineConfig) {
const configuredRules = {};
const enabledGlobals = Object.create(null);
const exportedVariables = {};
@ -269,16 +276,29 @@ function getDirectiveComments(filename, ast, ruleMapper) {
ast.comments.filter(token => token.type !== "Shebang").forEach(comment => {
const trimmedCommentText = comment.value.trim();
const match = /^(eslint(-\w+){0,3}|exported|globals?)(\s|$)/u.exec(trimmedCommentText);
const match = /^(eslint(?:-env|-enable|-disable(?:(?:-next)?-line)?)?|exported|globals?)(?:\s|$)/u.exec(trimmedCommentText);
if (!match) {
return;
}
const lineCommentSupported = /^eslint-disable-(next-)?line$/u.test(match[1]);
if (warnInlineConfig && (lineCommentSupported || comment.type === "Block")) {
const kind = comment.type === "Block" ? `/*${match[1]}*/` : `//${match[1]}`;
problems.push(createLintingProblem({
ruleId: null,
message: `'${kind}' has no effect because you have 'noInlineConfig' setting in ${warnInlineConfig}.`,
loc: comment.loc,
severity: 1
}));
return;
}
const directiveValue = trimmedCommentText.slice(match.index + match[1].length);
let directiveType = "";
if (/^eslint-disable-(next-)?line$/u.test(match[1])) {
if (lineCommentSupported) {
if (comment.loc.start.line === comment.loc.end.line) {
directiveType = match[1].slice("eslint-".length);
} else {
@ -441,16 +461,27 @@ function normalizeFilename(filename) {
return index === -1 ? filename : parts.slice(index).join(path.sep);
}
// eslint-disable-next-line valid-jsdoc
/**
* Normalizes the possible options for `linter.verify` and `linter.verifyAndFix` to a
* consistent shape.
* @param {VerifyOptions} providedOptions Options
* @returns {Required<VerifyOptions>} Normalized options
* @param {ConfigData} config Config.
* @returns {Required<VerifyOptions> & { warnInlineConfig: string|null }} Normalized options
*/
function normalizeVerifyOptions(providedOptions) {
function normalizeVerifyOptions(providedOptions, config) {
const disableInlineConfig = config.noInlineConfig === true;
const ignoreInlineConfig = providedOptions.allowInlineConfig === false;
const configNameOfNoInlineConfig = config.configNameOfNoInlineConfig
? ` (${config.configNameOfNoInlineConfig})`
: "";
return {
filename: normalizeFilename(providedOptions.filename || "<input>"),
allowInlineConfig: providedOptions.allowInlineConfig !== false,
allowInlineConfig: !ignoreInlineConfig,
warnInlineConfig: disableInlineConfig && !ignoreInlineConfig
? `your config${configNameOfNoInlineConfig}`
: null,
reportUnusedDisableDirectives: Boolean(providedOptions.reportUnusedDisableDirectives),
disableFixes: Boolean(providedOptions.disableFixes)
};
@ -984,7 +1015,7 @@ class Linter {
_verifyWithoutProcessors(textOrSourceCode, providedConfig, providedOptions) {
const slots = internalSlotsMap.get(this);
const config = providedConfig || {};
const options = normalizeVerifyOptions(providedOptions);
const options = normalizeVerifyOptions(providedOptions, config);
let text;
// evaluate arguments
@ -1019,7 +1050,9 @@ class Linter {
}
// search and apply "eslint-env *".
const envInFile = findEslintEnv(text);
const envInFile = options.allowInlineConfig && !options.warnInlineConfig
? findEslintEnv(text)
: {};
const resolvedEnvConfig = Object.assign({ builtin: true }, config.env, envInFile);
const enabledEnvs = Object.keys(resolvedEnvConfig)
.filter(envName => resolvedEnvConfig[envName])
@ -1062,7 +1095,7 @@ class Linter {
const sourceCode = slots.lastSourceCode;
const commentDirectives = options.allowInlineConfig
? getDirectiveComments(options.filename, sourceCode.ast, ruleId => getRule(slots, ruleId))
? getDirectiveComments(options.filename, sourceCode.ast, ruleId => getRule(slots, ruleId), options.warnInlineConfig)
: { configuredRules: {}, enabledGlobals: {}, exportedVariables: {}, problems: [], disableDirectives: [] };
// augment global scope with declared global variables

View File

@ -5,10 +5,87 @@
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const astUtils = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Typedefs
//------------------------------------------------------------------------------
/**
* Property name if it can be computed statically, otherwise the list of the tokens of the key node.
* @typedef {string|Token[]} Key
*/
/**
* Accessor nodes with the same key.
* @typedef {Object} AccessorData
* @property {Key} key Accessor's key
* @property {ASTNode[]} getters List of getter nodes.
* @property {ASTNode[]} setters List of setter nodes.
*/
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* Checks whether or not the given lists represent the equal tokens in the same order.
* Tokens are compared by their properties, not by instance.
* @param {Token[]} left First list of tokens.
* @param {Token[]} right Second list of tokens.
* @returns {boolean} `true` if the lists have same tokens.
*/
function areEqualTokenLists(left, right) {
if (left.length !== right.length) {
return false;
}
for (let i = 0; i < left.length; i++) {
const leftToken = left[i],
rightToken = right[i];
if (leftToken.type !== rightToken.type || leftToken.value !== rightToken.value) {
return false;
}
}
return true;
}
/**
* Checks whether or not the given keys are equal.
* @param {Key} left First key.
* @param {Key} right Second key.
* @returns {boolean} `true` if the keys are equal.
*/
function areEqualKeys(left, right) {
if (typeof left === "string" && typeof right === "string") {
// Statically computed names.
return left === right;
}
if (Array.isArray(left) && Array.isArray(right)) {
// Token lists.
return areEqualTokenLists(left, right);
}
return false;
}
/**
* Checks whether or not a given node is of an accessor kind ('get' or 'set').
* @param {ASTNode} node - A node to check.
* @returns {boolean} `true` if the node is of an accessor kind.
*/
function isAccessorKind(node) {
return node.kind === "get" || node.kind === "set";
}
/**
* Checks whether or not a given node is an `Identifier` node which was named a given name.
* @param {ASTNode} node - A node to check.
@ -97,69 +174,152 @@ module.exports = {
}],
messages: {
getter: "Getter is not present.",
setter: "Setter is not present."
missingGetterInPropertyDescriptor: "Getter is not present in property descriptor.",
missingSetterInPropertyDescriptor: "Setter is not present in property descriptor.",
missingGetterInObjectLiteral: "Getter is not present for {{ name }}.",
missingSetterInObjectLiteral: "Setter is not present for {{ name }}."
}
},
create(context) {
const config = context.options[0] || {};
const checkGetWithoutSet = config.getWithoutSet === true;
const checkSetWithoutGet = config.setWithoutGet !== false;
const sourceCode = context.getSourceCode();
/**
* Checks a object expression to see if it has setter and getter both present or none.
* @param {ASTNode} node The node to check.
* Reports the given node.
* @param {ASTNode} node The node to report.
* @param {string} messageKind "missingGetter" or "missingSetter".
* @returns {void}
* @private
*/
function checkLonelySetGet(node) {
let isSetPresent = false;
let isGetPresent = false;
const isDescriptor = isPropertyDescriptor(node);
function report(node, messageKind) {
if (node.type === "Property") {
context.report({
node,
messageId: `${messageKind}InObjectLiteral`,
loc: astUtils.getFunctionHeadLoc(node.value, sourceCode),
data: { name: astUtils.getFunctionNameWithKind(node.value) }
});
} else {
context.report({
node,
messageId: `${messageKind}InPropertyDescriptor`
});
}
}
for (let i = 0, end = node.properties.length; i < end; i++) {
const property = node.properties[i];
/**
* Reports each of the nodes in the given list using the same messageId.
* @param {ASTNode[]} nodes Nodes to report.
* @param {string} messageKind "missingGetter" or "missingSetter".
* @returns {void}
* @private
*/
function reportList(nodes, messageKind) {
for (const node of nodes) {
report(node, messageKind);
}
}
let propToCheck = "";
/**
* Creates a new `AccessorData` object for the given getter or setter node.
* @param {ASTNode} node A getter or setter node.
* @returns {AccessorData} New `AccessorData` object that contains the given node.
* @private
*/
function createAccessorData(node) {
const name = astUtils.getStaticPropertyName(node);
const key = (name !== null) ? name : sourceCode.getTokens(node.key);
if (property.kind === "init") {
if (isDescriptor && !property.computed) {
propToCheck = property.key.name;
}
} else {
propToCheck = property.kind;
}
return {
key,
getters: node.kind === "get" ? [node] : [],
setters: node.kind === "set" ? [node] : []
};
}
switch (propToCheck) {
case "set":
isSetPresent = true;
break;
/**
* Merges the given `AccessorData` object into the given accessors list.
* @param {AccessorData[]} accessors The list to merge into.
* @param {AccessorData} accessorData The object to merge.
* @returns {AccessorData[]} The same instance with the merged object.
* @private
*/
function mergeAccessorData(accessors, accessorData) {
const equalKeyElement = accessors.find(a => areEqualKeys(a.key, accessorData.key));
case "get":
isGetPresent = true;
break;
default:
// Do nothing
}
if (isSetPresent && isGetPresent) {
break;
}
if (equalKeyElement) {
equalKeyElement.getters.push(...accessorData.getters);
equalKeyElement.setters.push(...accessorData.setters);
} else {
accessors.push(accessorData);
}
if (checkSetWithoutGet && isSetPresent && !isGetPresent) {
context.report({ node, messageId: "getter" });
} else if (checkGetWithoutSet && isGetPresent && !isSetPresent) {
context.report({ node, messageId: "setter" });
return accessors;
}
/**
* Checks accessor pairs in the given list of nodes.
* @param {ASTNode[]} nodes The list to check.
* @returns {void}
* @private
*/
function checkList(nodes) {
const accessors = nodes
.filter(isAccessorKind)
.map(createAccessorData)
.reduce(mergeAccessorData, []);
for (const { getters, setters } of accessors) {
if (checkSetWithoutGet && setters.length && !getters.length) {
reportList(setters, "missingGetter");
}
if (checkGetWithoutSet && getters.length && !setters.length) {
reportList(getters, "missingSetter");
}
}
}
/**
* Checks accessor pairs in an object literal.
* @param {ASTNode} node `ObjectExpression` node to check.
* @returns {void}
* @private
*/
function checkObjectLiteral(node) {
checkList(node.properties.filter(p => p.type === "Property"));
}
/**
* Checks accessor pairs in a property descriptor.
* @param {ASTNode} node Property descriptor `ObjectExpression` node to check.
* @returns {void}
* @private
*/
function checkPropertyDescriptor(node) {
const namesToCheck = node.properties
.filter(p => p.type === "Property" && p.kind === "init" && !p.computed)
.map(({ key }) => key.name);
const hasGetter = namesToCheck.includes("get");
const hasSetter = namesToCheck.includes("set");
if (checkSetWithoutGet && hasSetter && !hasGetter) {
report(node, "missingGetter");
}
if (checkGetWithoutSet && hasGetter && !hasSetter) {
report(node, "missingSetter");
}
}
return {
ObjectExpression(node) {
if (checkSetWithoutGet || checkGetWithoutSet) {
checkLonelySetGet(node);
checkObjectLiteral(node);
if (isPropertyDescriptor(node)) {
checkPropertyDescriptor(node);
}
}
}
};

View File

@ -5,6 +5,12 @@
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const astUtils = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
@ -34,7 +40,7 @@ module.exports = {
}],
messages: {
missingThis: "Expected 'this' to be used by class method '{{name}}'."
missingThis: "Expected 'this' to be used by class {{name}}."
}
},
create(context) {
@ -70,7 +76,8 @@ module.exports = {
* @private
*/
function isIncludedInstanceMethod(node) {
return isInstanceMethod(node) && !exceptMethods.has(node.key.name);
return isInstanceMethod(node) &&
(node.computed || !exceptMethods.has(node.key.name));
}
/**
@ -89,7 +96,7 @@ module.exports = {
node,
messageId: "missingThis",
data: {
name: node.parent.key.name
name: astUtils.getFunctionNameWithKind(node)
}
});
}

View File

@ -9,13 +9,16 @@
//------------------------------------------------------------------------------
const astUtils = require("./utils/ast-utils");
const keywords = require("./utils/keywords");
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
const validIdentifier = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/u;
const keywords = require("./utils/keywords");
// `null` literal must be handled separately.
const literalTypesToCheck = new Set(["string", "boolean"]);
module.exports = {
meta: {
@ -115,7 +118,8 @@ module.exports = {
MemberExpression(node) {
if (
node.computed &&
node.property.type === "Literal"
node.property.type === "Literal" &&
(literalTypesToCheck.has(typeof node.property.value) || astUtils.isNullLiteral(node.property))
) {
checkComputedProperty(node, node.property.value);
}

View File

@ -78,21 +78,13 @@ module.exports = {
/**
* Check if open space is present in a function name
* @param {ASTNode} node node to evaluate
* @param {Token} leftToken The last token of the callee. This may be the closing parenthesis that encloses the callee.
* @param {Token} rightToken Tha first token of the arguments. this is the opening parenthesis that encloses the arguments.
* @returns {void}
* @private
*/
function checkSpacing(node) {
const lastToken = sourceCode.getLastToken(node);
const lastCalleeToken = sourceCode.getLastToken(node.callee);
const parenToken = sourceCode.getFirstTokenBetween(lastCalleeToken, lastToken, astUtils.isOpeningParenToken);
const prevToken = parenToken && sourceCode.getTokenBefore(parenToken);
// Parens in NewExpression are optional
if (!(parenToken && parenToken.range[1] < node.range[1])) {
return;
}
const textBetweenTokens = text.slice(prevToken.range[1], parenToken.range[0]).replace(/\/\*.*?\*\//gu, "");
function checkSpacing(node, leftToken, rightToken) {
const textBetweenTokens = text.slice(leftToken.range[1], rightToken.range[0]).replace(/\/\*.*?\*\//gu, "");
const hasWhitespace = /\s/u.test(textBetweenTokens);
const hasNewline = hasWhitespace && astUtils.LINEBREAK_MATCHER.test(textBetweenTokens);
@ -123,7 +115,7 @@ module.exports = {
if (never && hasWhitespace) {
context.report({
node,
loc: lastCalleeToken.loc.start,
loc: leftToken.loc.start,
messageId: "unexpected",
fix(fixer) {
@ -132,7 +124,7 @@ module.exports = {
* https://github.com/eslint/eslint/issues/7787
*/
if (!hasNewline) {
return fixer.removeRange([prevToken.range[1], parenToken.range[0]]);
return fixer.removeRange([leftToken.range[1], rightToken.range[0]]);
}
return null;
@ -141,27 +133,45 @@ module.exports = {
} else if (!never && !hasWhitespace) {
context.report({
node,
loc: lastCalleeToken.loc.start,
loc: leftToken.loc.start,
messageId: "missing",
fix(fixer) {
return fixer.insertTextBefore(parenToken, " ");
return fixer.insertTextBefore(rightToken, " ");
}
});
} else if (!never && !allowNewlines && hasNewline) {
context.report({
node,
loc: lastCalleeToken.loc.start,
loc: leftToken.loc.start,
messageId: "unexpected",
fix(fixer) {
return fixer.replaceTextRange([prevToken.range[1], parenToken.range[0]], " ");
return fixer.replaceTextRange([leftToken.range[1], rightToken.range[0]], " ");
}
});
}
}
return {
CallExpression: checkSpacing,
NewExpression: checkSpacing
"CallExpression, NewExpression"(node) {
const lastToken = sourceCode.getLastToken(node);
const lastCalleeToken = sourceCode.getLastToken(node.callee);
const parenToken = sourceCode.getFirstTokenBetween(lastCalleeToken, lastToken, astUtils.isOpeningParenToken);
const prevToken = parenToken && sourceCode.getTokenBefore(parenToken);
// Parens in NewExpression are optional
if (!(parenToken && parenToken.range[1] < node.range[1])) {
return;
}
checkSpacing(node, prevToken, parenToken);
},
ImportExpression(node) {
const leftToken = sourceCode.getFirstToken(node);
const rightToken = sourceCode.getTokenAfter(leftToken);
checkSpacing(node, leftToken, rightToken);
}
};
}

View File

@ -69,6 +69,8 @@ module.exports = {
create(context) {
const sourceCode = context.getSourceCode();
/**
* Returns the config option for the given node.
* @param {ASTNode} node - A node to get the config for.
@ -130,6 +132,7 @@ module.exports = {
context.report({
node,
messageId: "unnamed",
loc: astUtils.getFunctionHeadLoc(node, sourceCode),
data: { name: astUtils.getFunctionNameWithKind(node) }
});
}
@ -143,6 +146,7 @@ module.exports = {
context.report({
node,
messageId: "named",
loc: astUtils.getFunctionHeadLoc(node, sourceCode),
data: { name: astUtils.getFunctionNameWithKind(node) }
});
}

View File

@ -0,0 +1,120 @@
/**
* @fileoverview Rule to enforce line breaks between arguments of a function call
* @author Alexey Gonchar <https://github.com/finico>
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = {
meta: {
type: "layout",
docs: {
description: "enforce line breaks between arguments of a function call",
category: "Stylistic Issues",
recommended: false,
url: "https://eslint.org/docs/rules/function-call-argument-newline"
},
fixable: "whitespace",
schema: [
{
enum: ["always", "never", "consistent"]
}
],
messages: {
unexpectedLineBreak: "There should be no line break here.",
missingLineBreak: "There should be a line break after this argument."
}
},
create(context) {
const sourceCode = context.getSourceCode();
const checkers = {
unexpected: {
messageId: "unexpectedLineBreak",
check: (prevToken, currentToken) => prevToken.loc.start.line !== currentToken.loc.start.line,
createFix: (token, tokenBefore) => fixer =>
fixer.replaceTextRange([tokenBefore.range[1], token.range[0]], " ")
},
missing: {
messageId: "missingLineBreak",
check: (prevToken, currentToken) => prevToken.loc.start.line === currentToken.loc.start.line,
createFix: (token, tokenBefore) => fixer =>
fixer.replaceTextRange([tokenBefore.range[1], token.range[0]], "\n")
}
};
/**
* Check all arguments for line breaks in the CallExpression
* @param {CallExpression} node node to evaluate
* @param {{ messageId: string, check: Function }} checker selected checker
* @returns {void}
* @private
*/
function checkArguments(node, checker) {
for (let i = 1; i < node.arguments.length; i++) {
const prevArgToken = sourceCode.getFirstToken(node.arguments[i - 1]);
const currentArgToken = sourceCode.getFirstToken(node.arguments[i]);
if (checker.check(prevArgToken, currentArgToken)) {
const tokenBefore = sourceCode.getTokenBefore(
currentArgToken,
{ includeComments: true }
);
context.report({
node,
loc: {
start: tokenBefore.loc.end,
end: currentArgToken.loc.start
},
messageId: checker.messageId,
fix: checker.createFix(currentArgToken, tokenBefore)
});
}
}
}
/**
* Check if open space is present in a function name
* @param {CallExpression} node node to evaluate
* @returns {void}
* @private
*/
function check(node) {
if (node.arguments.length < 2) {
return;
}
const option = context.options[0] || "always";
if (option === "never") {
checkArguments(node, checkers.unexpected);
} else if (option === "always") {
checkArguments(node, checkers.missing);
} else if (option === "consistent") {
const firstArgToken = sourceCode.getFirstToken(node.arguments[0]);
const secondArgToken = sourceCode.getFirstToken(node.arguments[1]);
if (firstArgToken.loc.start.line === secondArgToken.loc.start.line) {
checkArguments(node, checkers.unexpected);
} else {
checkArguments(node, checkers.missing);
}
}
}
return {
CallExpression: check,
NewExpression: check
};
}
};

View File

@ -232,38 +232,50 @@ module.exports = {
};
}
case "ImportExpression": {
const leftParen = sourceCode.getFirstToken(node, 1);
const rightParen = sourceCode.getLastToken(node);
return { leftParen, rightParen };
}
default:
throw new TypeError(`unexpected node with type ${node.type}`);
}
}
/**
* Validates the parentheses for a node
* @param {ASTNode} node The node with parens
* @returns {void}
*/
function validateNode(node) {
const parens = getParenTokens(node);
if (parens) {
validateParens(parens, astUtils.isFunction(node) ? node.params : node.arguments);
if (multilineArgumentsOption) {
validateArguments(parens, astUtils.isFunction(node) ? node.params : node.arguments);
}
}
}
//----------------------------------------------------------------------
// Public
//----------------------------------------------------------------------
return {
ArrowFunctionExpression: validateNode,
CallExpression: validateNode,
FunctionDeclaration: validateNode,
FunctionExpression: validateNode,
NewExpression: validateNode
[[
"ArrowFunctionExpression",
"CallExpression",
"FunctionDeclaration",
"FunctionExpression",
"ImportExpression",
"NewExpression"
]](node) {
const parens = getParenTokens(node);
let params;
if (node.type === "ImportExpression") {
params = [node.source];
} else if (astUtils.isFunction(node)) {
params = node.params;
} else {
params = node.arguments;
}
if (parens) {
validateParens(parens, params);
if (multilineArgumentsOption) {
validateArguments(parens, params);
}
}
}
};
}
};

View File

@ -99,7 +99,8 @@ const KNOWN_NODES = new Set([
"ImportDeclaration",
"ImportSpecifier",
"ImportDefaultSpecifier",
"ImportNamespaceSpecifier"
"ImportNamespaceSpecifier",
"ImportExpression"
]);
/*
@ -1109,7 +1110,6 @@ module.exports = {
CallExpression: addFunctionCallIndent,
"ClassDeclaration[superClass], ClassExpression[superClass]"(node) {
const classToken = sourceCode.getFirstToken(node);
const extendsToken = sourceCode.getTokenBefore(node.superClass, astUtils.isNotOpeningParenToken);
@ -1236,6 +1236,17 @@ module.exports = {
}
},
ImportExpression(node) {
const openingParen = sourceCode.getFirstToken(node, 1);
const closingParen = sourceCode.getLastToken(node);
parameterParens.add(openingParen);
parameterParens.add(closingParen);
offsets.setDesiredOffset(openingParen, sourceCode.getTokenBefore(openingParen), 0);
addElementListIndent([node.source], openingParen, closingParen, options.CallExpression.arguments);
},
"MemberExpression, JSXMemberExpression, MetaProperty"(node) {
const object = node.type === "MetaProperty" ? node.meta : node.object;
const firstNonObjectToken = sourceCode.getFirstTokenBetween(object, node.property, astUtils.isNotClosingParenToken);

View File

@ -46,6 +46,7 @@ module.exports = new LazyLoadingRuleMap(Object.entries({
"func-name-matching": () => require("./func-name-matching"),
"func-names": () => require("./func-names"),
"func-style": () => require("./func-style"),
"function-call-argument-newline": () => require("./function-call-argument-newline"),
"function-paren-newline": () => require("./function-paren-newline"),
"generator-star-spacing": () => require("./generator-star-spacing"),
"getter-return": () => require("./getter-return"),

View File

@ -23,7 +23,8 @@ const CAPS_ALLOWED = [
"Object",
"RegExp",
"String",
"Symbol"
"Symbol",
"BigInt"
];
/**

View File

@ -120,7 +120,7 @@ module.exports = {
}
// Skip if the name is not static.
if (!name) {
if (name === null) {
return;
}

View File

@ -33,17 +33,19 @@ module.exports = {
return {
SwitchStatement(node) {
const mapping = {};
const previousKeys = new Set();
node.cases.forEach(switchCase => {
const key = sourceCode.getText(switchCase.test);
for (const switchCase of node.cases) {
if (switchCase.test) {
const key = sourceCode.getText(switchCase.test);
if (mapping[key]) {
context.report({ node: switchCase, messageId: "unexpected" });
} else {
mapping[key] = switchCase;
if (previousKeys.has(key)) {
context.report({ node: switchCase, messageId: "unexpected" });
} else {
previousKeys.add(key);
}
}
});
}
}
};
}

View File

@ -98,6 +98,7 @@ module.exports = {
grandparent.type === "CallExpression" &&
grandparent.callee === parent &&
grandparent.arguments.length === 1 &&
grandparent.arguments[0].type !== "SpreadElement" &&
parent.type === "MemberExpression" &&
parent.object === node &&
astUtils.getStaticPropertyName(parent) === "bind"

View File

@ -50,8 +50,8 @@ module.exports = {
/**
* Check if a node is in a context where its value would be coerced to a boolean at runtime.
*
* @param {Object} node The node
* @param {Object} parent Its parent
* @param {ASTNode} node The node
* @param {ASTNode} parent Its parent
* @returns {boolean} If it is in a boolean context
*/
function isInBooleanContext(node, parent) {
@ -65,6 +65,15 @@ module.exports = {
);
}
/**
* Check if a node has comments inside.
*
* @param {ASTNode} node The node to check.
* @returns {boolean} `true` if it has comments inside.
*/
function hasCommentsInside(node) {
return Boolean(sourceCode.getCommentsInside(node).length);
}
return {
UnaryExpression(node) {
@ -89,7 +98,12 @@ module.exports = {
context.report({
node,
messageId: "unexpectedNegation",
fix: fixer => fixer.replaceText(parent, sourceCode.getText(node.argument))
fix: fixer => {
if (hasCommentsInside(parent)) {
return null;
}
return fixer.replaceText(parent, sourceCode.getText(node.argument));
}
});
}
},
@ -106,10 +120,35 @@ module.exports = {
messageId: "unexpectedCall",
fix: fixer => {
if (!node.arguments.length) {
return fixer.replaceText(parent, "true");
if (parent.type === "UnaryExpression" && parent.operator === "!") {
// !Boolean() -> true
if (hasCommentsInside(parent)) {
return null;
}
const replacement = "true";
let prefix = "";
const tokenBefore = sourceCode.getTokenBefore(parent);
if (tokenBefore && tokenBefore.range[1] === parent.range[0] &&
!astUtils.canTokensBeAdjacent(tokenBefore, replacement)) {
prefix = " ";
}
return fixer.replaceText(parent, prefix + replacement);
}
// Boolean() -> false
if (hasCommentsInside(node)) {
return null;
}
return fixer.replaceText(node, "false");
}
if (node.arguments.length > 1 || node.arguments[0].type === "SpreadElement") {
if (node.arguments.length > 1 || node.arguments[0].type === "SpreadElement" ||
hasCommentsInside(node)) {
return null;
}

View File

@ -8,6 +8,7 @@
// Rule Definition
//------------------------------------------------------------------------------
const { isParenthesized: isParenthesizedRaw } = require("eslint-utils");
const astUtils = require("./utils/ast-utils.js");
module.exports = {
@ -68,7 +69,6 @@ module.exports = {
const sourceCode = context.getSourceCode();
const tokensToIgnore = new WeakSet();
const isParenthesised = astUtils.isParenthesised.bind(astUtils, sourceCode);
const precedence = astUtils.getPrecedence;
const ALL_NODES = context.options[0] !== "functions";
const EXCEPT_COND_ASSIGN = ALL_NODES && context.options[1] && context.options[1].conditionalAssign === false;
@ -118,6 +118,16 @@ module.exports = {
return ALL_NODES || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression";
}
/**
* Determines if a node is surrounded by parentheses.
* @param {ASTNode} node - The node to be checked.
* @returns {boolean} True if the node is parenthesised.
* @private
*/
function isParenthesised(node) {
return isParenthesizedRaw(1, node, sourceCode);
}
/**
* Determines if a node is surrounded by parentheses twice.
* @param {ASTNode} node - The node to be checked.
@ -125,12 +135,7 @@ module.exports = {
* @private
*/
function isParenthesisedTwice(node) {
const previousToken = sourceCode.getTokenBefore(node, 1),
nextToken = sourceCode.getTokenAfter(node, 1);
return isParenthesised(node) && previousToken && nextToken &&
astUtils.isOpeningParenToken(previousToken) && previousToken.range[1] <= node.range[0] &&
astUtils.isClosingParenToken(nextToken) && nextToken.range[0] >= node.range[1];
return isParenthesizedRaw(2, node, sourceCode);
}
/**
@ -406,15 +411,9 @@ module.exports = {
report(node.callee);
}
}
if (node.arguments.length === 1) {
if (hasDoubleExcessParens(node.arguments[0]) && precedence(node.arguments[0]) >= PRECEDENCE_OF_ASSIGNMENT_EXPR) {
report(node.arguments[0]);
}
} else {
node.arguments
.filter(arg => hasExcessParens(arg) && precedence(arg) >= PRECEDENCE_OF_ASSIGNMENT_EXPR)
.forEach(report);
}
node.arguments
.filter(arg => hasExcessParens(arg) && precedence(arg) >= PRECEDENCE_OF_ASSIGNMENT_EXPR)
.forEach(report);
}
/**
@ -686,6 +685,13 @@ module.exports = {
CallExpression: checkCallNew,
ClassBody(node) {
node.body
.filter(member => member.type === "MethodDefinition" && member.computed &&
member.key && hasExcessParens(member.key) && precedence(member.key) >= PRECEDENCE_OF_ASSIGNMENT_EXPR)
.forEach(member => report(member.key));
},
ConditionalExpression(node) {
if (isReturnAssignException(node)) {
return;
@ -705,7 +711,7 @@ module.exports = {
},
DoWhileStatement(node) {
if (hasDoubleExcessParens(node.test) && !isCondAssignException(node)) {
if (hasExcessParens(node.test) && !isCondAssignException(node)) {
report(node.test);
}
},
@ -830,11 +836,23 @@ module.exports = {
},
IfStatement(node) {
if (hasDoubleExcessParens(node.test) && !isCondAssignException(node)) {
if (hasExcessParens(node.test) && !isCondAssignException(node)) {
report(node.test);
}
},
ImportExpression(node) {
const { source } = node;
if (source.type === "SequenceExpression") {
if (hasDoubleExcessParens(source)) {
report(source);
}
} else if (hasExcessParens(source)) {
report(source);
}
},
LogicalExpression: checkBinaryLogical,
MemberExpression(node) {
@ -917,7 +935,7 @@ module.exports = {
},
SwitchStatement(node) {
if (hasDoubleExcessParens(node.discriminant)) {
if (hasExcessParens(node.discriminant)) {
report(node.discriminant);
}
},
@ -945,13 +963,13 @@ module.exports = {
},
WhileStatement(node) {
if (hasDoubleExcessParens(node.test) && !isCondAssignException(node)) {
if (hasExcessParens(node.test) && !isCondAssignException(node)) {
report(node.test);
}
},
WithStatement(node) {
if (hasDoubleExcessParens(node.object)) {
if (hasExcessParens(node.object)) {
report(node.object);
}
},
@ -973,7 +991,21 @@ module.exports = {
SpreadElement: checkSpreadOperator,
SpreadProperty: checkSpreadOperator,
ExperimentalSpreadProperty: checkSpreadOperator
ExperimentalSpreadProperty: checkSpreadOperator,
TemplateLiteral(node) {
node.expressions
.filter(e => e && hasExcessParens(e))
.forEach(report);
},
AssignmentPattern(node) {
const { right } = node;
if (right && hasExcessParens(right) && precedence(right) >= PRECEDENCE_OF_ASSIGNMENT_EXPR) {
report(right);
}
}
};
}

View File

@ -20,12 +20,14 @@ const BITWISE_OPERATORS = ["&", "|", "^", "~", "<<", ">>", ">>>"];
const COMPARISON_OPERATORS = ["==", "!=", "===", "!==", ">", ">=", "<", "<="];
const LOGICAL_OPERATORS = ["&&", "||"];
const RELATIONAL_OPERATORS = ["in", "instanceof"];
const TERNARY_OPERATOR = ["?:"];
const ALL_OPERATORS = [].concat(
ARITHMETIC_OPERATORS,
BITWISE_OPERATORS,
COMPARISON_OPERATORS,
LOGICAL_OPERATORS,
RELATIONAL_OPERATORS
RELATIONAL_OPERATORS,
TERNARY_OPERATOR
);
const DEFAULT_GROUPS = [
ARITHMETIC_OPERATORS,
@ -34,7 +36,7 @@ const DEFAULT_GROUPS = [
LOGICAL_OPERATORS,
RELATIONAL_OPERATORS
];
const TARGET_NODE_TYPE = /^(?:Binary|Logical)Expression$/u;
const TARGET_NODE_TYPE = /^(?:Binary|Logical|Conditional)Expression$/u;
/**
* Normalizes options.
@ -65,6 +67,18 @@ function includesBothInAGroup(groups, left, right) {
return groups.some(group => group.indexOf(left) !== -1 && group.indexOf(right) !== -1);
}
/**
* Checks whether the given node is a conditional expression and returns the test node else the left node.
*
* @param {ASTNode} node - A node which can be a BinaryExpression or a LogicalExpression node.
* This parent node can be BinaryExpression, LogicalExpression
* , or a ConditionalExpression node
* @returns {ASTNode} node the appropriate node(left or test).
*/
function getChildNode(node) {
return node.type === "ConditionalExpression" ? node.test : node.left;
}
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
@ -121,7 +135,7 @@ module.exports = {
const b = node.parent;
return (
!includesBothInAGroup(options.groups, a.operator, b.operator) ||
!includesBothInAGroup(options.groups, a.operator, b.type === "ConditionalExpression" ? "?:" : b.operator) ||
(
options.allowSamePrecedence &&
astUtils.getPrecedence(a) === astUtils.getPrecedence(b)
@ -139,12 +153,25 @@ module.exports = {
* @returns {boolean} `true` if the node was mixed.
*/
function isMixedWithParent(node) {
return (
node.operator !== node.parent.operator &&
!astUtils.isParenthesised(sourceCode, node)
);
}
/**
* Checks whether the operator of a given node is mixed with a
* conditional expression.
*
* @param {ASTNode} node - A node to check. This is a conditional
* expression node
* @returns {boolean} `true` if the node was mixed.
*/
function isMixedWithConditionalParent(node) {
return !astUtils.isParenthesised(sourceCode, node) && !astUtils.isParenthesised(sourceCode, node.test);
}
/**
* Gets the operator token of a given node.
*
@ -153,7 +180,7 @@ module.exports = {
* @returns {Token} The operator token of the node.
*/
function getOperatorToken(node) {
return sourceCode.getTokenAfter(node.left, astUtils.isNotClosingParenToken);
return sourceCode.getTokenAfter(getChildNode(node), astUtils.isNotClosingParenToken);
}
/**
@ -167,13 +194,13 @@ module.exports = {
*/
function reportBothOperators(node) {
const parent = node.parent;
const left = (parent.left === node) ? node : parent;
const right = (parent.left !== node) ? node : parent;
const left = (getChildNode(parent) === node) ? node : parent;
const right = (getChildNode(parent) !== node) ? node : parent;
const message =
"Unexpected mix of '{{leftOperator}}' and '{{rightOperator}}'.";
const data = {
leftOperator: left.operator,
rightOperator: right.operator
leftOperator: left.operator || "?:",
rightOperator: right.operator || "?:"
};
context.report({
@ -198,17 +225,25 @@ module.exports = {
* @returns {void}
*/
function check(node) {
if (TARGET_NODE_TYPE.test(node.parent.type) &&
isMixedWithParent(node) &&
!shouldIgnore(node)
) {
reportBothOperators(node);
if (TARGET_NODE_TYPE.test(node.parent.type)) {
if (node.parent.type === "ConditionalExpression" && !shouldIgnore(node) && isMixedWithConditionalParent(node.parent)) {
reportBothOperators(node);
} else {
if (TARGET_NODE_TYPE.test(node.parent.type) &&
isMixedWithParent(node) &&
!shouldIgnore(node)
) {
reportBothOperators(node);
}
}
}
}
return {
BinaryExpression: check,
LogicalExpression: check
};
}
};

View File

@ -21,7 +21,7 @@ module.exports = {
schema: {
type: "array",
items: [{
items: {
oneOf: [
{
type: "string"
@ -36,7 +36,7 @@ module.exports = {
additionalProperties: false
}
]
}],
},
uniqueItems: true,
minItems: 0
}

View File

@ -507,7 +507,7 @@ module.exports = {
const childScopes = scope.childScopes;
let i, l;
if (scope.type !== "TDZ" && (scope.type !== "global" || config.vars === "all")) {
if (scope.type !== "global" || config.vars === "all") {
for (i = 0, l = variables.length; i < l; ++i) {
const variable = variables[i];

View File

@ -52,16 +52,7 @@ function isOctalEscapeSequence(node) {
return false;
}
const match = node.raw.match(/^([^\\]|\\[^0-7])*\\([0-7]{1,3})/u);
if (match) {
// \0 is actually not considered an octal
if (match[2] !== "0" || typeof match[3] !== "undefined") {
return true;
}
}
return false;
return astUtils.hasOctalEscapeSequence(node.raw);
}
/**

View File

@ -29,7 +29,13 @@ const astUtils = require("./utils/ast-utils"),
* @private
*/
function getPropertyName(node) {
return astUtils.getStaticPropertyName(node) || node.key.name || null;
const staticName = astUtils.getStaticPropertyName(node);
if (staticName !== null) {
return staticName;
}
return node.key.name || null;
}
/**
@ -151,9 +157,11 @@ module.exports = {
const numKeys = stack.numKeys;
const thisName = getPropertyName(node);
stack.prevName = thisName || prevName;
if (thisName !== null) {
stack.prevName = thisName;
}
if (!prevName || !thisName || numKeys < minKeys) {
if (prevName === null || thisName === null || numKeys < minKeys) {
return;
}

View File

@ -38,6 +38,7 @@ const LINEBREAKS = new Set(["\r\n", "\r", "\n", "\u2028", "\u2029"]);
const STATEMENT_LIST_PARENTS = new Set(["Program", "BlockStatement", "SwitchCase"]);
const DECIMAL_INTEGER_PATTERN = /^(0|[1-9]\d*)$/u;
const OCTAL_ESCAPE_PATTERN = /^(?:[^\\]|\\[^0-7]|\\0(?![0-9]))*\\(?:[1-7]|0[0-9])/u;
/**
* Checks reference if is non initializer and writable.
@ -847,6 +848,7 @@ module.exports = {
return 17;
case "CallExpression":
case "ImportExpression":
return 18;
case "NewExpression":
@ -1101,7 +1103,7 @@ module.exports = {
} else {
const name = module.exports.getStaticPropertyName(parent);
if (name) {
if (name !== null) {
tokens.push(`'${name}'`);
}
}
@ -1301,7 +1303,7 @@ module.exports = {
* set `node.value` to a unicode regex. To make sure a literal is actually `null`, check
* `node.regex` instead. Also see: https://github.com/eslint/eslint/issues/8020
*/
return node.type === "Literal" && node.value === null && !node.regex;
return node.type === "Literal" && node.value === null && !node.regex && !node.bigint;
},
/**
@ -1373,5 +1375,20 @@ module.exports = {
"/*".length +
(match ? match.index + 1 : 0)
);
},
/**
* Determines whether the given raw string contains an octal escape sequence.
*
* "\1", "\2" ... "\7"
* "\00", "\01" ... "\09"
*
* "\0", when not followed by a digit, is not an octal escape sequence.
*
* @param {string} rawString A string in its raw representation.
* @returns {boolean} `true` if the string contains at least one octal escape sequence.
*/
hasOctalEscapeSequence(rawString) {
return OCTAL_ESCAPE_PATTERN.test(rawString);
}
};

View File

@ -119,7 +119,7 @@ function same(a, b) {
const nameA = astUtils.getStaticPropertyName(a);
// x.y = x["y"]
if (nameA) {
if (nameA !== null) {
return (
same(a.object, b.object) &&
nameA === astUtils.getStaticPropertyName(b)

View File

@ -30,6 +30,7 @@ module.exports = {};
* @property {Record<string, boolean>} [env] The environment settings.
* @property {string | string[]} [extends] The path to other config files or the package name of shareable configs.
* @property {Record<string, GlobalConf>} [globals] The global variable settings.
* @property {boolean} [noInlineConfig] The flag that disables directive comments.
* @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.
@ -47,6 +48,7 @@ module.exports = {};
* @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<string, GlobalConf>} [globals] The global variable settings.
* @property {boolean} [noInlineConfig] The flag that disables directive comments.
* @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.

View File

@ -6,7 +6,7 @@
"deprecated": false,
"description": "Alternative, faster React.js JSX parser",
"devDependencies": {
"acorn": "^6.0.0"
"acorn": "^7.0.0"
},
"homepage": "https://github.com/RReverser/acorn-jsx",
"license": "MIT",
@ -19,7 +19,7 @@
],
"name": "acorn-jsx",
"peerDependencies": {
"acorn": "^6.0.0"
"acorn": "^6.0.0 || ^7.0.0"
},
"repository": {
"type": "git",
@ -28,5 +28,5 @@
"scripts": {
"test": "node test/run.js"
},
"version": "5.0.1"
"version": "5.0.2"
}

View File

@ -54,7 +54,7 @@ an object containing any of these fields:
- **ecmaVersion**: Indicates the ECMAScript version to parse. Must be
either 3, 5, 6 (2015), 7 (2016), 8 (2017), 9 (2018) or 10 (2019, partial
support). This influences support for strict mode, the set of
reserved words, and support for new syntax features. Default is 9.
reserved words, and support for new syntax features. Default is 10.
**NOTE**: Only 'stage 4' (finalized) ECMAScript features are being
implemented by Acorn. Other proposed new features can be implemented
@ -64,6 +64,9 @@ an object containing any of these fields:
either `"script"` or `"module"`. This influences global strict mode
and parsing of `import` and `export` declarations.
**NOTE**: If set to `"module"`, then static `import` / `export` syntax
will be valid, even if `ecmaVersion` is less than 6.
- **onInsertedSemicolon**: If given a callback, that callback will be
called whenever a missing semicolon is inserted by the parser. The
callback will be given the character offset of the point where the

View File

@ -20,6 +20,7 @@
var keywords = {
5: ecma5AndLessKeywords,
"5module": ecma5AndLessKeywords + " export import",
6: ecma5AndLessKeywords + " const class extends export import super"
};
@ -319,8 +320,8 @@
// either 3, 5, 6 (2015), 7 (2016), 8 (2017), 9 (2018), or 10
// (2019). This influences support for strict mode, the set of
// reserved words, and support for new syntax features. The default
// is 9.
ecmaVersion: 9,
// is 10.
ecmaVersion: 10,
// `sourceType` indicates the mode the code should be parsed in.
// Can be either `"script"` or `"module"`. This influences global
// strict mode and parsing of `import` and `export` declarations.
@ -467,7 +468,7 @@
var Parser = function Parser(options, input, startPos) {
this.options = options = getOptions(options);
this.sourceFile = options.sourceFile;
this.keywords = wordsRegexp(keywords[options.ecmaVersion >= 6 ? 6 : 5]);
this.keywords = wordsRegexp(keywords[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
var reserved = "";
if (options.allowReserved !== true) {
for (var v = options.ecmaVersion;; v--)
@ -754,9 +755,7 @@
} }
this.adaptDirectivePrologue(node.body);
this.next();
if (this.options.ecmaVersion >= 6) {
node.sourceType = this.options.sourceType;
}
node.sourceType = this.options.sourceType;
return this.finishNode(node, "Program")
};
@ -2113,7 +2112,7 @@
if (computed || this.eat(types.dot)) {
var node = this.startNodeAt(startPos, startLoc);
node.object = base;
node.property = computed ? this.parseExpression() : this.parseIdent(true);
node.property = computed ? this.parseExpression() : this.parseIdent(this.options.allowReserved !== "never");
node.computed = !!computed;
if (computed) { this.expect(types.bracketR); }
base = this.finishNode(node, "MemberExpression");
@ -2122,7 +2121,7 @@
this.yieldPos = 0;
this.awaitPos = 0;
this.awaitIdentPos = 0;
var exprList = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8 && base.type !== "Import", false, refDestructuringErrors);
var exprList = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
if (maybeAsyncArrow && !this.canInsertSemicolon() && this.eat(types.arrow)) {
this.checkPatternErrors(refDestructuringErrors, false);
this.checkYieldAwaitInDefaultParams();
@ -2140,16 +2139,6 @@
var node$1 = this.startNodeAt(startPos, startLoc);
node$1.callee = base;
node$1.arguments = exprList;
if (node$1.callee.type === "Import") {
if (node$1.arguments.length !== 1) {
this.raise(node$1.start, "import() requires exactly one argument");
}
var importArg = node$1.arguments[0];
if (importArg && importArg.type === "SpreadElement") {
this.raise(importArg.start, "... is not allowed in import()");
}
}
base = this.finishNode(node$1, "CallExpression");
} else if (this.type === types.backQuote) {
var node$2 = this.startNodeAt(startPos, startLoc);
@ -2261,8 +2250,8 @@
return this.parseTemplate()
case types._import:
if (this.options.ecmaVersion > 10) {
return this.parseDynamicImport()
if (this.options.ecmaVersion >= 11) {
return this.parseExprImport()
} else {
return this.unexpected()
}
@ -2272,13 +2261,34 @@
}
};
pp$3.parseDynamicImport = function() {
pp$3.parseExprImport = function() {
var node = this.startNode();
this.next();
if (this.type !== types.parenL) {
this.next(); // skip `import`
switch (this.type) {
case types.parenL:
return this.parseDynamicImport(node)
default:
this.unexpected();
}
return this.finishNode(node, "Import")
};
pp$3.parseDynamicImport = function(node) {
this.next(); // skip `(`
// Parse node.source.
node.source = this.parseMaybeAssign();
// Verify ending.
if (!this.eat(types.parenR)) {
var errorPos = this.start;
if (this.eat(types.comma) && this.eat(types.parenR)) {
this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
} else {
this.unexpected(errorPos);
}
}
return this.finishNode(node, "ImportExpression")
};
pp$3.parseLiteral = function(value) {
@ -2388,12 +2398,12 @@
{ this.raiseRecoverable(node.start, "new.target can only be used in functions"); }
return this.finishNode(node, "MetaProperty")
}
var startPos = this.start, startLoc = this.startLoc;
var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types._import;
node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
if (this.options.ecmaVersion > 10 && node.callee.type === "Import") {
this.raise(node.callee.start, "Cannot use new with import(...)");
if (isImport && node.callee.type === "ImportExpression") {
this.raise(startPos, "Cannot use new with import()");
}
if (this.eat(types.parenL)) { node.arguments = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8 && node.callee.type !== "Import", false); }
if (this.eat(types.parenL)) { node.arguments = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false); }
else { node.arguments = empty$1; }
return this.finishNode(node, "NewExpression")
};
@ -2580,7 +2590,7 @@
prop.computed = false;
}
}
return prop.key = this.type === types.num || this.type === types.string ? this.parseExprAtom() : this.parseIdent(true)
return prop.key = this.type === types.num || this.type === types.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never")
};
// Initialize empty function node.
@ -2760,7 +2770,6 @@
pp$3.parseIdent = function(liberal, isBinding) {
var node = this.startNode();
if (liberal && this.options.allowReserved === "never") { liberal = false; }
if (this.type === types.name) {
node.name = this.value;
} else if (this.type.keyword) {
@ -4914,7 +4923,7 @@
// Acorn is a tiny, fast JavaScript parser written in JavaScript.
var version = "6.2.1";
var version = "7.0.0";
// The main exported interface (under `self.acorn` when in the
// browser) is a `parse` function that takes a code string and

View File

@ -14,6 +14,7 @@ var ecma5AndLessKeywords = "break case catch continue debugger default do else f
var keywords = {
5: ecma5AndLessKeywords,
"5module": ecma5AndLessKeywords + " export import",
6: ecma5AndLessKeywords + " const class extends export import super"
};
@ -313,8 +314,8 @@ var defaultOptions = {
// either 3, 5, 6 (2015), 7 (2016), 8 (2017), 9 (2018), or 10
// (2019). This influences support for strict mode, the set of
// reserved words, and support for new syntax features. The default
// is 9.
ecmaVersion: 9,
// is 10.
ecmaVersion: 10,
// `sourceType` indicates the mode the code should be parsed in.
// Can be either `"script"` or `"module"`. This influences global
// strict mode and parsing of `import` and `export` declarations.
@ -461,7 +462,7 @@ var
var Parser = function Parser(options, input, startPos) {
this.options = options = getOptions(options);
this.sourceFile = options.sourceFile;
this.keywords = wordsRegexp(keywords[options.ecmaVersion >= 6 ? 6 : 5]);
this.keywords = wordsRegexp(keywords[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
var reserved = "";
if (options.allowReserved !== true) {
for (var v = options.ecmaVersion;; v--)
@ -748,9 +749,7 @@ pp$1.parseTopLevel = function(node) {
} }
this.adaptDirectivePrologue(node.body);
this.next();
if (this.options.ecmaVersion >= 6) {
node.sourceType = this.options.sourceType;
}
node.sourceType = this.options.sourceType;
return this.finishNode(node, "Program")
};
@ -2107,7 +2106,7 @@ pp$3.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArro
if (computed || this.eat(types.dot)) {
var node = this.startNodeAt(startPos, startLoc);
node.object = base;
node.property = computed ? this.parseExpression() : this.parseIdent(true);
node.property = computed ? this.parseExpression() : this.parseIdent(this.options.allowReserved !== "never");
node.computed = !!computed;
if (computed) { this.expect(types.bracketR); }
base = this.finishNode(node, "MemberExpression");
@ -2116,7 +2115,7 @@ pp$3.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArro
this.yieldPos = 0;
this.awaitPos = 0;
this.awaitIdentPos = 0;
var exprList = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8 && base.type !== "Import", false, refDestructuringErrors);
var exprList = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
if (maybeAsyncArrow && !this.canInsertSemicolon() && this.eat(types.arrow)) {
this.checkPatternErrors(refDestructuringErrors, false);
this.checkYieldAwaitInDefaultParams();
@ -2134,16 +2133,6 @@ pp$3.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArro
var node$1 = this.startNodeAt(startPos, startLoc);
node$1.callee = base;
node$1.arguments = exprList;
if (node$1.callee.type === "Import") {
if (node$1.arguments.length !== 1) {
this.raise(node$1.start, "import() requires exactly one argument");
}
var importArg = node$1.arguments[0];
if (importArg && importArg.type === "SpreadElement") {
this.raise(importArg.start, "... is not allowed in import()");
}
}
base = this.finishNode(node$1, "CallExpression");
} else if (this.type === types.backQuote) {
var node$2 = this.startNodeAt(startPos, startLoc);
@ -2255,8 +2244,8 @@ pp$3.parseExprAtom = function(refDestructuringErrors) {
return this.parseTemplate()
case types._import:
if (this.options.ecmaVersion > 10) {
return this.parseDynamicImport()
if (this.options.ecmaVersion >= 11) {
return this.parseExprImport()
} else {
return this.unexpected()
}
@ -2266,13 +2255,34 @@ pp$3.parseExprAtom = function(refDestructuringErrors) {
}
};
pp$3.parseDynamicImport = function() {
pp$3.parseExprImport = function() {
var node = this.startNode();
this.next();
if (this.type !== types.parenL) {
this.next(); // skip `import`
switch (this.type) {
case types.parenL:
return this.parseDynamicImport(node)
default:
this.unexpected();
}
return this.finishNode(node, "Import")
};
pp$3.parseDynamicImport = function(node) {
this.next(); // skip `(`
// Parse node.source.
node.source = this.parseMaybeAssign();
// Verify ending.
if (!this.eat(types.parenR)) {
var errorPos = this.start;
if (this.eat(types.comma) && this.eat(types.parenR)) {
this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
} else {
this.unexpected(errorPos);
}
}
return this.finishNode(node, "ImportExpression")
};
pp$3.parseLiteral = function(value) {
@ -2382,12 +2392,12 @@ pp$3.parseNew = function() {
{ this.raiseRecoverable(node.start, "new.target can only be used in functions"); }
return this.finishNode(node, "MetaProperty")
}
var startPos = this.start, startLoc = this.startLoc;
var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types._import;
node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
if (this.options.ecmaVersion > 10 && node.callee.type === "Import") {
this.raise(node.callee.start, "Cannot use new with import(...)");
if (isImport && node.callee.type === "ImportExpression") {
this.raise(startPos, "Cannot use new with import()");
}
if (this.eat(types.parenL)) { node.arguments = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8 && node.callee.type !== "Import", false); }
if (this.eat(types.parenL)) { node.arguments = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false); }
else { node.arguments = empty$1; }
return this.finishNode(node, "NewExpression")
};
@ -2574,7 +2584,7 @@ pp$3.parsePropertyName = function(prop) {
prop.computed = false;
}
}
return prop.key = this.type === types.num || this.type === types.string ? this.parseExprAtom() : this.parseIdent(true)
return prop.key = this.type === types.num || this.type === types.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never")
};
// Initialize empty function node.
@ -2754,7 +2764,6 @@ pp$3.checkUnreserved = function(ref) {
pp$3.parseIdent = function(liberal, isBinding) {
var node = this.startNode();
if (liberal && this.options.allowReserved === "never") { liberal = false; }
if (this.type === types.name) {
node.name = this.value;
} else if (this.type.keyword) {
@ -4908,7 +4917,7 @@ pp$9.readWord = function() {
// Acorn is a tiny, fast JavaScript parser written in JavaScript.
var version = "6.2.1";
var version = "7.0.0";
// The main exported interface (under `self.acorn` when in the
// browser) is a `parse` function that takes a code string and

View File

@ -39,5 +39,5 @@
"scripts": {
"prepare": "cd ..; npm run build:main && npm run build:bin"
},
"version": "6.2.1"
"version": "7.0.0"
}

View File

@ -398,14 +398,15 @@ range, use the `satisfies(version, range)` function.
* `coerce(version)`: Coerces a string to semver if possible
This aims to provide a very forgiving translation of a non-semver
string to semver. It looks for the first digit in a string, and
consumes all remaining characters which satisfy at least a partial semver
(e.g., `1`, `1.2`, `1.2.3`) up to the max permitted length (256 characters).
Longer versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`).
All surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes `3.4.0`).
Only text which lacks digits will fail coercion (`version one` is not valid).
The maximum length for any semver component considered for coercion is 16 characters;
longer components will be ignored (`10000000000000000.4.7.4` becomes `4.7.4`).
The maximum value for any semver component is `Integer.MAX_SAFE_INTEGER || (2**53 - 1)`;
higher value components are invalid (`9999999999999999.4.7.4` is likely invalid).
This aims to provide a very forgiving translation of a non-semver string to
semver. It looks for the first digit in a string, and consumes all
remaining characters which satisfy at least a partial semver (e.g., `1`,
`1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer
versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All
surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes
`3.4.0`). Only text which lacks digits will fail coercion (`version one`
is not valid). The maximum length for any semver component considered for
coercion is 16 characters; longer components will be ignored
(`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any
semver component is `Number.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value
components are invalid (`9999999999999999.4.7.4` is likely invalid).

View File

@ -33,5 +33,5 @@
"tap": {
"check-coverage": true
},
"version": "5.7.0"
"version": "5.7.1"
}

View File

@ -240,10 +240,15 @@ function getFunctionHeadLocation(node, sourceCode) {
}
}
/* globals BigInt */
const builtinNames = Object.freeze(
new Set([
"Array",
"ArrayBuffer",
"BigInt",
"BigInt64Array",
"BigUint64Array",
"Boolean",
"DataView",
"Date",
@ -251,9 +256,7 @@ const builtinNames = Object.freeze(
"decodeURIComponent",
"encodeURI",
"encodeURIComponent",
"Error",
"escape",
"EvalError",
"Float32Array",
"Float64Array",
"Function",
@ -274,26 +277,97 @@ const builtinNames = Object.freeze(
"parseInt",
"Promise",
"Proxy",
"RangeError",
"ReferenceError",
"Reflect",
"RegExp",
"Set",
"String",
"Symbol",
"SyntaxError",
"TypeError",
"Uint16Array",
"Uint32Array",
"Uint8Array",
"Uint8ClampedArray",
"undefined",
"unescape",
"URIError",
"WeakMap",
"WeakSet",
])
);
const callAllowed = new Set(
[
Array.isArray,
typeof BigInt === "function" ? BigInt : undefined,
Boolean,
Date,
Date.parse,
decodeURI,
decodeURIComponent,
encodeURI,
encodeURIComponent,
escape,
isFinite,
isNaN,
isPrototypeOf,
...Object.getOwnPropertyNames(Math)
.map(k => Math[k])
.filter(f => typeof f === "function"),
Number,
Number.isFinite,
Number.isNaN,
Number.parseFloat,
Number.parseInt,
Object,
Object.entries, //eslint-disable-line @mysticatea/node/no-unsupported-features/es-builtins
Object.is,
Object.isExtensible,
Object.isFrozen,
Object.isSealed,
Object.keys,
Object.values, //eslint-disable-line @mysticatea/node/no-unsupported-features/es-builtins
parseFloat,
parseInt,
RegExp,
String,
String.fromCharCode,
String.fromCodePoint,
String.raw,
Symbol,
Symbol.for,
Symbol.keyFor,
unescape,
].filter(f => typeof f === "function")
);
const callPassThrough = new Set([
Object.freeze,
Object.preventExtensions,
Object.seal,
]);
/**
* Get the property descriptor.
* @param {object} object The object to get.
* @param {string|number|symbol} name The property name to get.
*/
function getPropertyDescriptor(object, name) {
let x = object;
while ((typeof x === "object" || typeof x === "function") && x !== null) {
const d = Object.getOwnPropertyDescriptor(x, name);
if (d) {
return d
}
x = Object.getPrototypeOf(x);
}
return null
}
/**
* Check if a property is getter or not.
* @param {object} object The object to check.
* @param {string|number|symbol} name The property name to check.
*/
function isGetter(object, name) {
const d = getPropertyDescriptor(object, name);
return d != null && d.get != null
}
/**
* Get the element values of a given node list.
@ -413,13 +487,23 @@ const operations = Object.freeze({
if (object != null && property != null) {
const receiver = object.value;
const methodName = property.value;
return { value: receiver[methodName](...args) }
if (callAllowed.has(receiver[methodName])) {
return { value: receiver[methodName](...args) }
}
if (callPassThrough.has(receiver[methodName])) {
return { value: args[0] }
}
}
} else {
const callee = getStaticValueR(calleeNode, initialScope);
if (callee != null) {
const func = callee.value;
return { value: func(...args) }
if (callAllowed.has(func)) {
return { value: func(...args) }
}
if (callPassThrough.has(func)) {
return { value: args[0] }
}
}
}
}
@ -473,11 +557,11 @@ const operations = Object.freeze({
Literal(node) {
//istanbul ignore if : this is implementation-specific behavior.
if (node.regex != null && node.value == null) {
// It was a RegExp literal, but Node.js didn't support it.
if ((node.regex != null || node.bigint != null) && node.value == null) {
// It was a RegExp/BigInt literal, but Node.js didn't support it.
return null
}
return node
return { value: node.value }
},
LogicalExpression(node, initialScope) {
@ -505,7 +589,11 @@ const operations = Object.freeze({
? getStaticValueR(node.property, initialScope)
: { value: node.property.name };
if (object != null && property != null) {
if (
object != null &&
property != null &&
!isGetter(object.value, property.value)
) {
return { value: object.value[property.value] }
}
return null
@ -517,7 +605,9 @@ const operations = Object.freeze({
if (callee != null && args != null) {
const Func = callee.value;
return { value: new Func(...args) }
if (callAllowed.has(Func)) {
return { value: new Func(...args) }
}
}
return null
@ -576,7 +666,9 @@ const operations = Object.freeze({
const strings = node.quasi.quasis.map(q => q.value.cooked);
strings.raw = node.quasi.quasis.map(q => q.value.raw);
return { value: func(strings, ...expressions) }
if (func === String.raw) {
return { value: func(strings, ...expressions) }
}
}
return null
@ -660,6 +752,16 @@ function getStaticValue(node, initialScope = null) {
* @returns {string|null} The value of the node, or `null`.
*/
function getStringIfConstant(node, initialScope = null) {
// Handle the literals that the platform doesn't support natively.
if (node && node.type === "Literal" && node.value === null) {
if (node.regex) {
return `/${node.regex.pattern}/${node.regex.flags}`
}
if (node.bigint) {
return node.bigint
}
}
const evaluated = getStaticValue(node, initialScope);
return evaluated && String(evaluated.value)
}

View File

@ -234,10 +234,15 @@ function getFunctionHeadLocation(node, sourceCode) {
}
}
/* globals BigInt */
const builtinNames = Object.freeze(
new Set([
"Array",
"ArrayBuffer",
"BigInt",
"BigInt64Array",
"BigUint64Array",
"Boolean",
"DataView",
"Date",
@ -245,9 +250,7 @@ const builtinNames = Object.freeze(
"decodeURIComponent",
"encodeURI",
"encodeURIComponent",
"Error",
"escape",
"EvalError",
"Float32Array",
"Float64Array",
"Function",
@ -268,26 +271,97 @@ const builtinNames = Object.freeze(
"parseInt",
"Promise",
"Proxy",
"RangeError",
"ReferenceError",
"Reflect",
"RegExp",
"Set",
"String",
"Symbol",
"SyntaxError",
"TypeError",
"Uint16Array",
"Uint32Array",
"Uint8Array",
"Uint8ClampedArray",
"undefined",
"unescape",
"URIError",
"WeakMap",
"WeakSet",
])
);
const callAllowed = new Set(
[
Array.isArray,
typeof BigInt === "function" ? BigInt : undefined,
Boolean,
Date,
Date.parse,
decodeURI,
decodeURIComponent,
encodeURI,
encodeURIComponent,
escape,
isFinite,
isNaN,
isPrototypeOf,
...Object.getOwnPropertyNames(Math)
.map(k => Math[k])
.filter(f => typeof f === "function"),
Number,
Number.isFinite,
Number.isNaN,
Number.parseFloat,
Number.parseInt,
Object,
Object.entries, //eslint-disable-line @mysticatea/node/no-unsupported-features/es-builtins
Object.is,
Object.isExtensible,
Object.isFrozen,
Object.isSealed,
Object.keys,
Object.values, //eslint-disable-line @mysticatea/node/no-unsupported-features/es-builtins
parseFloat,
parseInt,
RegExp,
String,
String.fromCharCode,
String.fromCodePoint,
String.raw,
Symbol,
Symbol.for,
Symbol.keyFor,
unescape,
].filter(f => typeof f === "function")
);
const callPassThrough = new Set([
Object.freeze,
Object.preventExtensions,
Object.seal,
]);
/**
* Get the property descriptor.
* @param {object} object The object to get.
* @param {string|number|symbol} name The property name to get.
*/
function getPropertyDescriptor(object, name) {
let x = object;
while ((typeof x === "object" || typeof x === "function") && x !== null) {
const d = Object.getOwnPropertyDescriptor(x, name);
if (d) {
return d
}
x = Object.getPrototypeOf(x);
}
return null
}
/**
* Check if a property is getter or not.
* @param {object} object The object to check.
* @param {string|number|symbol} name The property name to check.
*/
function isGetter(object, name) {
const d = getPropertyDescriptor(object, name);
return d != null && d.get != null
}
/**
* Get the element values of a given node list.
@ -407,13 +481,23 @@ const operations = Object.freeze({
if (object != null && property != null) {
const receiver = object.value;
const methodName = property.value;
return { value: receiver[methodName](...args) }
if (callAllowed.has(receiver[methodName])) {
return { value: receiver[methodName](...args) }
}
if (callPassThrough.has(receiver[methodName])) {
return { value: args[0] }
}
}
} else {
const callee = getStaticValueR(calleeNode, initialScope);
if (callee != null) {
const func = callee.value;
return { value: func(...args) }
if (callAllowed.has(func)) {
return { value: func(...args) }
}
if (callPassThrough.has(func)) {
return { value: args[0] }
}
}
}
}
@ -467,11 +551,11 @@ const operations = Object.freeze({
Literal(node) {
//istanbul ignore if : this is implementation-specific behavior.
if (node.regex != null && node.value == null) {
// It was a RegExp literal, but Node.js didn't support it.
if ((node.regex != null || node.bigint != null) && node.value == null) {
// It was a RegExp/BigInt literal, but Node.js didn't support it.
return null
}
return node
return { value: node.value }
},
LogicalExpression(node, initialScope) {
@ -499,7 +583,11 @@ const operations = Object.freeze({
? getStaticValueR(node.property, initialScope)
: { value: node.property.name };
if (object != null && property != null) {
if (
object != null &&
property != null &&
!isGetter(object.value, property.value)
) {
return { value: object.value[property.value] }
}
return null
@ -511,7 +599,9 @@ const operations = Object.freeze({
if (callee != null && args != null) {
const Func = callee.value;
return { value: new Func(...args) }
if (callAllowed.has(Func)) {
return { value: new Func(...args) }
}
}
return null
@ -570,7 +660,9 @@ const operations = Object.freeze({
const strings = node.quasi.quasis.map(q => q.value.cooked);
strings.raw = node.quasi.quasis.map(q => q.value.raw);
return { value: func(strings, ...expressions) }
if (func === String.raw) {
return { value: func(strings, ...expressions) }
}
}
return null
@ -654,6 +746,16 @@ function getStaticValue(node, initialScope = null) {
* @returns {string|null} The value of the node, or `null`.
*/
function getStringIfConstant(node, initialScope = null) {
// Handle the literals that the platform doesn't support natively.
if (node && node.type === "Literal" && node.value === null) {
if (node.regex) {
return `/${node.regex.pattern}/${node.regex.flags}`
}
if (node.bigint) {
return node.bigint
}
}
const evaluated = getStaticValue(node, initialScope);
return evaluated && String(evaluated.value)
}

View File

@ -62,5 +62,5 @@
"watch": "warun \"{src,test}/**/*.js\" -- nyc --reporter lcov mocha --reporter dot \"test/*.js\""
},
"sideEffects": false,
"version": "1.4.0"
"version": "1.4.2"
}

View File

@ -128,6 +128,9 @@
"ImportDefaultSpecifier": [
"local"
],
"ImportExpression": [
"source"
],
"ImportNamespaceSpecifier": [
"local"
],

View File

@ -13,7 +13,7 @@
"devDependencies": {
"eslint": "^4.7.2",
"eslint-config-eslint": "^4.0.0",
"eslint-release": "^0.10.3",
"eslint-release": "^1.0.0",
"mocha": "^3.5.3",
"nyc": "^11.2.1",
"opener": "^1.4.3"
@ -34,12 +34,15 @@
"url": "git+https://github.com/eslint/eslint-visitor-keys.git"
},
"scripts": {
"ci-release": "eslint-ci-release",
"coverage": "nyc report --reporter lcov && opener coverage/lcov-report/index.html",
"generate-alpharelease": "eslint-generate-prerelease alpha",
"generate-betarelease": "eslint-generate-prerelease beta",
"generate-rcrelease": "eslint-generate-prerelease rc",
"generate-release": "eslint-generate-release",
"lint": "eslint lib tests/lib",
"pretest": "npm run -s lint",
"release": "eslint-release",
"publish-release": "eslint-publish-release",
"test": "nyc mocha tests/lib"
},
"version": "1.0.0"
"version": "1.1.0"
}

View File

@ -44,7 +44,7 @@ const ast = espree.parse(code, {
tokens: false,
// Set to 3, 5 (default), 6, 7, 8, 9, or 10 to specify the version of ECMAScript syntax you want to use.
// You can also set to 2015 (same as 6), 2016 (same as 7), 2017 (same as 8), 2018 (same as 9), or 2019 (same as 10) to use the year-based naming.
// You can also set to 2015 (same as 6), 2016 (same as 7), 2017 (same as 8), 2018 (same as 9), 2019 (same as 10), or 2020 (same as 11) to use the year-based naming.
ecmaVersion: 5,
// specify which type of script you're parsing ("script" or "module")

View File

@ -154,7 +154,7 @@ exports.Syntax = (function() {
}
for (name in astNodeTypes) {
if (astNodeTypes.hasOwnProperty(name)) {
if (Object.hasOwnProperty.call(astNodeTypes, name)) {
types[name] = astNodeTypes[name];
}
}

View File

@ -18,27 +18,30 @@ const tokTypes = Object.assign({}, acorn.tokTypes, jsx.tokTypes);
* @returns {number} normalized ECMAScript version
*/
function normalizeEcmaVersion(ecmaVersion = DEFAULT_ECMA_VERSION) {
if (typeof ecmaVersion === "number") {
let version = ecmaVersion;
if (typeof ecmaVersion !== "number") {
throw new Error(`ecmaVersion must be a number. Received value of type ${typeof ecmaVersion} instead.`);
}
// Calculate ECMAScript edition number from official year version starting with
// ES2015, which corresponds with ES6 (or a difference of 2009).
if (version >= 2015) {
version -= 2009;
}
let version = ecmaVersion;
switch (version) {
case 3:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
return version;
// Calculate ECMAScript edition number from official year version starting with
// ES2015, which corresponds with ES6 (or a difference of 2009).
if (version >= 2015) {
version -= 2009;
}
// no default
}
switch (version) {
case 3:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
case 11:
return version;
// no default
}
throw new Error("Invalid ecmaVersion.");
@ -174,6 +177,9 @@ module.exports = () => Parser => class Espree extends Parser {
this.next();
} while (this.type !== tokTypes.eof);
// Consume the final eof token
this.next();
const extra = this[STATE];
const tokens = extra.tokens;

View File

@ -8,29 +8,29 @@
},
"bundleDependencies": false,
"dependencies": {
"acorn": "^6.0.7",
"acorn-jsx": "^5.0.0",
"eslint-visitor-keys": "^1.0.0"
"acorn": "^7.0.0",
"acorn-jsx": "^5.0.2",
"eslint-visitor-keys": "^1.1.0"
},
"deprecated": false,
"description": "An Esprima-compatible JavaScript parser built on Acorn",
"devDependencies": {
"browserify": "^7.0.0",
"chai": "^1.10.0",
"eslint": "^5.7.0",
"browserify": "^16.5.0",
"chai": "^4.2.0",
"eslint": "^6.0.1",
"eslint-config-eslint": "^5.0.1",
"eslint-plugin-node": "^8.0.0",
"eslint-plugin-node": "^9.1.0",
"eslint-release": "^1.0.0",
"esprima": "latest",
"esprima-fb": "^8001.2001.0-dev-harmony-fb",
"json-diff": "~0.3.1",
"leche": "^1.0.1",
"mocha": "^2.0.1",
"nyc": "^13.0.1",
"regenerate": "~0.5.4",
"json-diff": "^0.5.4",
"leche": "^2.3.0",
"mocha": "^6.2.0",
"nyc": "^14.1.1",
"regenerate": "^1.4.0",
"shelljs": "^0.3.0",
"shelljs-nodecli": "^0.1.1",
"unicode-6.3.0": "~0.1.0"
"unicode-6.3.0": "^0.7.5"
},
"engines": {
"node": ">=6.0.0"
@ -66,5 +66,5 @@
"publish-release": "eslint-publish-release",
"test": "npm run-script lint && node Makefile.js test"
},
"version": "6.0.0"
"version": "6.1.1"
}

View File

@ -0,0 +1,153 @@
### Estraverse [![Build Status](https://secure.travis-ci.org/estools/estraverse.svg)](http://travis-ci.org/estools/estraverse)
Estraverse ([estraverse](http://github.com/estools/estraverse)) is
[ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm)
traversal functions from [esmangle project](http://github.com/estools/esmangle).
### Documentation
You can find usage docs at [wiki page](https://github.com/estools/estraverse/wiki/Usage).
### Example Usage
The following code will output all variables declared at the root of a file.
```javascript
estraverse.traverse(ast, {
enter: function (node, parent) {
if (node.type == 'FunctionExpression' || node.type == 'FunctionDeclaration')
return estraverse.VisitorOption.Skip;
},
leave: function (node, parent) {
if (node.type == 'VariableDeclarator')
console.log(node.id.name);
}
});
```
We can use `this.skip`, `this.remove` and `this.break` functions instead of using Skip, Remove and Break.
```javascript
estraverse.traverse(ast, {
enter: function (node) {
this.break();
}
});
```
And estraverse provides `estraverse.replace` function. When returning node from `enter`/`leave`, current node is replaced with it.
```javascript
result = estraverse.replace(tree, {
enter: function (node) {
// Replace it with replaced.
if (node.type === 'Literal')
return replaced;
}
});
```
By passing `visitor.keys` mapping, we can extend estraverse traversing functionality.
```javascript
// This tree contains a user-defined `TestExpression` node.
var tree = {
type: 'TestExpression',
// This 'argument' is the property containing the other **node**.
argument: {
type: 'Literal',
value: 20
},
// This 'extended' is the property not containing the other **node**.
extended: true
};
estraverse.traverse(tree, {
enter: function (node) { },
// Extending the existing traversing rules.
keys: {
// TargetNodeName: [ 'keys', 'containing', 'the', 'other', '**node**' ]
TestExpression: ['argument']
}
});
```
By passing `visitor.fallback` option, we can control the behavior when encountering unknown nodes.
```javascript
// This tree contains a user-defined `TestExpression` node.
var tree = {
type: 'TestExpression',
// This 'argument' is the property containing the other **node**.
argument: {
type: 'Literal',
value: 20
},
// This 'extended' is the property not containing the other **node**.
extended: true
};
estraverse.traverse(tree, {
enter: function (node) { },
// Iterating the child **nodes** of unknown nodes.
fallback: 'iteration'
});
```
When `visitor.fallback` is a function, we can determine which keys to visit on each node.
```javascript
// This tree contains a user-defined `TestExpression` node.
var tree = {
type: 'TestExpression',
// This 'argument' is the property containing the other **node**.
argument: {
type: 'Literal',
value: 20
},
// This 'extended' is the property not containing the other **node**.
extended: true
};
estraverse.traverse(tree, {
enter: function (node) { },
// Skip the `argument` property of each node
fallback: function(node) {
return Object.keys(node).filter(function(key) {
return key !== 'argument';
});
}
});
```
### License
Copyright (C) 2012-2016 [Yusuke Suzuki](http://github.com/Constellation)
(twitter: [@Constellation](http://twitter.com/Constellation)) and other contributors.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@ -29,24 +29,12 @@
'use strict';
var Syntax,
isArray,
VisitorOption,
VisitorKeys,
objectCreate,
objectKeys,
BREAK,
SKIP,
REMOVE;
function ignoreJSHintError() { }
isArray = Array.isArray;
if (!isArray) {
isArray = function isArray(array) {
return Object.prototype.toString.call(array) === '[object Array]';
};
}
function deepCopy(obj) {
var ret = {}, key, val;
for (key in obj) {
@ -62,17 +50,6 @@
return ret;
}
function shallowCopy(obj) {
var ret = {}, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
ret[key] = obj[key];
}
}
return ret;
}
ignoreJSHintError(shallowCopy);
// based on LLVM libc++ upper_bound / lower_bound
// MIT License
@ -95,52 +72,6 @@
return i;
}
function lowerBound(array, func) {
var diff, len, i, current;
len = array.length;
i = 0;
while (len) {
diff = len >>> 1;
current = i + diff;
if (func(array[current])) {
i = current + 1;
len -= diff + 1;
} else {
len = diff;
}
}
return i;
}
ignoreJSHintError(lowerBound);
objectCreate = Object.create || (function () {
function F() { }
return function (o) {
F.prototype = o;
return new F();
};
})();
objectKeys = Object.keys || function (o) {
var keys = [], key;
for (key in o) {
keys.push(key);
}
return keys;
};
function extend(to, from) {
var keys = objectKeys(from), key, i, len;
for (i = 0, len = keys.length; i < len; i += 1) {
key = keys[i];
to[key] = from[key];
}
return to;
}
Syntax = {
AssignmentExpression: 'AssignmentExpression',
AssignmentPattern: 'AssignmentPattern',
@ -177,6 +108,7 @@
GeneratorExpression: 'GeneratorExpression', // CAUTION: It's deferred to ES7.
Identifier: 'Identifier',
IfStatement: 'IfStatement',
ImportExpression: 'ImportExpression',
ImportDeclaration: 'ImportDeclaration',
ImportDefaultSpecifier: 'ImportDefaultSpecifier',
ImportNamespaceSpecifier: 'ImportNamespaceSpecifier',
@ -251,6 +183,7 @@
GeneratorExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7.
Identifier: [],
IfStatement: ['test', 'consequent', 'alternate'],
ImportExpression: ['source'],
ImportDeclaration: ['specifiers', 'source'],
ImportDefaultSpecifier: ['local'],
ImportNamespaceSpecifier: ['local'],
@ -310,7 +243,7 @@
};
Reference.prototype.remove = function remove() {
if (isArray(this.parent)) {
if (Array.isArray(this.parent)) {
this.parent.splice(this.key, 1);
return true;
} else {
@ -334,7 +267,7 @@
var i, iz, j, jz, result, element;
function addToPath(result, path) {
if (isArray(path)) {
if (Array.isArray(path)) {
for (j = 0, jz = path.length; j < jz; ++j) {
result.push(path[j]);
}
@ -434,14 +367,14 @@
this.__state = null;
this.__fallback = null;
if (visitor.fallback === 'iteration') {
this.__fallback = objectKeys;
this.__fallback = Object.keys;
} else if (typeof visitor.fallback === 'function') {
this.__fallback = visitor.fallback;
}
this.__keys = VisitorKeys;
if (visitor.keys) {
this.__keys = extend(objectCreate(this.__keys), visitor.keys);
this.__keys = Object.assign(Object.create(this.__keys), visitor.keys);
}
};
@ -530,7 +463,7 @@
continue;
}
if (isArray(candidate)) {
if (Array.isArray(candidate)) {
current2 = candidate.length;
while ((current2 -= 1) >= 0) {
if (!candidate[current2]) {
@ -684,7 +617,7 @@
continue;
}
if (isArray(candidate)) {
if (Array.isArray(candidate)) {
current2 = candidate.length;
while ((current2 -= 1) >= 0) {
if (!candidate[current2]) {

View File

@ -6,7 +6,7 @@
"deprecated": false,
"description": "ECMAScript JS AST traversal functions",
"devDependencies": {
"babel-preset-es2015": "^6.3.13",
"babel-preset-env": "^1.6.1",
"babel-register": "^6.3.13",
"chai": "^2.1.1",
"espree": "^1.11.0",
@ -14,12 +14,12 @@
"gulp-bump": "^0.2.2",
"gulp-filter": "^2.0.0",
"gulp-git": "^1.0.1",
"gulp-tag-version": "^1.2.1",
"gulp-tag-version": "^1.3.0",
"jshint": "^2.5.6",
"mocha": "^2.1.0"
},
"engines": {
"node": ">=0.10.0"
"node": ">=4.0"
},
"homepage": "https://github.com/estools/estraverse",
"license": "BSD-2-Clause",
@ -41,5 +41,5 @@
"test": "npm run-script lint && npm run-script unit-test",
"unit-test": "mocha --compilers js:babel-register"
},
"version": "4.2.0"
"version": "4.3.0"
}

View File

@ -98,8 +98,8 @@ respectively. If the `strict` flag is truthy, this function additionally checks
Returns `true` if provided identifier string is a Keyword or Future Reserved Word
in ECMA262 edition 6. They are formally defined in ECMA262 sections
[11.6.2.1](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-keywords) and
[11.6.2.2](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-future-reserved-words),
[11.6.2.1](http://ecma-international.org/ecma-262/6.0/#sec-keywords) and
[11.6.2.2](http://ecma-international.org/ecma-262/6.0/#sec-future-reserved-words),
respectively. If the `strict` flag is truthy, this function additionally checks whether
`id` is a Keyword or Future Reserved Word under strict mode.
@ -113,7 +113,7 @@ is a Reserved Word under strict mode.
#### keyword.isReservedWordES6(id, strict)
Returns `true` if provided identifier string is a Reserved Word in ECMA262 edition 6.
They are formally defined in ECMA262 section [11.6.2](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-reserved-words).
They are formally defined in ECMA262 section [11.6.2](http://ecma-international.org/ecma-262/6.0/#sec-reserved-words).
If the `strict` flag is truthy, this function additionally checks whether `id`
is a Reserved Word under strict mode.
@ -121,13 +121,18 @@ is a Reserved Word under strict mode.
Returns `true` if provided identifier string is one of `eval` or `arguments`.
They are restricted in strict mode code throughout ECMA262 edition 5.1 and
in ECMA262 edition 6 section [12.1.1](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-identifiers-static-semantics-early-errors).
in ECMA262 edition 6 section [12.1.1](http://ecma-international.org/ecma-262/6.0/#sec-identifiers-static-semantics-early-errors).
#### keyword.isIdentifierName(id)
#### keyword.isIdentifierNameES5(id)
Return true if provided identifier string is an IdentifierName as specified in
ECMA262 edition 5.1 section [7.6](https://es5.github.io/#x7.6).
#### keyword.isIdentifierNameES6(id)
Return true if provided identifier string is an IdentifierName as specified in
ECMA262 edition 6 section [11.6](http://ecma-international.org/ecma-262/6.0/#sec-names-and-keywords).
#### keyword.isIdentifierES5(id, strict)
Return true if provided identifier string is an Identifier as specified in
@ -138,7 +143,7 @@ under strict mode.
#### keyword.isIdentifierES6(id, strict)
Return true if provided identifier string is an Identifier as specified in
ECMA262 edition 6 section [12.1](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-identifiers).
ECMA262 edition 6 section [12.1](http://ecma-international.org/ecma-262/6.0/#sec-identifiers).
If the `strict` flag is truthy, this function additionally checks whether `id`
is an Identifier under strict mode.

File diff suppressed because one or more lines are too long

View File

@ -10,8 +10,8 @@
"coffee-script": "~1.6.3",
"jshint": "2.6.3",
"mocha": "~2.2.1",
"regenerate": "~1.2.1",
"unicode-7.0.0": "^0.1.5"
"regenerate": "~1.3.1",
"unicode-9.0.0": "~0.7.0"
},
"directories": {
"lib": "./lib"
@ -25,12 +25,7 @@
"lib"
],
"homepage": "https://github.com/estools/esutils",
"licenses": [
{
"type": "BSD",
"url": "http://github.com/estools/esutils/raw/master/LICENSE.BSD"
}
],
"license": "BSD-2-Clause",
"main": "lib/utils.js",
"maintainers": [
{
@ -50,5 +45,5 @@
"test": "npm run-script lint && npm run-script unit-test",
"unit-test": "mocha --compilers coffee:coffee-script -R spec"
},
"version": "2.0.2"
"version": "2.0.3"
}

View File

@ -172,3 +172,4 @@
"requireUseStrict": true
}

View File

@ -115,7 +115,7 @@ A full featured example
- `mode` (number) *Optional* Which mode to create the file with. e.g. 644
- `template` (string) *Optional* A template for the filename. See [tmp](https://www.npmjs.com/package/tmp).
- `dir` (string) *Optional* Which path to store the file.
## Errors
All errors have a simple message explaining what went wrong. They all also have an `originalError` property containing

View File

@ -1,5 +1,11 @@
<img width="75px" height="75px" align="right" alt="Inquirer Logo" src="https://raw.githubusercontent.com/SBoudrias/Inquirer.js/master/assets/inquirer_readme.svg?sanitize=true" title="Inquirer.js"/>
# Compat Version #
This version is branched from Inquirer master branch to maintain support for Node 6.
See latest version release line at https://github.com/SBoudrias/Inquirer.js
# Inquirer.js
[![npm](https://badge.fury.io/js/inquirer.svg)](http://badge.fury.io/js/inquirer) [![tests](https://travis-ci.org/SBoudrias/Inquirer.js.svg?branch=master)](http://travis-ci.org/SBoudrias/Inquirer.js) [![Coverage Status](https://codecov.io/gh/SBoudrias/Inquirer.js/branch/master/graph/badge.svg)](https://codecov.io/gh/SBoudrias/Inquirer.js) [![dependencies](https://david-dm.org/SBoudrias/Inquirer.js.svg?theme=shields.io)](https://david-dm.org/SBoudrias/Inquirer.js)
@ -446,4 +452,4 @@ Auto submit based on your current input, saving one extra enter
[**inquirer-file-tree-selection-prompt**](https://github.com/anc95/inquirer-file-tree-selection)<br>
Inquirer prompt for to select a file or directory in file tree
![inquirer-file-tree-selection-prompt](https://github.com/anc95/inquirer-file-tree-selection/blob/master/example/screenshot.gif)
![inquirer-file-tree-selection-prompt](https://github.com/anc95/inquirer-file-tree-selection/blob/master/example/screenshot.gif)

View File

@ -40,7 +40,7 @@
"lib",
"README.md"
],
"gitHead": "da5d0e22de84486240b12f52643fbd573f8d0d38",
"gitHead": "7d87f666042c67638d2e89bd4586d22f61e90130",
"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.5.0"
"version": "6.5.2"
}

View File

@ -180,13 +180,13 @@ You might also be interested in these projects:
### 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) |
| **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

View File

@ -430,7 +430,7 @@ any other overlapping SemVer tuple.
* `clean(version)`: Clean a string to be a valid semver if possible
This will return a cleaned and trimmed semver version. If the provided version is not valid a null will be returned. This does not work for ranges.
This will return a cleaned and trimmed semver version. If the provided version is not valid a null will be returned. This does not work for ranges.
ex.
* `s.clean(' = v 2.1.5foo')`: `null`

Binary file not shown.

View File

@ -33,5 +33,5 @@
"tap": {
"check-coverage": true
},
"version": "6.2.0"
"version": "6.3.0"
}

View File

@ -29,75 +29,80 @@ var MAX_SAFE_COMPONENT_LENGTH = 16
// The actual regexps go on exports.re
var re = exports.re = []
var src = exports.src = []
var t = exports.tokens = {}
var R = 0
function tok (n) {
t[n] = R++
}
// The following Regular Expressions can be used for tokenizing,
// validating, and parsing SemVer version strings.
// ## Numeric Identifier
// A single `0`, or a non-zero digit followed by zero or more digits.
var NUMERICIDENTIFIER = R++
src[NUMERICIDENTIFIER] = '0|[1-9]\\d*'
var NUMERICIDENTIFIERLOOSE = R++
src[NUMERICIDENTIFIERLOOSE] = '[0-9]+'
tok('NUMERICIDENTIFIER')
src[t.NUMERICIDENTIFIER] = '0|[1-9]\\d*'
tok('NUMERICIDENTIFIERLOOSE')
src[t.NUMERICIDENTIFIERLOOSE] = '[0-9]+'
// ## Non-numeric Identifier
// Zero or more digits, followed by a letter or hyphen, and then zero or
// more letters, digits, or hyphens.
var NONNUMERICIDENTIFIER = R++
src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*'
tok('NONNUMERICIDENTIFIER')
src[t.NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*'
// ## Main Version
// Three dot-separated numeric identifiers.
var MAINVERSION = R++
src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' +
'(' + src[NUMERICIDENTIFIER] + ')\\.' +
'(' + src[NUMERICIDENTIFIER] + ')'
tok('MAINVERSION')
src[t.MAINVERSION] = '(' + src[t.NUMERICIDENTIFIER] + ')\\.' +
'(' + src[t.NUMERICIDENTIFIER] + ')\\.' +
'(' + src[t.NUMERICIDENTIFIER] + ')'
var MAINVERSIONLOOSE = R++
src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' +
'(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' +
'(' + src[NUMERICIDENTIFIERLOOSE] + ')'
tok('MAINVERSIONLOOSE')
src[t.MAINVERSIONLOOSE] = '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' +
'(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' +
'(' + src[t.NUMERICIDENTIFIERLOOSE] + ')'
// ## Pre-release Version Identifier
// A numeric identifier, or a non-numeric identifier.
var PRERELEASEIDENTIFIER = R++
src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] +
'|' + src[NONNUMERICIDENTIFIER] + ')'
tok('PRERELEASEIDENTIFIER')
src[t.PRERELEASEIDENTIFIER] = '(?:' + src[t.NUMERICIDENTIFIER] +
'|' + src[t.NONNUMERICIDENTIFIER] + ')'
var PRERELEASEIDENTIFIERLOOSE = R++
src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] +
'|' + src[NONNUMERICIDENTIFIER] + ')'
tok('PRERELEASEIDENTIFIERLOOSE')
src[t.PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[t.NUMERICIDENTIFIERLOOSE] +
'|' + src[t.NONNUMERICIDENTIFIER] + ')'
// ## Pre-release Version
// Hyphen, followed by one or more dot-separated pre-release version
// identifiers.
var PRERELEASE = R++
src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] +
'(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))'
tok('PRERELEASE')
src[t.PRERELEASE] = '(?:-(' + src[t.PRERELEASEIDENTIFIER] +
'(?:\\.' + src[t.PRERELEASEIDENTIFIER] + ')*))'
var PRERELEASELOOSE = R++
src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] +
'(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))'
tok('PRERELEASELOOSE')
src[t.PRERELEASELOOSE] = '(?:-?(' + src[t.PRERELEASEIDENTIFIERLOOSE] +
'(?:\\.' + src[t.PRERELEASEIDENTIFIERLOOSE] + ')*))'
// ## Build Metadata Identifier
// Any combination of digits, letters, or hyphens.
var BUILDIDENTIFIER = R++
src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+'
tok('BUILDIDENTIFIER')
src[t.BUILDIDENTIFIER] = '[0-9A-Za-z-]+'
// ## Build Metadata
// Plus sign, followed by one or more period-separated build metadata
// identifiers.
var BUILD = R++
src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] +
'(?:\\.' + src[BUILDIDENTIFIER] + ')*))'
tok('BUILD')
src[t.BUILD] = '(?:\\+(' + src[t.BUILDIDENTIFIER] +
'(?:\\.' + src[t.BUILDIDENTIFIER] + ')*))'
// ## Full Version String
// A main version, followed optionally by a pre-release version and
@ -108,131 +113,133 @@ src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] +
// capturing group, because it should not ever be used in version
// comparison.
var FULL = R++
var FULLPLAIN = 'v?' + src[MAINVERSION] +
src[PRERELEASE] + '?' +
src[BUILD] + '?'
tok('FULL')
tok('FULLPLAIN')
src[t.FULLPLAIN] = 'v?' + src[t.MAINVERSION] +
src[t.PRERELEASE] + '?' +
src[t.BUILD] + '?'
src[FULL] = '^' + FULLPLAIN + '$'
src[t.FULL] = '^' + src[t.FULLPLAIN] + '$'
// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
// common in the npm registry.
var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] +
src[PRERELEASELOOSE] + '?' +
src[BUILD] + '?'
tok('LOOSEPLAIN')
src[t.LOOSEPLAIN] = '[v=\\s]*' + src[t.MAINVERSIONLOOSE] +
src[t.PRERELEASELOOSE] + '?' +
src[t.BUILD] + '?'
var LOOSE = R++
src[LOOSE] = '^' + LOOSEPLAIN + '$'
tok('LOOSE')
src[t.LOOSE] = '^' + src[t.LOOSEPLAIN] + '$'
var GTLT = R++
src[GTLT] = '((?:<|>)?=?)'
tok('GTLT')
src[t.GTLT] = '((?:<|>)?=?)'
// Something like "2.*" or "1.2.x".
// Note that "x.x" is a valid xRange identifer, meaning "any version"
// Only the first item is strictly required.
var XRANGEIDENTIFIERLOOSE = R++
src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*'
var XRANGEIDENTIFIER = R++
src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*'
tok('XRANGEIDENTIFIERLOOSE')
src[t.XRANGEIDENTIFIERLOOSE] = src[t.NUMERICIDENTIFIERLOOSE] + '|x|X|\\*'
tok('XRANGEIDENTIFIER')
src[t.XRANGEIDENTIFIER] = src[t.NUMERICIDENTIFIER] + '|x|X|\\*'
var XRANGEPLAIN = R++
src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' +
'(?:\\.(' + src[XRANGEIDENTIFIER] + ')' +
'(?:\\.(' + src[XRANGEIDENTIFIER] + ')' +
'(?:' + src[PRERELEASE] + ')?' +
src[BUILD] + '?' +
tok('XRANGEPLAIN')
src[t.XRANGEPLAIN] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIER] + ')' +
'(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' +
'(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' +
'(?:' + src[t.PRERELEASE] + ')?' +
src[t.BUILD] + '?' +
')?)?'
var XRANGEPLAINLOOSE = R++
src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' +
'(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' +
'(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' +
'(?:' + src[PRERELEASELOOSE] + ')?' +
src[BUILD] + '?' +
tok('XRANGEPLAINLOOSE')
src[t.XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' +
'(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' +
'(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' +
'(?:' + src[t.PRERELEASELOOSE] + ')?' +
src[t.BUILD] + '?' +
')?)?'
var XRANGE = R++
src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$'
var XRANGELOOSE = R++
src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$'
tok('XRANGE')
src[t.XRANGE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAIN] + '$'
tok('XRANGELOOSE')
src[t.XRANGELOOSE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAINLOOSE] + '$'
// Coercion.
// Extract anything that could conceivably be a part of a valid semver
var COERCE = R++
src[COERCE] = '(^|[^\\d])' +
tok('COERCE')
src[t.COERCE] = '(^|[^\\d])' +
'(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' +
'(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' +
'(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' +
'(?:$|[^\\d])'
var COERCERTL = R++
re[COERCERTL] = new RegExp(src[COERCE], 'g')
tok('COERCERTL')
re[t.COERCERTL] = new RegExp(src[t.COERCE], 'g')
// Tilde ranges.
// Meaning is "reasonably at or greater than"
var LONETILDE = R++
src[LONETILDE] = '(?:~>?)'
tok('LONETILDE')
src[t.LONETILDE] = '(?:~>?)'
var TILDETRIM = R++
src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+'
re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g')
tok('TILDETRIM')
src[t.TILDETRIM] = '(\\s*)' + src[t.LONETILDE] + '\\s+'
re[t.TILDETRIM] = new RegExp(src[t.TILDETRIM], 'g')
var tildeTrimReplace = '$1~'
var TILDE = R++
src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$'
var TILDELOOSE = R++
src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$'
tok('TILDE')
src[t.TILDE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAIN] + '$'
tok('TILDELOOSE')
src[t.TILDELOOSE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAINLOOSE] + '$'
// Caret ranges.
// Meaning is "at least and backwards compatible with"
var LONECARET = R++
src[LONECARET] = '(?:\\^)'
tok('LONECARET')
src[t.LONECARET] = '(?:\\^)'
var CARETTRIM = R++
src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+'
re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g')
tok('CARETTRIM')
src[t.CARETTRIM] = '(\\s*)' + src[t.LONECARET] + '\\s+'
re[t.CARETTRIM] = new RegExp(src[t.CARETTRIM], 'g')
var caretTrimReplace = '$1^'
var CARET = R++
src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$'
var CARETLOOSE = R++
src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$'
tok('CARET')
src[t.CARET] = '^' + src[t.LONECARET] + src[t.XRANGEPLAIN] + '$'
tok('CARETLOOSE')
src[t.CARETLOOSE] = '^' + src[t.LONECARET] + src[t.XRANGEPLAINLOOSE] + '$'
// A simple gt/lt/eq thing, or just "" to indicate "any version"
var COMPARATORLOOSE = R++
src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$'
var COMPARATOR = R++
src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$'
tok('COMPARATORLOOSE')
src[t.COMPARATORLOOSE] = '^' + src[t.GTLT] + '\\s*(' + src[t.LOOSEPLAIN] + ')$|^$'
tok('COMPARATOR')
src[t.COMPARATOR] = '^' + src[t.GTLT] + '\\s*(' + src[t.FULLPLAIN] + ')$|^$'
// An expression to strip any whitespace between the gtlt and the thing
// it modifies, so that `> 1.2.3` ==> `>1.2.3`
var COMPARATORTRIM = R++
src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] +
'\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')'
tok('COMPARATORTRIM')
src[t.COMPARATORTRIM] = '(\\s*)' + src[t.GTLT] +
'\\s*(' + src[t.LOOSEPLAIN] + '|' + src[t.XRANGEPLAIN] + ')'
// this one has to use the /g flag
re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g')
re[t.COMPARATORTRIM] = new RegExp(src[t.COMPARATORTRIM], 'g')
var comparatorTrimReplace = '$1$2$3'
// Something like `1.2.3 - 1.2.4`
// Note that these all use the loose form, because they'll be
// checked against either the strict or loose comparator form
// later.
var HYPHENRANGE = R++
src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' +
tok('HYPHENRANGE')
src[t.HYPHENRANGE] = '^\\s*(' + src[t.XRANGEPLAIN] + ')' +
'\\s+-\\s+' +
'(' + src[XRANGEPLAIN] + ')' +
'(' + src[t.XRANGEPLAIN] + ')' +
'\\s*$'
var HYPHENRANGELOOSE = R++
src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' +
tok('HYPHENRANGELOOSE')
src[t.HYPHENRANGELOOSE] = '^\\s*(' + src[t.XRANGEPLAINLOOSE] + ')' +
'\\s+-\\s+' +
'(' + src[XRANGEPLAINLOOSE] + ')' +
'(' + src[t.XRANGEPLAINLOOSE] + ')' +
'\\s*$'
// Star ranges basically just allow anything at all.
var STAR = R++
src[STAR] = '(<|>)?=?\\s*\\*'
tok('STAR')
src[t.STAR] = '(<|>)?=?\\s*\\*'
// Compile to actual regexp objects.
// All are flag-free, unless they were created above with a flag.
@ -264,7 +271,7 @@ function parse (version, options) {
return null
}
var r = options.loose ? re[LOOSE] : re[FULL]
var r = options.loose ? re[t.LOOSE] : re[t.FULL]
if (!r.test(version)) {
return null
}
@ -319,7 +326,7 @@ function SemVer (version, options) {
this.options = options
this.loose = !!options.loose
var m = version.trim().match(options.loose ? re[LOOSE] : re[FULL])
var m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL])
if (!m) {
throw new TypeError('Invalid Version: ' + version)
@ -780,7 +787,7 @@ function Comparator (comp, options) {
var ANY = {}
Comparator.prototype.parse = function (comp) {
var r = this.options.loose ? re[COMPARATORLOOSE] : re[COMPARATOR]
var r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]
var m = comp.match(r)
if (!m) {
@ -935,18 +942,18 @@ Range.prototype.parseRange = function (range) {
var loose = this.options.loose
range = range.trim()
// `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE]
var hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]
range = range.replace(hr, hyphenReplace)
debug('hyphen replace', range)
// `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace)
debug('comparator trim', range, re[COMPARATORTRIM])
range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace)
debug('comparator trim', range, re[t.COMPARATORTRIM])
// `~ 1.2.3` => `~1.2.3`
range = range.replace(re[TILDETRIM], tildeTrimReplace)
range = range.replace(re[t.TILDETRIM], tildeTrimReplace)
// `^ 1.2.3` => `^1.2.3`
range = range.replace(re[CARETTRIM], caretTrimReplace)
range = range.replace(re[t.CARETTRIM], caretTrimReplace)
// normalize spaces
range = range.split(/\s+/).join(' ')
@ -954,7 +961,7 @@ Range.prototype.parseRange = function (range) {
// At this point, the range is completely trimmed and
// ready to be split into comparators.
var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR]
var compRe = loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]
var set = range.split(' ').map(function (comp) {
return parseComparator(comp, this.options)
}, this).join(' ').split(/\s+/)
@ -1054,7 +1061,7 @@ function replaceTildes (comp, options) {
}
function replaceTilde (comp, options) {
var r = options.loose ? re[TILDELOOSE] : re[TILDE]
var r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]
return comp.replace(r, function (_, M, m, p, pr) {
debug('tilde', comp, _, M, m, p, pr)
var ret
@ -1095,7 +1102,7 @@ function replaceCarets (comp, options) {
function replaceCaret (comp, options) {
debug('caret', comp, options)
var r = options.loose ? re[CARETLOOSE] : re[CARET]
var r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]
return comp.replace(r, function (_, M, m, p, pr) {
debug('caret', comp, _, M, m, p, pr)
var ret
@ -1154,7 +1161,7 @@ function replaceXRanges (comp, options) {
function replaceXRange (comp, options) {
comp = comp.trim()
var r = options.loose ? re[XRANGELOOSE] : re[XRANGE]
var r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]
return comp.replace(r, function (ret, gtlt, M, m, p, pr) {
debug('xRange', comp, ret, gtlt, M, m, p, pr)
var xM = isX(M)
@ -1229,10 +1236,10 @@ function replaceXRange (comp, options) {
function replaceStars (comp, options) {
debug('replaceStars', comp, options)
// Looseness is ignored here. star is always as loose as it gets!
return comp.trim().replace(re[STAR], '')
return comp.trim().replace(re[t.STAR], '')
}
// This function is passed to string.replace(re[HYPHENRANGE])
// This function is passed to string.replace(re[t.HYPHENRANGE])
// M, m, patch, prerelease, build
// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do
@ -1555,7 +1562,7 @@ function coerce (version, options) {
var match = null
if (!options.rtl) {
match = version.match(re[COERCE])
match = version.match(re[t.COERCE])
} else {
// Find the right-most coercible string that does not share
// a terminus with a more left-ward coercible string.
@ -1566,17 +1573,17 @@ function coerce (version, options) {
// Stop when we get a match that ends at the string end, since no
// coercible string can be more right-ward without the same terminus.
var next
while ((next = re[COERCERTL].exec(version)) &&
while ((next = re[t.COERCERTL].exec(version)) &&
(!match || match.index + match[0].length !== version.length)
) {
if (!match ||
next.index + next[0].length !== match.index + match[0].length) {
match = next
}
re[COERCERTL].lastIndex = next.index + next[1].length + next[2].length
re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length
}
// leave it in a clean state
re[COERCERTL].lastIndex = -1
re[t.COERCERTL].lastIndex = -1
}
if (match === null) {

View File

@ -5,7 +5,9 @@ Object.defineProperty(exports, "__esModule", {
});
exports.default = void 0;
var _lodash = _interopRequireDefault(require("lodash"));
var _isNumber2 = _interopRequireDefault(require("lodash/isNumber"));
var _isString2 = _interopRequireDefault(require("lodash/isString"));
var _stringWidth = _interopRequireDefault(require("string-width"));
@ -61,11 +63,11 @@ const alignCenter = (subject, width) => {
const alignString = (subject, containerWidth, alignment) => {
if (!_lodash.default.isString(subject)) {
if (!(0, _isString2.default)(subject)) {
throw new TypeError('Subject parameter value must be a string.');
}
if (!_lodash.default.isNumber(containerWidth)) {
if (!(0, _isNumber2.default)(containerWidth)) {
throw new TypeError('Container width parameter value must be a number.');
}
@ -76,7 +78,7 @@ const alignString = (subject, containerWidth, alignment) => {
throw new Error('Subject parameter value width cannot be greater than the container width.');
}
if (!_lodash.default.isString(alignment)) {
if (!(0, _isString2.default)(alignment)) {
throw new TypeError('Alignment parameter value must be a string.');
}

View File

@ -5,7 +5,7 @@ Object.defineProperty(exports, "__esModule", {
});
exports.default = void 0;
var _lodash = _interopRequireDefault(require("lodash"));
var _isString2 = _interopRequireDefault(require("lodash/isString"));
var _wrapCell = _interopRequireDefault(require("./wrapCell"));
@ -18,7 +18,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
* @returns {number}
*/
const calculateCellHeight = (value, columnWidth, useWrapWord = false) => {
if (!_lodash.default.isString(value)) {
if (!(0, _isString2.default)(value)) {
throw new TypeError('Value must be a string.');
}

View File

@ -5,7 +5,11 @@ Object.defineProperty(exports, "__esModule", {
});
exports.default = void 0;
var _lodash = _interopRequireDefault(require("lodash"));
var _max2 = _interopRequireDefault(require("lodash/max"));
var _isBoolean2 = _interopRequireDefault(require("lodash/isBoolean"));
var _isNumber2 = _interopRequireDefault(require("lodash/isNumber"));
var _calculateCellHeight = _interopRequireDefault(require("./calculateCellHeight"));
@ -24,17 +28,17 @@ const calculateRowHeightIndex = (rows, config) => {
rows.forEach(cells => {
const cellHeightIndex = new Array(tableWidth).fill(1);
cells.forEach((value, index1) => {
if (!_lodash.default.isNumber(config.columns[index1].width)) {
if (!(0, _isNumber2.default)(config.columns[index1].width)) {
throw new TypeError('column[index].width must be a number.');
}
if (!_lodash.default.isBoolean(config.columns[index1].wrapWord)) {
if (!(0, _isBoolean2.default)(config.columns[index1].wrapWord)) {
throw new TypeError('column[index].wrapWord must be a boolean.');
}
cellHeightIndex[index1] = (0, _calculateCellHeight.default)(value, config.columns[index1].width, config.columns[index1].wrapWord);
});
rowSpanIndex.push(_lodash.default.max(cellHeightIndex));
rowSpanIndex.push((0, _max2.default)(cellHeightIndex));
});
return rowSpanIndex;
};

View File

@ -5,7 +5,11 @@ Object.defineProperty(exports, "__esModule", {
});
exports.default = void 0;
var _lodash = _interopRequireDefault(require("lodash"));
var _mapValues2 = _interopRequireDefault(require("lodash/mapValues"));
var _values2 = _interopRequireDefault(require("lodash/values"));
var _trimEnd2 = _interopRequireDefault(require("lodash/trimEnd"));
var _makeStreamConfig = _interopRequireDefault(require("./makeStreamConfig"));
@ -60,7 +64,7 @@ const create = (row, columnWidthIndex, config) => {
output += (0, _drawBorder.drawBorderTop)(columnWidthIndex, config.border);
output += body;
output += (0, _drawBorder.drawBorderBottom)(columnWidthIndex, config.border);
output = _lodash.default.trimEnd(output);
output = (0, _trimEnd2.default)(output);
process.stdout.write(output);
};
/**
@ -76,12 +80,17 @@ const append = (row, columnWidthIndex, config) => {
const body = rows.map(literalRow => {
return (0, _drawRow.default)(literalRow, config.border);
}).join('');
let output;
output = '\r\u001B[K';
let output = '';
const bottom = (0, _drawBorder.drawBorderBottom)(columnWidthIndex, config.border);
if (bottom !== '\n') {
output = '\r\u001B[K';
}
output += (0, _drawBorder.drawBorderJoin)(columnWidthIndex, config.border);
output += body;
output += (0, _drawBorder.drawBorderBottom)(columnWidthIndex, config.border);
output = _lodash.default.trimEnd(output);
output += bottom;
output = (0, _trimEnd2.default)(output);
process.stdout.write(output);
};
/**
@ -93,10 +102,9 @@ const append = (row, columnWidthIndex, config) => {
const createStream = (userConfig = {}) => {
const config = (0, _makeStreamConfig.default)(userConfig); // @todo Use 'Object.values' when Node.js v6 support is dropped.
const columnWidthIndex = _lodash.default.values(_lodash.default.mapValues(config.columns, column => {
const columnWidthIndex = (0, _values2.default)((0, _mapValues2.default)(config.columns, column => {
return column.width + column.paddingLeft + column.paddingRight;
}));
let empty;
empty = true;
return {

View File

@ -73,13 +73,16 @@ const append = (row, columnWidthIndex, config) => {
return drawRow(literalRow, config.border);
}).join('');
let output;
let output = '';
const bottom = drawBorderBottom(columnWidthIndex, config.border);
output = '\r\u001B[K';
if (bottom !== '\n') {
output = '\r\u001B[K';
}
output += drawBorderJoin(columnWidthIndex, config.border);
output += body;
output += drawBorderBottom(columnWidthIndex, config.border);
output += bottom;
output = _.trimEnd(output);

View File

@ -42,12 +42,18 @@ const drawBorder = (columnSizeIndex, parts) => {
exports.drawBorder = drawBorder;
const drawBorderTop = (columnSizeIndex, parts) => {
return drawBorder(columnSizeIndex, {
const border = drawBorder(columnSizeIndex, {
body: parts.topBody,
join: parts.topJoin,
left: parts.topLeft,
right: parts.topRight
});
if (border === '\n') {
return '';
}
return border;
};
/**
* @typedef drawBorderJoin~parts

View File

@ -35,12 +35,18 @@ const drawBorder = (columnSizeIndex, parts) => {
* @returns {string}
*/
const drawBorderTop = (columnSizeIndex, parts) => {
return drawBorder(columnSizeIndex, {
const border = drawBorder(columnSizeIndex, {
body: parts.topBody,
join: parts.topJoin,
left: parts.topLeft,
right: parts.topRight
});
if (border === '\n') {
return '';
}
return border;
};
/**

View File

@ -5,7 +5,11 @@ Object.defineProperty(exports, "__esModule", {
});
exports.default = void 0;
var _lodash = _interopRequireDefault(require("lodash"));
var _cloneDeep2 = _interopRequireDefault(require("lodash/cloneDeep"));
var _isUndefined2 = _interopRequireDefault(require("lodash/isUndefined"));
var _times2 = _interopRequireDefault(require("lodash/times"));
var _getBorderCharacters = _interopRequireDefault(require("./getBorderCharacters"));
@ -37,9 +41,8 @@ const makeBorder = (border = {}) => {
const makeColumns = (rows, columns = {}, columnDefault = {}) => {
const maximumColumnWidthIndex = (0, _calculateMaximumColumnWidthIndex.default)(rows);
_lodash.default.times(rows[0].length, index => {
if (_lodash.default.isUndefined(columns[index])) {
(0, _times2.default)(rows[0].length, index => {
if ((0, _isUndefined2.default)(columns[index])) {
columns[index] = {};
}
@ -52,7 +55,6 @@ const makeColumns = (rows, columns = {}, columnDefault = {}) => {
wrapWord: false
}, columnDefault, columns[index]);
});
return columns;
};
/**
@ -67,9 +69,7 @@ const makeColumns = (rows, columns = {}, columnDefault = {}) => {
const makeConfig = (rows, userConfig = {}) => {
(0, _validateConfig.default)('config.json', userConfig);
const config = _lodash.default.cloneDeep(userConfig);
const config = (0, _cloneDeep2.default)(userConfig);
config.border = makeBorder(config.border);
config.columns = makeColumns(rows, config.columns, config.columnDefault);

View File

@ -5,7 +5,11 @@ Object.defineProperty(exports, "__esModule", {
});
exports.default = void 0;
var _lodash = _interopRequireDefault(require("lodash"));
var _cloneDeep2 = _interopRequireDefault(require("lodash/cloneDeep"));
var _isUndefined2 = _interopRequireDefault(require("lodash/isUndefined"));
var _times2 = _interopRequireDefault(require("lodash/times"));
var _getBorderCharacters = _interopRequireDefault(require("./getBorderCharacters"));
@ -34,8 +38,8 @@ const makeBorder = (border = {}) => {
const makeColumns = (columnCount, columns = {}, columnDefault = {}) => {
_lodash.default.times(columnCount, index => {
if (_lodash.default.isUndefined(columns[index])) {
(0, _times2.default)(columnCount, index => {
if ((0, _isUndefined2.default)(columns[index])) {
columns[index] = {};
}
@ -47,7 +51,6 @@ const makeColumns = (columnCount, columns = {}, columnDefault = {}) => {
wrapWord: false
}, columnDefault, columns[index]);
});
return columns;
};
/**
@ -78,8 +81,7 @@ const makeColumns = (columnCount, columns = {}, columnDefault = {}) => {
const makeStreamConfig = (userConfig = {}) => {
(0, _validateConfig.default)('streamConfig.json', userConfig);
const config = _lodash.default.cloneDeep(userConfig);
const config = (0, _cloneDeep2.default)(userConfig);
if (!config.columnDefault || !config.columnDefault.width) {
throw new Error('Must provide config.columnDefault.width when creating a stream.');

View File

@ -5,7 +5,9 @@ Object.defineProperty(exports, "__esModule", {
});
exports.default = void 0;
var _lodash = _interopRequireDefault(require("lodash"));
var _flatten2 = _interopRequireDefault(require("lodash/flatten"));
var _times2 = _interopRequireDefault(require("lodash/times"));
var _wrapCell = _interopRequireDefault(require("./wrapCell"));
@ -20,13 +22,12 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
const mapDataUsingRowHeightIndex = (unmappedRows, rowHeightIndex, config) => {
const tableWidth = unmappedRows[0].length;
const mappedRows = unmappedRows.map((cells, index0) => {
const rowHeight = _lodash.default.times(rowHeightIndex[index0], () => {
const rowHeight = (0, _times2.default)(rowHeightIndex[index0], () => {
return new Array(tableWidth).fill('');
}); // rowHeight
// [{row index within rowSaw; index2}]
// [{cell index within a virtual row; index1}]
cells.forEach((value, index1) => {
const cellLines = (0, _wrapCell.default)(value, config.columns[index1].width, config.columns[index1].wrapWord);
cellLines.forEach((cellLine, index2) => {
@ -35,7 +36,7 @@ const mapDataUsingRowHeightIndex = (unmappedRows, rowHeightIndex, config) => {
});
return rowHeight;
});
return _lodash.default.flatten(mappedRows);
return (0, _flatten2.default)(mappedRows);
};
var _default = mapDataUsingRowHeightIndex;

View File

@ -5,7 +5,7 @@ Object.defineProperty(exports, "__esModule", {
});
exports.default = void 0;
var _lodash = _interopRequireDefault(require("lodash"));
var _truncate2 = _interopRequireDefault(require("lodash/truncate"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
@ -18,7 +18,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
const truncateTableData = (rows, config) => {
return rows.map(cells => {
return cells.map((content, index) => {
return _lodash.default.truncate(content, {
return (0, _truncate2.default)(content, {
length: config.columns[index].truncate
});
});

View File

@ -26,6 +26,7 @@
"ajv-cli": "^3.0.0",
"ajv-keywords": "^3.4.1",
"babel-plugin-istanbul": "^5.1.4",
"babel-plugin-lodash": "^3.3.4",
"babel-plugin-transform-export-default-name": "^2.0.4",
"chai": "^4.2.0",
"chalk": "^2.4.2",
@ -85,5 +86,5 @@
"lint": "npm run build && eslint ./src ./test && flow",
"test": "mocha --require @babel/register"
},
"version": "5.4.4"
"version": "5.4.6"
}

View File

@ -46,7 +46,7 @@ tmp.file(function _tempFileCreated(err, path, fd, cleanupCallback) {
console.log('File: ', path);
console.log('Filedescriptor: ', fd);
// If we don't need the file anymore we could manually call the cleanupCallback
// But that is not necessary if we didn't pass the keep option because the library
// will clean after itself.
@ -64,7 +64,7 @@ var tmp = require('tmp');
var tmpobj = tmp.fileSync();
console.log('File: ', tmpobj.name);
console.log('Filedescriptor: ', tmpobj.fd);
// If we don't need the file anymore we could manually call the removeCallback
// But that is not necessary if we didn't pass the keep option because the library
// will clean after itself.
@ -88,7 +88,7 @@ tmp.dir(function _tempDirCreated(err, path, cleanupCallback) {
if (err) throw err;
console.log('Dir: ', path);
// Manual cleanup
cleanupCallback();
});

View File

@ -268,7 +268,7 @@ function fileSync(options) {
const name = tmpNameSync(opts);
var fd = fs.openSync(name, CREATE_FLAGS, opts.mode || FILE_MODE);
if (opts.discardDescriptor) {
fs.closeSync(fd);
fs.closeSync(fd);
fd = undefined;
}

View File

@ -102,19 +102,19 @@ You will need to add a `paths` mapping for `tslib`, e.g. For Bower users:
For JSPM users:
```json
{
"compilerOptions": {
"module": "system",
"importHelpers": true,
"baseUrl": "./",
"paths": {
"tslib" : ["jspm_packages/npm/tslib@1.10.0/tslib.d.ts"]
}
}
}
```
{
"compilerOptions": {
"module": "system",
"importHelpers": true,
"baseUrl": "./",
"paths": {
"tslib" : ["jspm_packages/npm/tslib@1.10.0/tslib.d.ts"]
}
}
}
```
# Contribute
There are many ways to [contribute](https://github.com/Microsoft/TypeScript/blob/master/CONTRIBUTING.md) to TypeScript.

View File

@ -37,22 +37,22 @@ export var __assign = function() {
}
return __assign.apply(this, arguments);
}
export function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
}
export function __decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
export function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
}
export function __decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
@ -134,26 +134,26 @@ export function __read(o, n) {
return ar;
}
export function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
}
export function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
export function __await(v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
}
export function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
export function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
}
export function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
export function __await(v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
}
export function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }

View File

@ -19,19 +19,19 @@ var __rest;
var __decorate;
var __param;
var __metadata;
var __awaiter;
var __generator;
var __exportStar;
var __values;
var __read;
var __spread;
var __spreadArrays;
var __await;
var __asyncGenerator;
var __asyncDelegator;
var __asyncValues;
var __makeTemplateObject;
var __importStar;
var __awaiter;
var __generator;
var __exportStar;
var __values;
var __read;
var __spread;
var __spreadArrays;
var __await;
var __asyncGenerator;
var __asyncDelegator;
var __asyncValues;
var __makeTemplateObject;
var __importStar;
var __importDefault;
(function (factory) {
var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {};
@ -74,22 +74,22 @@ var __importDefault;
}
return t;
};
__rest = function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
__decorate = function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
__rest = function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
__decorate = function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
@ -171,26 +171,26 @@ var __importDefault;
return ar;
};
__spread = function () {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
};
__spreadArrays = function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
__await = function (v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
};
__asyncGenerator = function (thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
__spread = function () {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
};
__spreadArrays = function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
__await = function (v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
};
__asyncGenerator = function (thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
@ -238,18 +238,18 @@ var __importDefault;
exporter("__decorate", __decorate);
exporter("__param", __param);
exporter("__metadata", __metadata);
exporter("__awaiter", __awaiter);
exporter("__generator", __generator);
exporter("__exportStar", __exportStar);
exporter("__values", __values);
exporter("__read", __read);
exporter("__spread", __spread);
exporter("__spreadArrays", __spreadArrays);
exporter("__await", __await);
exporter("__asyncGenerator", __asyncGenerator);
exporter("__asyncDelegator", __asyncDelegator);
exporter("__asyncValues", __asyncValues);
exporter("__makeTemplateObject", __makeTemplateObject);
exporter("__importStar", __importStar);
exporter("__awaiter", __awaiter);
exporter("__generator", __generator);
exporter("__exportStar", __exportStar);
exporter("__values", __values);
exporter("__read", __read);
exporter("__spread", __spread);
exporter("__spreadArrays", __spreadArrays);
exporter("__await", __await);
exporter("__asyncGenerator", __asyncGenerator);
exporter("__asyncDelegator", __asyncDelegator);
exporter("__asyncValues", __asyncValues);
exporter("__makeTemplateObject", __makeTemplateObject);
exporter("__importStar", __importStar);
exporter("__importDefault", __importDefault);
});

View File

@ -46,7 +46,7 @@ _^ Includes the overhead of loading the cache itself._
## Acknowledgements
* `FileSystemBlobStore` and `NativeCompileCache` are based on Atom's implementation of their v8 compile cache:
* `FileSystemBlobStore` and `NativeCompileCache` are based on Atom's implementation of their v8 compile cache:
- https://github.com/atom/atom/blob/b0d7a8a/src/file-system-blob-store.js
- https://github.com/atom/atom/blob/b0d7a8a/src/native-compile-cache.js
* `mkdirpSync` is based on:

View File

@ -38,5 +38,5 @@
"posttest": "npm run lint",
"test": "tap test/*-test.js"
},
"version": "2.0.3"
"version": "2.1.0"
}

View File

@ -188,7 +188,9 @@ class NativeCompileCache {
// We skip the debugger setup because by the time we run, node has already
// done that itself.
const args = [mod.exports, require, mod, filename, dirname, process, global];
// `Buffer` is included for Electron.
// See https://github.com/zertosh/v8-compile-cache/pull/10#issuecomment-518042543
const args = [mod.exports, require, mod, filename, dirname, process, global, Buffer];
return compiledWrapper.apply(mod.exports, args);
};
}

View File

@ -25,7 +25,7 @@ var combination = extend({
## Stability status: Locked
## MIT Licensed
## MIT Licensed
[3]: http://ci.testling.com/Raynos/xtend.png

View File

@ -19,9 +19,9 @@
"doctrine": "^3.0.0",
"eslint-plugin-markdown": "^1.0.0",
"eslint-scope": "^5.0.0",
"eslint-utils": "^1.3.1",
"eslint-visitor-keys": "^1.0.0",
"espree": "^6.0.0",
"eslint-utils": "^1.4.2",
"eslint-visitor-keys": "^1.1.0",
"espree": "^6.1.1",
"esquery": "^1.0.1",
"esutils": "^2.0.2",
"file-entry-cache": "^5.0.1",
@ -55,7 +55,7 @@
"devDependencies": {
"@babel/core": "^7.4.3",
"@babel/preset-env": "^7.4.3",
"acorn": "^6.1.1",
"acorn": "^7.0.0",
"babel-loader": "^8.0.5",
"chai": "^4.0.1",
"cheerio": "^0.22.0",
@ -149,5 +149,5 @@
"test": "node Makefile.js test",
"webpack": "node Makefile.js webpack"
},
"version": "6.1.0"
"version": "6.2.2"
}