tools: update ESLint to 5.10.0

Update ESLint to 5.10.0.

PR-URL: https://github.com/nodejs/node/pull/24903
Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de>
Reviewed-By: Michaël Zasso <targos@protonmail.com>
Reviewed-By: Franziska Hinkelmann <franziska.hinkelmann@gmail.com>
This commit is contained in:
cjihrig 2018-12-08 08:42:29 -05:00
parent 4aabd7ed64
commit cc8250fab8
No known key found for this signature in database
GPG Key ID: 7434390BDBE9B9C5
139 changed files with 1654 additions and 3229 deletions

View File

@ -38,7 +38,7 @@ If you want to include ESLint as part of your project's build system, we recomme
$ npm install eslint --save-dev
```
You should then setup a configuration file:
You should then set up a configuration file:
```
$ ./node_modules/.bin/eslint --init
@ -60,7 +60,7 @@ If you want to make ESLint available to tools that run across all of your projec
$ npm install -g eslint
```
You should then setup a configuration file:
You should then set up a configuration file:
```
$ eslint --init

View File

@ -20,7 +20,7 @@ const fs = require("fs"),
defaultOptions = require("../conf/default-cli-options"),
Linter = require("./linter"),
lodash = require("lodash"),
IgnoredPaths = require("./ignored-paths"),
IgnoredPaths = require("./util/ignored-paths"),
Config = require("./config"),
ConfigOps = require("./config/config-ops"),
LintResultCache = require("./util/lint-result-cache"),

View File

@ -15,8 +15,7 @@ const path = require("path"),
ConfigFile = require("./config/config-file"),
ConfigCache = require("./config/config-cache"),
Plugins = require("./config/plugins"),
FileFinder = require("./util/file-finder"),
isResolvable = require("is-resolvable");
FileFinder = require("./util/file-finder");
const debug = require("debug")("eslint:config");
@ -41,6 +40,20 @@ function hasRules(options) {
return options.rules && Object.keys(options.rules).length > 0;
}
/**
* Determines if a module is can be resolved.
* @param {string} moduleId The ID (name) of the module
* @returns {boolean} True if it is resolvable; False otherwise.
*/
function isResolvable(moduleId) {
try {
require.resolve(moduleId);
return true;
} catch (err) {
return false;
}
}
//------------------------------------------------------------------------------
// API
//------------------------------------------------------------------------------

View File

@ -102,7 +102,6 @@ class Registry {
*
* The length of the returned array will be <= MAX_CONFIG_COMBINATIONS.
*
* @param {Object} registry The autoconfig registry
* @returns {Object[]} "rules" configurations to use for linting
*/
buildRuleSets() {

View File

@ -37,9 +37,9 @@ function explodeArray(xs) {
* For example:
* combineArrays([a, [b, c]], [x, y]); // -> [[a, x], [a, y], [b, c, x], [b, c, y]]
*
* @param {array} arr1 The first array to combine.
* @param {array} arr2 The second array to combine.
* @returns {array} A mixture of the elements of the first and second arrays.
* @param {Array} arr1 The first array to combine.
* @param {Array} arr2 The second array to combine.
* @returns {Array} A mixture of the elements of the first and second arrays.
*/
function combineArrays(arr1, arr2) {
const res = [];
@ -268,7 +268,7 @@ class RuleConfigSet {
/**
* Generate valid rule configurations based on a schema object
* @param {Object} schema A rule's schema object
* @returns {array[]} Valid rule configurations
* @returns {Array[]} Valid rule configurations
*/
function generateConfigsFromSchema(schema) {
const configSet = new RuleConfigSet();

View File

@ -83,7 +83,7 @@ function validateRuleSeverity(options) {
/**
* Validates the non-severity options passed to a rule, based on its schema.
* @param {{create: Function}} rule The rule to validate
* @param {array} localOptions The options for the rule, excluding severity
* @param {Array} localOptions The options for the rule, excluding severity
* @returns {void}
*/
function validateRuleSchema(rule, localOptions) {
@ -111,7 +111,7 @@ function validateRuleSchema(rule, localOptions) {
* Validates a rule's options against its schema.
* @param {{create: Function}|null} rule The rule that the config is being validated for
* @param {string} ruleId The rule's unique name.
* @param {array|number} options The given options for the rule.
* @param {Array|number} options The given options for the rule.
* @param {string|null} source The name of the configuration source to report in any errors. If null or undefined,
* no source is prepended to the message.
* @returns {void}

View File

@ -11,7 +11,6 @@
const eslintScope = require("eslint-scope"),
evk = require("eslint-visitor-keys"),
levn = require("levn"),
lodash = require("lodash"),
CodePathAnalyzer = require("./code-path-analysis/code-path-analyzer"),
ConfigOps = require("./config/config-ops"),
@ -22,9 +21,10 @@ const eslintScope = require("eslint-scope"),
NodeEventGenerator = require("./util/node-event-generator"),
SourceCode = require("./util/source-code"),
Traverser = require("./util/traverser"),
createReportTranslator = require("./report-translator"),
createReportTranslator = require("./util/report-translator"),
Rules = require("./rules"),
timing = require("./util/timing"),
ConfigCommentParser = require("./util/config-comment-parser"),
astUtils = require("./util/ast-utils"),
pkg = require("../package.json"),
SourceCodeFixer = require("./util/source-code-fixer");
@ -32,6 +32,7 @@ const eslintScope = require("eslint-scope"),
const debug = require("debug")("eslint:linter");
const MAX_AUTOFIX_PASSES = 10;
const DEFAULT_PARSER_NAME = "espree";
const commentParser = new ConfigCommentParser();
//------------------------------------------------------------------------------
// Typedefs
@ -59,117 +60,6 @@ const DEFAULT_PARSER_NAME = "espree";
// Helpers
//------------------------------------------------------------------------------
/**
* Parses a list of "name:boolean_value" or/and "name" options divided by comma or
* whitespace.
* @param {string} string The string to parse.
* @param {Comment} comment The comment node which has the string.
* @returns {Object} Result map object of names and boolean values
*/
function parseBooleanConfig(string, comment) {
const items = {};
// Collapse whitespace around `:` and `,` to make parsing easier
const trimmedString = string.replace(/\s*([:,])\s*/g, "$1");
trimmedString.split(/\s|,+/).forEach(name => {
if (!name) {
return;
}
const pos = name.indexOf(":");
if (pos === -1) {
items[name] = {
value: false,
comment
};
} else {
items[name.slice(0, pos)] = {
value: name.slice(pos + 1) === "true",
comment
};
}
});
return items;
}
/**
* Parses a JSON-like config.
* @param {string} string The string to parse.
* @param {Object} location Start line and column of comments for potential error message.
* @returns {({success: true, config: Object}|{success: false, error: Problem})} Result map object
*/
function parseJsonConfig(string, location) {
let items = {};
// Parses a JSON-like comment by the same way as parsing CLI option.
try {
items = levn.parse("Object", string) || {};
// Some tests say that it should ignore invalid comments such as `/*eslint no-alert:abc*/`.
// Also, commaless notations have invalid severity:
// "no-alert: 2 no-console: 2" --> {"no-alert": "2 no-console: 2"}
// Should ignore that case as well.
if (ConfigOps.isEverySeverityValid(items)) {
return {
success: true,
config: items
};
}
} catch (ex) {
// ignore to parse the string by a fallback.
}
/*
* Optionator cannot parse commaless notations.
* But we are supporting that. So this is a fallback for that.
*/
items = {};
const normalizedString = string.replace(/([a-zA-Z0-9\-/]+):/g, "\"$1\":").replace(/(]|[0-9])\s+(?=")/, "$1,");
try {
items = JSON.parse(`{${normalizedString}}`);
} catch (ex) {
return {
success: false,
error: {
ruleId: null,
fatal: true,
severity: 2,
message: `Failed to parse JSON from '${normalizedString}': ${ex.message}`,
line: location.start.line,
column: location.start.column + 1
}
};
}
return {
success: true,
config: items
};
}
/**
* Parses a config of values separated by comma.
* @param {string} string The string to parse.
* @returns {Object} Result map of values and true values
*/
function parseListConfig(string) {
const items = {};
// Collapse whitespace around ,
string.replace(/\s*,\s*/g, ",").split(/,+/).forEach(name => {
const trimmedName = name.trim();
if (trimmedName) {
items[trimmedName] = true;
}
});
return items;
}
/**
* Ensures that variables representing built-in properties of the Global Object,
* and any globals declared by special block comments, are present in the global
@ -248,7 +138,7 @@ function addDeclaredGlobals(globalScope, configGlobals, commentDirectives) {
* @returns {DisableDirective[]} Directives from the comment
*/
function createDisableDirectives(type, loc, value) {
const ruleIds = Object.keys(parseListConfig(value));
const ruleIds = Object.keys(commentParser.parseListConfig(value));
const directiveRules = ruleIds.length ? ruleIds : [null];
return directiveRules.map(ruleId => ({ type, line: loc.line, column: loc.column + 1, ruleId }));
@ -301,12 +191,12 @@ function getDirectiveComments(filename, ast, ruleMapper) {
} else if (comment.type === "Block") {
switch (match[1]) {
case "exported":
Object.assign(exportedVariables, parseBooleanConfig(directiveValue, comment));
Object.assign(exportedVariables, commentParser.parseBooleanConfig(directiveValue, comment));
break;
case "globals":
case "global":
Object.assign(enabledGlobals, parseBooleanConfig(directiveValue, comment));
Object.assign(enabledGlobals, commentParser.parseBooleanConfig(directiveValue, comment));
break;
case "eslint-disable":
@ -318,7 +208,7 @@ function getDirectiveComments(filename, ast, ruleMapper) {
break;
case "eslint": {
const parseResult = parseJsonConfig(directiveValue, comment.loc);
const parseResult = commentParser.parseJsonConfig(directiveValue, comment.loc);
if (parseResult.success) {
Object.keys(parseResult.config).forEach(name => {
@ -398,7 +288,7 @@ function findEslintEnv(text) {
eslintEnvPattern.lastIndex = 0;
while ((match = eslintEnvPattern.exec(text))) {
retv = Object.assign(retv || {}, parseListConfig(match[1]));
retv = Object.assign(retv || {}, commentParser.parseListConfig(match[1]));
}
return retv;
@ -1032,8 +922,6 @@ module.exports = class Linter {
* @param {(string|Object)} [filenameOrOptions] The optional filename of the file being checked.
* If this is not set, the filename will default to '<input>' in the rule context. If
* an object, then it has "filename", "saveState", and "allowInlineConfig" properties.
* @param {boolean} [saveState] Indicates if the state from the last run should be saved.
* Mostly useful for testing purposes.
* @param {boolean} [filenameOrOptions.allowInlineConfig] Allow/disallow inline comments' ability to change config once it is set. Defaults to true if not supplied.
* Useful if you want to validate JS without comments overriding rules.
* @param {function(string): string[]} [filenameOrOptions.preprocess] preprocessor for source text. If provided,

View File

@ -173,7 +173,6 @@ module.exports = {
* Reports a given node if it violated this rule.
*
* @param {ASTNode} node - A node to check. This is an ObjectExpression node or an ObjectPattern node.
* @param {{multiline: boolean, minItems: number}} options - An option object.
* @returns {void}
*/
function check(node) {

View File

@ -132,9 +132,10 @@ module.exports = {
/*
* Leading and trailing underscores are commonly used to flag
* private/protected identifiers, strip them
* private/protected identifiers, strip them before checking if underscored
*/
const name = node.name.replace(/^_+|_+$/g, ""),
const name = node.name,
nameIsUnderscored = isUnderscored(name.replace(/^_+|_+$/g, "")),
effectiveParent = (node.parent.type === "MemberExpression") ? node.parent.parent : node.parent;
// First, we ignore the node if it match the ignore list
@ -151,11 +152,11 @@ module.exports = {
}
// Always report underscored object names
if (node.parent.object.type === "Identifier" && node.parent.object.name === node.name && isUnderscored(name)) {
if (node.parent.object.type === "Identifier" && node.parent.object.name === node.name && nameIsUnderscored) {
report(node);
// Report AssignmentExpressions only if they are the left side of the assignment
} else if (effectiveParent.type === "AssignmentExpression" && isUnderscored(name) && (effectiveParent.right.type !== "MemberExpression" || effectiveParent.left.type === "MemberExpression" && effectiveParent.left.property.name === node.name)) {
} else if (effectiveParent.type === "AssignmentExpression" && nameIsUnderscored && (effectiveParent.right.type !== "MemberExpression" || effectiveParent.left.type === "MemberExpression" && effectiveParent.left.property.name === node.name)) {
report(node);
}
@ -167,7 +168,7 @@ module.exports = {
} else if (node.parent.type === "Property" || node.parent.type === "AssignmentPattern") {
if (node.parent.parent && node.parent.parent.type === "ObjectPattern") {
if (node.parent.shorthand && node.parent.value.left && isUnderscored(name)) {
if (node.parent.shorthand && node.parent.value.left && nameIsUnderscored) {
report(node);
}
@ -179,7 +180,7 @@ module.exports = {
return;
}
const valueIsUnderscored = node.parent.value.name && isUnderscored(name);
const valueIsUnderscored = node.parent.value.name && nameIsUnderscored;
// ignore destructuring if the option is set, unless a new identifier is created
if (valueIsUnderscored && !(assignmentKeyEqualsValue && ignoreDestructuring)) {
@ -193,7 +194,7 @@ module.exports = {
}
// don't check right hand side of AssignmentExpression to prevent duplicate warnings
if (isUnderscored(name) && !ALLOWED_PARENT_TYPES.has(effectiveParent.type) && !(node.parent.right === node)) {
if (nameIsUnderscored && !ALLOWED_PARENT_TYPES.has(effectiveParent.type) && !(node.parent.right === node)) {
report(node);
}
@ -201,12 +202,12 @@ module.exports = {
} else if (["ImportSpecifier", "ImportNamespaceSpecifier", "ImportDefaultSpecifier"].indexOf(node.parent.type) >= 0) {
// Report only if the local imported identifier is underscored
if (node.parent.local && node.parent.local.name === node.name && isUnderscored(name)) {
if (node.parent.local && node.parent.local.name === node.name && nameIsUnderscored) {
report(node);
}
// Report anything that is underscored that isn't a CallExpression
} else if (isUnderscored(name) && !ALLOWED_PARENT_TYPES.has(effectiveParent.type)) {
} else if (nameIsUnderscored && !ALLOWED_PARENT_TYPES.has(effectiveParent.type)) {
report(node);
}
}

View File

@ -85,7 +85,7 @@ module.exports = {
function getReplacedText(styleType, text) {
switch (styleType) {
case "between":
return `,${text.replace("\n", "")}`;
return `,${text.replace(astUtils.LINEBREAK_MATCHER, "")}`;
case "first":
return `${text},`;
@ -138,6 +138,11 @@ module.exports = {
} else if (!astUtils.isTokenOnSameLine(commaToken, currentItemToken) &&
!astUtils.isTokenOnSameLine(previousItemToken, commaToken)) {
const comment = sourceCode.getCommentsAfter(commaToken)[0];
const styleType = comment && comment.type === "Block" && astUtils.isTokenOnSameLine(commaToken, comment)
? style
: "between";
// lone comma
context.report({
node: reportItem,
@ -146,7 +151,7 @@ module.exports = {
column: commaToken.loc.start.column
},
messageId: "unexpectedLineBeforeAndAfterComma",
fix: getFixerFunction("between", previousItemToken, commaToken, currentItemToken)
fix: getFixerFunction(styleType, previousItemToken, commaToken, currentItemToken)
});
} else if (style === "first" && !astUtils.isTokenOnSameLine(commaToken, currentItemToken)) {

View File

@ -119,7 +119,6 @@ module.exports = {
/**
* Gets the location (line and column) of the binary expression's operator
* @param {ASTNode} node The binary expression node to check
* @param {string} operator The operator to find
* @returns {Object} { line, column } location of operator
* @private
*/

View File

@ -59,7 +59,7 @@ module.exports = {
/**
* Get the parameters of a given function scope.
* @param {Object} scope The function scope.
* @returns {array} All parameters of the given scope.
* @returns {Array} All parameters of the given scope.
*/
function getParameters(scope) {
return scope.variables.filter(variable => variable.defs[0] && variable.defs[0].type === "Parameter");

View File

@ -44,7 +44,6 @@ module.exports = {
/**
* Validates the location of an arrow function body
* @param {ASTNode} node The arrow function body
* @param {string} keywordName The applicable keyword name for the arrow function body
* @returns {void}
*/
function validateExpression(node) {

View File

@ -300,7 +300,6 @@ module.exports = {
* @param {int} gottenTabs Indentation tab count in the actual node/code
* @param {Object=} loc Error line and column location
* @param {boolean} isLastNodeCheck Is the error for last node check
* @param {int} lastNodeCheckEndOffset Number of charecters to skip from the end
* @returns {void}
*/
function report(node, needed, gottenSpaces, gottenTabs, loc, isLastNodeCheck) {
@ -365,7 +364,6 @@ module.exports = {
* Check indent for node
* @param {ASTNode} node Node to check
* @param {int} neededIndent needed indent
* @param {boolean} [excludeCommas=false] skip comma on start of line
* @returns {void}
*/
function checkNodeIndent(node, neededIndent) {
@ -413,7 +411,6 @@ module.exports = {
* Check indent for nodes list
* @param {ASTNode[]} nodes list of node objects
* @param {int} indent needed indent
* @param {boolean} [excludeCommas=false] skip comma on start of line
* @returns {void}
*/
function checkNodesIndent(nodes, indent) {

View File

@ -1229,9 +1229,13 @@ module.exports = {
}
const fromToken = sourceCode.getLastToken(node, token => token.type === "Identifier" && token.value === "from");
const sourceToken = sourceCode.getLastToken(node, token => token.type === "String");
const semiToken = sourceCode.getLastToken(node, token => token.type === "Punctuator" && token.value === ";");
if (fromToken) {
offsets.setDesiredOffsets([fromToken.range[0], node.range[1]], sourceCode.getFirstToken(node), 1);
const end = semiToken && semiToken.range[1] === sourceToken.range[1] ? node.range[1] : sourceToken.range[1];
offsets.setDesiredOffsets([fromToken.range[0], end], sourceCode.getFirstToken(node), 1);
}
},

View File

@ -453,6 +453,10 @@ module.exports = {
checkSpacingBefore(firstToken, PREV_TOKEN_M);
checkSpacingAfter(firstToken, NEXT_TOKEN_M);
if (node.type === "ExportDefaultDeclaration") {
checkSpacingAround(sourceCode.getTokenAfter(firstToken));
}
if (node.source) {
const fromToken = sourceCode.getTokenBefore(node.source);
@ -554,7 +558,7 @@ module.exports = {
// Statements - Declarations
ClassDeclaration: checkSpacingForClass,
ExportNamedDeclaration: checkSpacingForModuleDeclaration,
ExportDefaultDeclaration: checkSpacingAroundFirstToken,
ExportDefaultDeclaration: checkSpacingForModuleDeclaration,
ExportAllDeclaration: checkSpacingForModuleDeclaration,
FunctionDeclaration: checkSpacingForFunction,
ImportDeclaration: checkSpacingForModuleDeclaration,

View File

@ -36,7 +36,7 @@ module.exports = {
/**
* Tests whether node is preceded by supplied tokens
* @param {ASTNode} node - node to check
* @param {array} testTokens - array of tokens to test against
* @param {Array} testTokens - array of tokens to test against
* @returns {boolean} Whether or not the node is preceded by one of the supplied tokens
* @private
*/

View File

@ -173,7 +173,6 @@ module.exports = {
/**
* Reports when the set still contains stored constant conditions
* @param {ASTNode} node The AST node to check.
* @returns {void}
* @private
*/

View File

@ -183,7 +183,6 @@ module.exports = {
* code paths.
*
* @param {Node} node The consequent or body node
* @param {Node} alternate The alternate node
* @returns {boolean} `true` if it is a Return/If node that always returns.
*/
function checkForReturnOrIf(node) {

View File

@ -38,7 +38,7 @@ module.exports = {
/**
* Get the last element of an array, without modifying arr, like pop(), but non-destructive.
* @param {array} arr What to inspect
* @param {Array} arr What to inspect
* @returns {*} The last element of arr
* @private
*/

View File

@ -195,7 +195,7 @@ module.exports = {
/**
* Check if the given importNames are restricted given a list of restrictedImportNames.
* @param {Set.<string>} importNames - Set of import names that are being imported
* @param {[string]} restrictedImportNames - array of import names that are restricted for this import
* @param {string[]} restrictedImportNames - array of import names that are restricted for this import
* @returns {boolean} whether the objectName is restricted
* @private
*/

View File

@ -171,7 +171,6 @@ module.exports = {
* invalid node.
*
* @param {CodePath} codePath - A code path which was ended.
* @param {ASTNode} node - The current node.
* @returns {void}
*/
onCodePathEnd(codePath) {

View File

@ -172,7 +172,6 @@ module.exports = {
/**
* Reports a given node if it violated this rule.
* @param {ASTNode} node - A node to check. This is an ObjectExpression, ObjectPattern, ImportDeclaration or ExportNamedDeclaration node.
* @param {{multiline: boolean, minProperties: number, consistent: boolean}} options - An option object.
* @returns {void}
*/
function check(node) {

View File

@ -310,7 +310,6 @@ module.exports = {
/**
* Fixer to split a VariableDeclaration into individual declarations
* @param {VariableDeclaration} declaration The `VariableDeclaration` to split
* @param {?Function} filter Function to filter the declarations
* @returns {Function} The fixer function
*/
function splitDeclarations(declaration) {

View File

@ -36,6 +36,36 @@ function newKeywordTester(keyword) {
};
}
/**
* Creates tester which check if a node starts with specific keyword and spans a single line.
*
* @param {string} keyword The keyword to test.
* @returns {Object} the created tester.
* @private
*/
function newSinglelineKeywordTester(keyword) {
return {
test: (node, sourceCode) =>
node.loc.start.line === node.loc.end.line &&
sourceCode.getFirstToken(node).value === keyword
};
}
/**
* Creates tester which check if a node starts with specific keyword and spans multiple lines.
*
* @param {string} keyword The keyword to test.
* @returns {Object} the created tester.
* @private
*/
function newMultilineKeywordTester(keyword) {
return {
test: (node, sourceCode) =>
node.loc.start.line !== node.loc.end.line &&
sourceCode.getFirstToken(node).value === keyword
};
}
/**
* Creates tester which check if a node is specific type.
*
@ -368,6 +398,13 @@ const StatementTypes = {
!isDirectivePrologue(node, sourceCode)
},
"multiline-const": newMultilineKeywordTester("const"),
"multiline-let": newMultilineKeywordTester("let"),
"multiline-var": newMultilineKeywordTester("var"),
"singleline-const": newSinglelineKeywordTester("const"),
"singleline-let": newSinglelineKeywordTester("let"),
"singleline-var": newSinglelineKeywordTester("var"),
block: newNodeTypeTester("BlockStatement"),
empty: newNodeTypeTester("EmptyStatement"),
function: newNodeTypeTester("FunctionDeclaration"),

View File

@ -228,6 +228,34 @@ module.exports = {
}
}
/**
* Checks whether or not a given TemplateLiteral node is actually using any of the special features provided by template literal strings.
* @param {ASTNode} node - A TemplateLiteral node to check.
* @returns {boolean} Whether or not the TemplateLiteral node is using any of the special features provided by template literal strings.
* @private
*/
function isUsingFeatureOfTemplateLiteral(node) {
const hasTag = node.parent.type === "TaggedTemplateExpression" && node === node.parent.quasi;
if (hasTag) {
return true;
}
const hasStringInterpolation = node.expressions.length > 0;
if (hasStringInterpolation) {
return true;
}
const isMultilineString = node.quasis.length >= 1 && UNESCAPED_LINEBREAK_PATTERN.test(node.quasis[0].value.raw);
if (isMultilineString) {
return true;
}
return false;
}
return {
Literal(node) {
@ -260,19 +288,15 @@ module.exports = {
TemplateLiteral(node) {
// If backticks are expected or it's a tagged template, then this shouldn't throw an errors
// Don't throw an error if backticks are expected or a template literal feature is in use.
if (
allowTemplateLiterals ||
quoteOption === "backtick" ||
node.parent.type === "TaggedTemplateExpression" && node === node.parent.quasi
isUsingFeatureOfTemplateLiteral(node)
) {
return;
}
// A warning should be produced if the template literal only has one TemplateElement, and has no unescaped newlines.
const shouldWarn = node.quasis.length === 1 && !UNESCAPED_LINEBREAK_PATTERN.test(node.quasis[0].value.raw);
if (shouldWarn) {
context.report({
node,
message: "Strings must use {{description}}.",
@ -293,7 +317,6 @@ module.exports = {
}
});
}
}
};
}

View File

@ -43,7 +43,10 @@ module.exports = {
},
additionalProperties: false
}
]
],
deprecated: true,
replacedBy: []
},
create(context) {

View File

@ -61,7 +61,6 @@ module.exports = {
/**
* Produces an object with the opener and closer exception values
* @param {Object} opts The exception options
* @returns {Object} `openers` and `closers` exception values
* @private
*/

View File

@ -69,7 +69,10 @@ module.exports = {
context.report({
node: mainNode,
loc: culpritToken.loc.start,
message: "Infix operators must be spaced.",
message: "Operator '{{operator}}' must be spaced.",
data: {
operator: culpritToken.value
},
fix(fixer) {
const previousToken = sourceCode.getTokenBefore(culpritToken);
const afterToken = sourceCode.getTokenAfter(culpritToken);

View File

@ -64,7 +64,10 @@ module.exports = {
}
],
fixable: "code"
fixable: "code",
deprecated: true,
replacedBy: []
},
create(context) {

View File

@ -0,0 +1,144 @@
/**
* @fileoverview Config Comment Parser
* @author Nicholas C. Zakas
*/
/* eslint-disable class-methods-use-this*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const levn = require("levn"),
ConfigOps = require("../config/config-ops");
const debug = require("debug")("eslint:config-comment-parser");
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
/**
* Object to parse ESLint configuration comments inside JavaScript files.
* @name ConfigCommentParser
*/
module.exports = class ConfigCommentParser {
/**
* Parses a list of "name:boolean_value" or/and "name" options divided by comma or
* whitespace. Used for "global" and "exported" comments.
* @param {string} string The string to parse.
* @param {Comment} comment The comment node which has the string.
* @returns {Object} Result map object of names and boolean values
*/
parseBooleanConfig(string, comment) {
debug("Parsing Boolean config");
const items = {};
// Collapse whitespace around `:` and `,` to make parsing easier
const trimmedString = string.replace(/\s*([:,])\s*/g, "$1");
trimmedString.split(/\s|,+/).forEach(name => {
if (!name) {
return;
}
// value defaults to "false" (if not provided), e.g: "foo" => ["foo", "false"]
const [key, value = "false"] = name.split(":");
items[key] = {
value: value === "true",
comment
};
});
return items;
}
/**
* Parses a JSON-like config.
* @param {string} string The string to parse.
* @param {Object} location Start line and column of comments for potential error message.
* @returns {({success: true, config: Object}|{success: false, error: Problem})} Result map object
*/
parseJsonConfig(string, location) {
debug("Parsing JSON config");
let items = {};
// Parses a JSON-like comment by the same way as parsing CLI option.
try {
items = levn.parse("Object", string) || {};
// Some tests say that it should ignore invalid comments such as `/*eslint no-alert:abc*/`.
// Also, commaless notations have invalid severity:
// "no-alert: 2 no-console: 2" --> {"no-alert": "2 no-console: 2"}
// Should ignore that case as well.
if (ConfigOps.isEverySeverityValid(items)) {
return {
success: true,
config: items
};
}
} catch (ex) {
debug("Levn parsing failed; falling back to manual parsing.");
// ignore to parse the string by a fallback.
}
/*
* Optionator cannot parse commaless notations.
* But we are supporting that. So this is a fallback for that.
*/
items = {};
const normalizedString = string.replace(/([a-zA-Z0-9\-/]+):/g, "\"$1\":").replace(/(]|[0-9])\s+(?=")/, "$1,");
try {
items = JSON.parse(`{${normalizedString}}`);
} catch (ex) {
debug("Manual parsing failed.");
return {
success: false,
error: {
ruleId: null,
fatal: true,
severity: 2,
message: `Failed to parse JSON from '${normalizedString}': ${ex.message}`,
line: location.start.line,
column: location.start.column + 1
}
};
}
return {
success: true,
config: items
};
}
/**
* Parses a config of values separated by comma.
* @param {string} string The string to parse.
* @returns {Object} Result map of values and true values
*/
parseListConfig(string) {
debug("Parsing list config");
const items = {};
// Collapse whitespace around commas
string.replace(/\s*,\s*/g, ",").split(/,+/).forEach(name => {
const trimmedName = name.trim();
if (trimmedName) {
items[trimmedName] = true;
}
});
return items;
}
};

View File

@ -14,7 +14,7 @@ const lodash = require("lodash"),
GlobSync = require("./glob"),
pathUtils = require("./path-utils"),
IgnoredPaths = require("../ignored-paths");
IgnoredPaths = require("./ignored-paths");
const debug = require("debug")("eslint:glob-utils");

View File

@ -12,7 +12,7 @@
const fs = require("fs"),
path = require("path"),
ignore = require("ignore"),
pathUtils = require("./util/path-utils");
pathUtils = require("./path-utils");
const debug = require("debug")("eslint:ignored-paths");
@ -296,7 +296,7 @@ class IgnoredPaths {
/**
* read ignore filepath
* @param {string} filePath, file to add to ig
* @returns {array} raw ignore rules
* @returns {Array} raw ignore rules
*/
readIgnoreFile(filePath) {
if (typeof this.cache[filePath] === "undefined") {
@ -307,8 +307,8 @@ class IgnoredPaths {
/**
* add ignore file to node-ignore instance
* @param {Object} ig, instance of node-ignore
* @param {string} filePath, file to add to ig
* @param {Object} ig instance of node-ignore
* @param {string} filePath file to add to ig
* @returns {void}
*/
addIgnoreFile(ig, filePath) {

View File

@ -10,8 +10,8 @@
//------------------------------------------------------------------------------
const assert = require("assert");
const ruleFixer = require("./util/rule-fixer");
const interpolate = require("./util/interpolate");
const ruleFixer = require("./rule-fixer");
const interpolate = require("./interpolate");
//------------------------------------------------------------------------------
// Typedefs

View File

@ -87,7 +87,7 @@ class SourceCode extends TokenStore {
* @param {string|Object} textOrConfig - The source code text or config object.
* @param {string} textOrConfig.text - The source code text.
* @param {ASTNode} textOrConfig.ast - The Program node of the AST representing the code. This AST should be created from the text that BOM was stripped.
* @param {Object|null} textOrConfig.parserServices - The parser srevices.
* @param {Object|null} textOrConfig.parserServices - The parser services.
* @param {ScopeManager|null} textOrConfig.scopeManager - The scope of this source code.
* @param {Object|null} textOrConfig.visitorKeys - The visitor keys to traverse AST.
* @param {ASTNode} [astIfNoConfig] - The Program node of the AST representing the code. This AST should be created from the text that BOM was stripped.
@ -316,6 +316,7 @@ class SourceCode extends TokenStore {
* @returns {Token|null} The Block comment token containing the JSDoc comment
* for the given node or null if not found.
* @public
* @deprecated
*/
getJSDocComment(node) {

View File

@ -1,4 +1,4 @@
All of the files matching the glob pattern "<%= pattern %>" are ignored.
You are linting "<%= pattern %>", but all of the files matching the glob pattern "<%= pattern %>" are ignored.
If you don't want to lint these files, remove the pattern "<%= pattern %>" from the list of arguments passed to ESLint.

View File

@ -1,9 +1,18 @@
'use strict';
const XHTMLEntities = require('./xhtml');
const hexNumber = /^[\da-fA-F]+$/;
const decimalNumber = /^\d+$/;
const {tokTypes: tt, TokContext, tokContexts, TokenType, isNewLine, isIdentifierStart, isIdentifierChar} = require("acorn");
const acorn = require("acorn");
const tt = acorn.tokTypes;
const TokContext = acorn.TokContext;
const tokContexts = acorn.tokContexts;
const TokenType = acorn.TokenType;
const isNewLine = acorn.isNewLine;
const isIdentifierStart = acorn.isIdentifierStart;
const isIdentifierChar = acorn.isIdentifierChar;
const tc_oTag = new TokContext('<tag', false);
const tc_cTag = new TokContext('</tag', false);
@ -48,15 +57,16 @@ function getQualifiedJSXName(object) {
getQualifiedJSXName(object.property);
}
module.exports = function(options = {}) {
module.exports = function(options) {
options = options || {};
return function(Parser) {
return plugin({
allowNamespaces: options.allowNamespaces !== false,
allowNamespacedObjects: !!options.allowNamespacedObjects
}, Parser);
}
}
module.exports.tokTypes = tok
};
module.exports.tokTypes = tok;
function plugin(options, Parser) {
return class extends Parser {
@ -115,7 +125,7 @@ function plugin(options, Parser) {
}
return out;
};
}
jsx_readString(quote) {
let out = '', chunkStart = ++this.pos;
@ -428,4 +438,4 @@ function plugin(options, Parser) {
}
}
};
};
}

View File

@ -28,5 +28,5 @@
"scripts": {
"test": "node test/run.js"
},
"version": "5.0.0"
"version": "5.0.1"
}

View File

@ -1029,6 +1029,7 @@ Defaults:
jsonPointers: false,
uniqueItems: true,
unicode: true,
nullable: false,
format: 'fast',
formats: {},
unknownFormats: true,
@ -1075,6 +1076,7 @@ Defaults:
- _jsonPointers_: set `dataPath` property of errors using [JSON Pointers](https://tools.ietf.org/html/rfc6901) instead of JavaScript property access notation.
- _uniqueItems_: validate `uniqueItems` keyword (true by default).
- _unicode_: calculate correct length of strings with unicode pairs (true by default). Pass `false` to use `.length` of strings that is faster, but gives "incorrect" lengths of strings with unicode pairs - each unicode pair is counted as two characters.
- _nullable_: support keyword "nullable" from [Open API 3 specification](https://swagger.io/docs/specification/data-models/data-types/).
- _format_: formats validation mode ('fast' by default). Pass 'full' for more correct and slow validation or `false` not to validate formats at all. E.g., 25:00:00 and 2015/14/33 will be invalid time and date in 'full' mode but it will be valid in 'fast' mode.
- _formats_: an object with custom formats. Keys and values will be passed to `addFormat` method.
- _unknownFormats_: handling of unknown formats. Option values:

View File

@ -4260,6 +4260,14 @@ module.exports = function generate_validate(it, $keyword, $ruleType) {
var $errorKeyword;
var $typeSchema = it.schema.type,
$typeIsArray = Array.isArray($typeSchema);
if ($typeSchema && it.opts.nullable && it.schema.nullable === true) {
if ($typeIsArray) {
if ($typeSchema.indexOf('null') == -1) $typeSchema = $typeSchema.concat('null');
} else if ($typeSchema != 'null') {
$typeSchema = [$typeSchema, 'null'];
$typeIsArray = true;
}
}
if ($typeIsArray && $typeSchema.length == 1) {
$typeSchema = $typeSchema[0];
$typeIsArray = false;
@ -5051,11 +5059,17 @@ module.exports = function (data, opts) {
'use strict';
var traverse = module.exports = function (schema, opts, cb) {
// Legacy support for v0.3.1 and earlier.
if (typeof opts == 'function') {
cb = opts;
opts = {};
}
_traverse(opts, cb, schema, '', schema);
cb = opts.cb || cb;
var pre = (typeof cb == 'function') ? cb : cb.pre || function() {};
var post = cb.post || function() {};
_traverse(opts, pre, post, schema, '', schema);
};
@ -5083,6 +5097,7 @@ traverse.propsKeywords = {
};
traverse.skipKeywords = {
default: true,
enum: true,
const: true,
required: true,
@ -5103,25 +5118,26 @@ traverse.skipKeywords = {
};
function _traverse(opts, cb, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
if (schema && typeof schema == 'object' && !Array.isArray(schema)) {
cb(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
for (var key in schema) {
var sch = schema[key];
if (Array.isArray(sch)) {
if (key in traverse.arrayKeywords) {
for (var i=0; i<sch.length; i++)
_traverse(opts, cb, sch[i], jsonPtr + '/' + key + '/' + i, rootSchema, jsonPtr, key, schema, i);
_traverse(opts, pre, post, sch[i], jsonPtr + '/' + key + '/' + i, rootSchema, jsonPtr, key, schema, i);
}
} else if (key in traverse.propsKeywords) {
if (sch && typeof sch == 'object') {
for (var prop in sch)
_traverse(opts, cb, sch[prop], jsonPtr + '/' + key + '/' + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);
_traverse(opts, pre, post, sch[prop], jsonPtr + '/' + key + '/' + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);
}
} else if (key in traverse.keywords || (opts.allKeys && !(key in traverse.skipKeywords))) {
_traverse(opts, cb, sch, jsonPtr + '/' + key, rootSchema, jsonPtr, key, schema);
_traverse(opts, pre, post, sch, jsonPtr + '/' + key, rootSchema, jsonPtr, key, schema);
}
}
post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
}
}
@ -6594,8 +6610,9 @@ function Ajv(opts) {
this._metaOpts = getMetaSchemaOptions(this);
if (opts.formats) addInitialFormats(this);
addDraft6MetaSchema(this);
addDefaultMetaSchema(this);
if (typeof opts.meta == 'object') this.addMetaSchema(opts.meta);
if (opts.nullable) this.addKeyword('nullable', {metaSchema: {const: true}});
addInitialSchemas(this);
}
@ -6967,7 +6984,7 @@ function addFormat(name, format) {
}
function addDraft6MetaSchema(self) {
function addDefaultMetaSchema(self) {
var $dataSchema;
if (self._opts.$data) {
$dataSchema = require('./refs/data.json');

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -104,7 +104,7 @@ declare namespace ajv {
* @return {string} human readable string with all errors descriptions
*/
errorsText(errors?: Array<ErrorObject> | null, options?: ErrorsTextOptions): string;
errors?: Array<ErrorObject>;
errors?: Array<ErrorObject> | null;
}
interface CustomLogger {
@ -163,7 +163,9 @@ declare namespace ajv {
sourceCode?: boolean;
processCode?: (code: string) => string;
cache?: object;
logger?: CustomLogger | false
logger?: CustomLogger | false;
nullable?: boolean;
serialize?: ((schema: object | boolean) => any) | false;
}
type FormatValidator = string | RegExp | ((data: string) => boolean | PromiseLike<any>);

View File

@ -70,8 +70,9 @@ function Ajv(opts) {
this._metaOpts = getMetaSchemaOptions(this);
if (opts.formats) addInitialFormats(this);
addDraft6MetaSchema(this);
addDefaultMetaSchema(this);
if (typeof opts.meta == 'object') this.addMetaSchema(opts.meta);
if (opts.nullable) this.addKeyword('nullable', {metaSchema: {const: true}});
addInitialSchemas(this);
}
@ -443,7 +444,7 @@ function addFormat(name, format) {
}
function addDraft6MetaSchema(self) {
function addDefaultMetaSchema(self) {
var $dataSchema;
if (self._opts.$data) {
$dataSchema = require('./refs/data.json');

View File

@ -100,6 +100,16 @@
var $typeSchema = it.schema.type
, $typeIsArray = Array.isArray($typeSchema);
if ($typeSchema && it.opts.nullable && it.schema.nullable === true) {
if ($typeIsArray) {
if ($typeSchema.indexOf('null') == -1)
$typeSchema = $typeSchema.concat('null');
} else if ($typeSchema != 'null') {
$typeSchema = [$typeSchema, 'null'];
$typeIsArray = true;
}
}
if ($typeIsArray && $typeSchema.length == 1) {
$typeSchema = $typeSchema[0];
$typeIsArray = false;

View File

@ -101,6 +101,14 @@ module.exports = function generate_validate(it, $keyword, $ruleType) {
var $errorKeyword;
var $typeSchema = it.schema.type,
$typeIsArray = Array.isArray($typeSchema);
if ($typeSchema && it.opts.nullable && it.schema.nullable === true) {
if ($typeIsArray) {
if ($typeSchema.indexOf('null') == -1) $typeSchema = $typeSchema.concat('null');
} else if ($typeSchema != 'null') {
$typeSchema = [$typeSchema, 'null'];
$typeIsArray = true;
}
}
if ($typeIsArray && $typeSchema.length == 1) {
$typeSchema = $typeSchema[0];
$typeIsArray = false;

View File

@ -16,7 +16,7 @@
"description": "Another JSON Schema Validator",
"devDependencies": {
"ajv-async": "^1.0.0",
"bluebird": "3.5.1",
"bluebird": "^3.5.3",
"brfs": "^2.0.0",
"browserify": "^16.2.0",
"chai": "^4.0.1",
@ -96,5 +96,5 @@
},
"tonicExampleFilename": ".tonic_example.js",
"typings": "lib/ajv.d.ts",
"version": "6.5.5"
"version": "6.6.1"
}

View File

@ -1,6 +0,0 @@
'use strict';
var arrayUniq = require('array-uniq');
module.exports = function () {
return arrayUniq([].concat.apply([], arguments));
};

View File

@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -1,49 +0,0 @@
{
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/sindresorhus/array-union/issues"
},
"bundleDependencies": false,
"dependencies": {
"array-uniq": "^1.0.1"
},
"deprecated": false,
"description": "Create an array of unique values, in order, from the input arrays",
"devDependencies": {
"ava": "*",
"xo": "*"
},
"engines": {
"node": ">=0.10.0"
},
"files": [
"index.js"
],
"homepage": "https://github.com/sindresorhus/array-union#readme",
"keywords": [
"array",
"arr",
"set",
"uniq",
"unique",
"duplicate",
"remove",
"union",
"combine",
"merge"
],
"license": "MIT",
"name": "array-union",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/array-union.git"
},
"scripts": {
"test": "xo && ava"
},
"version": "1.0.2"
}

View File

@ -1,28 +0,0 @@
# array-union [![Build Status](https://travis-ci.org/sindresorhus/array-union.svg?branch=master)](https://travis-ci.org/sindresorhus/array-union)
> Create an array of unique values, in order, from the input arrays
## Install
```
$ npm install --save array-union
```
## Usage
```js
const arrayUnion = require('array-union');
arrayUnion([1, 1, 2, 3], [2, 3]);
//=> [1, 2, 3]
arrayUnion(['foo', 'foo', 'bar'], ['foo']);
//=> ['foo', 'bar']
```
## License
MIT © [Sindre Sorhus](https://sindresorhus.com)

View File

@ -1,62 +0,0 @@
'use strict';
// there's 3 implementations written in increasing order of efficiency
// 1 - no Set type is defined
function uniqNoSet(arr) {
var ret = [];
for (var i = 0; i < arr.length; i++) {
if (ret.indexOf(arr[i]) === -1) {
ret.push(arr[i]);
}
}
return ret;
}
// 2 - a simple Set type is defined
function uniqSet(arr) {
var seen = new Set();
return arr.filter(function (el) {
if (!seen.has(el)) {
seen.add(el);
return true;
}
return false;
});
}
// 3 - a standard Set type is defined and it has a forEach method
function uniqSetWithForEach(arr) {
var ret = [];
(new Set(arr)).forEach(function (el) {
ret.push(el);
});
return ret;
}
// V8 currently has a broken implementation
// https://github.com/joyent/node/issues/8449
function doesForEachActuallyWork() {
var ret = false;
(new Set([true])).forEach(function (el) {
ret = el;
});
return ret === true;
}
if ('Set' in global) {
if (typeof Set.prototype.forEach === 'function' && doesForEachActuallyWork()) {
module.exports = uniqSetWithForEach;
} else {
module.exports = uniqSet;
}
} else {
module.exports = uniqNoSet;
}

View File

@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -1,46 +0,0 @@
{
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/sindresorhus/array-uniq/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Create an array without duplicates",
"devDependencies": {
"ava": "*",
"es6-set": "^0.1.0",
"require-uncached": "^1.0.2",
"xo": "*"
},
"engines": {
"node": ">=0.10.0"
},
"files": [
"index.js"
],
"homepage": "https://github.com/sindresorhus/array-uniq#readme",
"keywords": [
"array",
"arr",
"set",
"uniq",
"unique",
"es6",
"duplicate",
"remove"
],
"license": "MIT",
"name": "array-uniq",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/array-uniq.git"
},
"scripts": {
"test": "xo && ava"
},
"version": "1.0.3"
}

View File

@ -1,30 +0,0 @@
# array-uniq [![Build Status](https://travis-ci.org/sindresorhus/array-uniq.svg?branch=master)](https://travis-ci.org/sindresorhus/array-uniq)
> Create an array without duplicates
It's already pretty fast, but will be much faster when [Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) becomes available in V8 (especially with large arrays).
## Install
```
$ npm install --save array-uniq
```
## Usage
```js
const arrayUniq = require('array-uniq');
arrayUniq([1, 1, 2, 3, 3]);
//=> [1, 2, 3]
arrayUniq(['foo', 'foo', 'bar', 'foo']);
//=> ['foo', 'bar']
```
## License
MIT © [Sindre Sorhus](https://sindresorhus.com)

View File

@ -0,0 +1,4 @@
'use strict';
const regex = '[\uD800-\uDBFF][\uDC00-\uDFFF]';
module.exports = opts => opts && opts.exact ? new RegExp(`^${regex}$`) : new RegExp(regex, 'g');

View File

@ -1,6 +1,6 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Copyright (c) Kevin Mårtensson <kevinmartensson@gmail.com> (github.com/kevva)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

View File

@ -0,0 +1,41 @@
{
"author": {
"name": "Kevin Mårtensson",
"email": "kevinmartensson@gmail.com",
"url": "github.com/kevva"
},
"bugs": {
"url": "https://github.com/kevva/astral-regex/issues"
},
"bundleDependencies": false,
"dependencies": {},
"deprecated": false,
"description": "Regular expression for matching astral symbols",
"devDependencies": {
"ava": "*",
"xo": "*"
},
"engines": {
"node": ">=4"
},
"files": [
"index.js"
],
"homepage": "https://github.com/kevva/astral-regex#readme",
"keywords": [
"astral",
"emoji",
"regex",
"surrogate"
],
"license": "MIT",
"name": "astral-regex",
"repository": {
"type": "git",
"url": "git+https://github.com/kevva/astral-regex.git"
},
"scripts": {
"test": "xo && ava"
},
"version": "1.0.0"
}

View File

@ -0,0 +1,43 @@
# astral-regex [![Build Status](https://travis-ci.org/kevva/astral-regex.svg?branch=master)](https://travis-ci.org/kevva/astral-regex)
> Regular expression for matching astral symbols
## Install
```
$ npm install astral-regex
```
## Usage
```js
const astralRegex = require('astral-regex');
astralRegex({exact: true}).test('');
//=> true
```
## API
### astralRegex([options])
Returns a `RegExp` for matching astral symbols.
#### options
Type: `Object`
##### exact
Type: `boolean`<br>
Default: `false` *(Matches any astral symbols in a string)*
Only match an exact string. Useful with `RegExp#test()` to check if a string is a astral symbol.
## License
MIT © [Kevin Mårtensson](https://github.com/kevva)

View File

@ -1,70 +0,0 @@
'use strict';
const path = require('path');
const globby = require('globby');
const isPathCwd = require('is-path-cwd');
const isPathInCwd = require('is-path-in-cwd');
const pify = require('pify');
const rimraf = require('rimraf');
const pMap = require('p-map');
const rimrafP = pify(rimraf);
function safeCheck(file) {
if (isPathCwd(file)) {
throw new Error('Cannot delete the current working directory. Can be overriden with the `force` option.');
}
if (!isPathInCwd(file)) {
throw new Error('Cannot delete files/folders outside the current working directory. Can be overriden with the `force` option.');
}
}
module.exports = (patterns, opts) => {
opts = Object.assign({}, opts);
const force = opts.force;
delete opts.force;
const dryRun = opts.dryRun;
delete opts.dryRun;
const mapper = file => {
if (!force) {
safeCheck(file);
}
file = path.resolve(opts.cwd || '', file);
if (dryRun) {
return file;
}
return rimrafP(file, {glob: false}).then(() => file);
};
return globby(patterns, opts).then(files => pMap(files, mapper, opts));
};
module.exports.sync = (patterns, opts) => {
opts = Object.assign({}, opts);
const force = opts.force;
delete opts.force;
const dryRun = opts.dryRun;
delete opts.dryRun;
return globby.sync(patterns, opts).map(file => {
if (!force) {
safeCheck(file);
}
file = path.resolve(opts.cwd || '', file);
if (!dryRun) {
rimraf.sync(file, {glob: false});
}
return file;
});
};

View File

@ -1,70 +0,0 @@
{
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/sindresorhus/del/issues"
},
"bundleDependencies": false,
"dependencies": {
"globby": "^6.1.0",
"is-path-cwd": "^1.0.0",
"is-path-in-cwd": "^1.0.0",
"p-map": "^1.1.1",
"pify": "^3.0.0",
"rimraf": "^2.2.8"
},
"deprecated": false,
"description": "Delete files and folders",
"devDependencies": {
"ava": "*",
"make-dir": "^1.0.0",
"tempy": "^0.1.0",
"xo": "*"
},
"engines": {
"node": ">=4"
},
"files": [
"index.js"
],
"homepage": "https://github.com/sindresorhus/del#readme",
"keywords": [
"delete",
"files",
"folders",
"directories",
"del",
"remove",
"destroy",
"trash",
"unlink",
"clean",
"cleaning",
"cleanup",
"rm",
"rmrf",
"rimraf",
"rmdir",
"glob",
"gulpfriendly",
"file",
"folder",
"directory",
"dir",
"fs",
"filesystem"
],
"license": "MIT",
"name": "del",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/del.git"
},
"scripts": {
"test": "xo && ava"
},
"version": "3.0.0"
}

View File

@ -1,121 +0,0 @@
# del [![Build Status](https://travis-ci.org/sindresorhus/del.svg?branch=master)](https://travis-ci.org/sindresorhus/del) [![XO code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/sindresorhus/xo)
> Delete files and folders using [globs](https://github.com/isaacs/minimatch#usage)
Similar to [rimraf](https://github.com/isaacs/rimraf), but with a Promise API and support for multiple files and globbing. It also protects you against deleting the current working directory and above.
---
<p align="center">🐶</p>
<p align="center"><b>Support this project and improve your JavaScript skills with this great <a href="https://ES6.io/friend/AWESOME">ES6 course</a> by Wes Bos.</b><br>Try his free <a href="https://javascript30.com/friend/AWESOME">JavaScript 30 course</a> for a taste of what to expect. You might also like his <a href="https://ReactForBeginners.com/friend/AWESOME">React</a> and <a href="https://SublimeTextBook.com/friend/AWESOME">Sublime</a> course.</p>
---
## Install
```
$ npm install --save del
```
## Usage
```js
const del = require('del');
del(['tmp/*.js', '!tmp/unicorn.js']).then(paths => {
console.log('Deleted files and folders:\n', paths.join('\n'));
});
```
## Beware
The glob pattern `**` matches all children and *the parent*.
So this won't work:
```js
del.sync(['public/assets/**', '!public/assets/goat.png']);
```
You have to explicitly ignore the parent directories too:
```js
del.sync(['public/assets/**', '!public/assets', '!public/assets/goat.png']);
```
Suggestions on how to improve this welcome!
## API
### del(patterns, [options])
Returns a promise for an array of deleted paths.
### del.sync(patterns, [options])
Returns an array of deleted paths.
#### patterns
Type: `string` `Array`
See supported minimatch [patterns](https://github.com/isaacs/minimatch#usage).
- [Pattern examples with expected matches](https://github.com/sindresorhus/multimatch/blob/master/test.js)
- [Quick globbing pattern overview](https://github.com/sindresorhus/multimatch#globbing-patterns)
#### options
Type: `Object`
See the [`glob` options](https://github.com/isaacs/node-glob#options).
##### force
Type: `boolean`<br>
Default: `false`
Allow deleting the current working directory and outside.
##### dryRun
Type: `boolean`<br>
Default: `false`
See what would be deleted.
```js
const del = require('del');
del(['tmp/*.js'], {dryRun: true}).then(paths => {
console.log('Files and folders that would be deleted:\n', paths.join('\n'));
});
```
##### concurrency
Type: `number`<br>
Default: `Infinity`<br>
Minimum: `1`
Concurrency limit.
## CLI
See [del-cli](https://github.com/sindresorhus/del-cli) for a CLI for this module and [trash-cli](https://github.com/sindresorhus/trash-cli) for a safe version that is suitable for running by hand.
## Related
- [make-dir](https://github.com/sindresorhus/make-dir) - Make a directory and its parents if needed
- [globby](https://github.com/sindresorhus/globby) - User-friendly glob matching
## License
MIT © [Sindre Sorhus](https://sindresorhus.com)

View File

@ -12,24 +12,24 @@ Espree started out as a fork of [Esprima](http://esprima.org) v1.2.2, the last s
Install:
```
npm i espree --save
npm i espree
```
And in your Node.js code:
```javascript
var espree = require("espree");
const espree = require("espree");
var ast = espree.parse(code);
const ast = espree.parse(code);
```
There is a second argument to `parse()` that allows you to specify various options:
```javascript
var espree = require("espree");
const espree = require("espree");
// Optional second options argument with the following default settings
var ast = espree.parse(code, {
const ast = espree.parse(code, {
// attach range information to each node
range: false,
@ -40,9 +40,6 @@ var ast = espree.parse(code, {
// create a top-level comments array containing all comments
comment: false,
// attach comments to the closest relevant node as leadingComments and trailingComments
attachComment: false,
// create a top-level tokens array containing all tokens
tokens: false,

View File

@ -88,6 +88,7 @@ const parsers = {
options.ecmaFeatures &&
options.ecmaFeatures.jsx
);
return useJsx ? this.jsx : this.regular;
}
};
@ -109,7 +110,7 @@ function tokenize(code, options) {
// Ensure to collect tokens.
if (!options || options.tokens !== true) {
options = Object.assign({}, options, { tokens: true });
options = Object.assign({}, options, { tokens: true }); // eslint-disable-line no-param-reassign
}
return new Parser(options, code).tokenize();
@ -128,6 +129,7 @@ function tokenize(code, options) {
*/
function parse(code, options) {
const Parser = parsers.get(options);
return new Parser(options, code).parse();
}
@ -144,7 +146,8 @@ exports.parse = parse;
// Deep copy.
/* istanbul ignore next */
exports.Syntax = (function() {
var name, types = {};
let name,
types = {};
if (typeof Object.create === "function") {
types = Object.create(null);

View File

@ -1,175 +0,0 @@
/**
* @fileoverview Attaches comments to the AST.
* @author Nicholas C. Zakas
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
var astNodeTypes = require("./ast-node-types");
//------------------------------------------------------------------------------
// Private
//------------------------------------------------------------------------------
var extra = {
trailingComments: [],
leadingComments: [],
bottomRightStack: [],
previousNode: null
};
//------------------------------------------------------------------------------
// Public
//------------------------------------------------------------------------------
module.exports = {
reset: function() {
extra.trailingComments = [];
extra.leadingComments = [];
extra.bottomRightStack = [];
extra.previousNode = null;
},
addComment: function(comment) {
extra.trailingComments.push(comment);
extra.leadingComments.push(comment);
},
processComment: function(node) {
var lastChild,
trailingComments,
i,
j;
if (node.type === astNodeTypes.Program) {
if (node.body.length > 0) {
return;
}
}
if (extra.trailingComments.length > 0) {
/*
* If the first comment in trailingComments comes after the
* current node, then we're good - all comments in the array will
* come after the node and so it's safe to add then as official
* trailingComments.
*/
if (extra.trailingComments[0].range[0] >= node.range[1]) {
trailingComments = extra.trailingComments;
extra.trailingComments = [];
} else {
/*
* Otherwise, if the first comment doesn't come after the
* current node, that means we have a mix of leading and trailing
* comments in the array and that leadingComments contains the
* same items as trailingComments. Reset trailingComments to
* zero items and we'll handle this by evaluating leadingComments
* later.
*/
extra.trailingComments.length = 0;
}
} else {
if (extra.bottomRightStack.length > 0 &&
extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments &&
extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments[0].range[0] >= node.range[1]) {
trailingComments = extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments;
delete extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments;
}
}
// Eating the stack.
while (extra.bottomRightStack.length > 0 && extra.bottomRightStack[extra.bottomRightStack.length - 1].range[0] >= node.range[0]) {
lastChild = extra.bottomRightStack.pop();
}
if (lastChild) {
if (lastChild.leadingComments) {
if (lastChild.leadingComments[lastChild.leadingComments.length - 1].range[1] <= node.range[0]) {
node.leadingComments = lastChild.leadingComments;
delete lastChild.leadingComments;
} else {
// A leading comment for an anonymous class had been stolen by its first MethodDefinition,
// so this takes back the leading comment.
// See Also: https://github.com/eslint/espree/issues/158
for (i = lastChild.leadingComments.length - 2; i >= 0; --i) {
if (lastChild.leadingComments[i].range[1] <= node.range[0]) {
node.leadingComments = lastChild.leadingComments.splice(0, i + 1);
break;
}
}
}
}
} else if (extra.leadingComments.length > 0) {
if (extra.leadingComments[extra.leadingComments.length - 1].range[1] <= node.range[0]) {
if (extra.previousNode) {
for (j = 0; j < extra.leadingComments.length; j++) {
if (extra.leadingComments[j].end < extra.previousNode.end) {
extra.leadingComments.splice(j, 1);
j--;
}
}
}
if (extra.leadingComments.length > 0) {
node.leadingComments = extra.leadingComments;
extra.leadingComments = [];
}
} else {
// https://github.com/eslint/espree/issues/2
/*
* In special cases, such as return (without a value) and
* debugger, all comments will end up as leadingComments and
* will otherwise be eliminated. This extra step runs when the
* bottomRightStack is empty and there are comments left
* in leadingComments.
*
* This loop figures out the stopping point between the actual
* leading and trailing comments by finding the location of the
* first comment that comes after the given node.
*/
for (i = 0; i < extra.leadingComments.length; i++) {
if (extra.leadingComments[i].range[1] > node.range[0]) {
break;
}
}
/*
* Split the array based on the location of the first comment
* that comes after the node. Keep in mind that this could
* result in an empty array, and if so, the array must be
* deleted.
*/
node.leadingComments = extra.leadingComments.slice(0, i);
if (node.leadingComments.length === 0) {
delete node.leadingComments;
}
/*
* Similarly, trailing comments are attached later. The variable
* must be reset to null if there are no trailing comments.
*/
trailingComments = extra.leadingComments.slice(i);
if (trailingComments.length === 0) {
trailingComments = null;
}
}
}
extra.previousNode = node;
if (trailingComments) {
node.trailingComments = trailingComments;
}
extra.bottomRightStack.push(node);
}
};

View File

@ -1,8 +1,8 @@
"use strict";
/* eslint-disable no-param-reassign*/
const acorn = require("acorn");
const jsx = require("acorn-jsx");
const commentAttachment = require("./comment-attachment");
const TokenTranslator = require("./token-translator");
const DEFAULT_ECMA_VERSION = 5;
@ -89,23 +89,24 @@ module.exports = () => Parser => class Espree extends Parser {
const ecmaVersion = normalizeEcmaVersion(options.ecmaVersion);
const isModule = options.sourceType === "module";
const tokenTranslator =
options.tokens === true ?
new TokenTranslator(tokTypes, code) :
null;
options.tokens === true
? new TokenTranslator(tokTypes, code)
: null;
// Initialize acorn parser.
super({
ecmaVersion: isModule ? Math.max(6, ecmaVersion) : ecmaVersion,
sourceType: isModule ? "module" : "script",
ranges: options.range === true || options.attachComment === true,
ranges: options.range === true,
locations: options.loc === true,
// Truthy value is true for backward compatibility.
allowReturnOutsideFunction: Boolean(ecmaFeatures.globalReturn),
// Collect tokens
onToken: (token) => {
onToken: token => {
if (tokenTranslator) {
// Use `tokens`, `ecmaVersion`, and `jsxAttrValueToken` in the state.
tokenTranslator.onToken(token, this[STATE]);
}
@ -118,23 +119,16 @@ module.exports = () => Parser => class Espree extends Parser {
onComment: (block, text, start, end, startLoc, endLoc) => {
if (this[STATE].comments) {
const comment = convertAcornCommentToEsprimaComment(block, text, start, end, startLoc, endLoc);
this[STATE].comments.push(comment);
if (options.attachComment === true) {
commentAttachment.addComment(comment);
}
this[STATE].comments.push(comment);
}
}
}, code);
// TODO: remove global state.
commentAttachment.reset();
// Initialize internal state.
this[STATE] = {
tokens: tokenTranslator ? [] : null,
comments: options.comment === true || options.attachComment === true ? [] : null,
attachComment: options.attachComment === true,
comments: options.comment === true ? [] : null,
impliedStrict: ecmaFeatures.impliedStrict === true && this.options.ecmaVersion >= 5,
ecmaVersion: this.options.ecmaVersion,
jsxAttrValueToken: false,
@ -159,11 +153,13 @@ module.exports = () => Parser => class Espree extends Parser {
finishNode(...args) {
const result = super.finishNode(...args);
return this[ESPRIMA_FINISH_NODE](result);
}
finishNodeAt(...args) {
const result = super.finishNodeAt(...args);
return this[ESPRIMA_FINISH_NODE](result);
}
@ -216,6 +212,7 @@ module.exports = () => Parser => class Espree extends Parser {
raise(pos, message) {
const loc = acorn.getLineInfo(this.input, pos);
const err = new SyntaxError(message);
err.index = pos;
err.lineNumber = loc.line;
err.column = loc.column + 1; // acorn uses 0-based columns
@ -256,7 +253,7 @@ module.exports = () => Parser => class Espree extends Parser {
}
if (this.end > this.start) {
message += " " + this.input.slice(this.start, this.end);
message += ` ${this.input.slice(this.start, this.end)}`;
}
this.raise(this.start, message);
@ -271,6 +268,7 @@ module.exports = () => Parser => class Espree extends Parser {
*/
jsx_readString(quote) { // eslint-disable-line camelcase
const result = super.jsx_readString(quote);
if (this.type === tokTypes.string) {
this[STATE].jsxAttrValueToken = true;
}
@ -283,6 +281,7 @@ module.exports = () => Parser => class Espree extends Parser {
* @returns {ASTNode} The finished node.
*/
[ESPRIMA_FINISH_NODE](result) {
// Acorn doesn't count the opening and closing backticks as part of templates
// so we have to adjust ranges/locations appropriately.
if (result.type === "TemplateElement") {
@ -301,10 +300,6 @@ module.exports = () => Parser => class Espree extends Parser {
}
}
if (this[STATE].attachComment) {
commentAttachment.processComment(result);
}
if (result.type.indexOf("Function") > -1 && !result.generator) {
result.generator = false;
}

View File

@ -18,7 +18,7 @@
// Esprima Token Types
var Token = {
const Token = {
Boolean: "Boolean",
EOF: "<end>",
Identifier: "Identifier",
@ -41,10 +41,10 @@ var Token = {
* @private
*/
function convertTemplatePart(tokens, code) {
var firstToken = tokens[0],
const firstToken = tokens[0],
lastTemplateToken = tokens[tokens.length - 1];
var token = {
const token = {
type: Token.Template,
value: code.slice(firstToken.start, lastTemplateToken.end)
};
@ -99,9 +99,9 @@ TokenTranslator.prototype = {
* @param {Object} extra Espree extra object.
* @returns {EsprimaToken} The Esprima version of the token.
*/
translate: function(token, extra) {
translate(token, extra) {
var type = token.type,
const type = token.type,
tt = this._acornTokTypes;
if (type === tt.name) {
@ -157,12 +157,13 @@ TokenTranslator.prototype = {
token.value = this._code.slice(token.start, token.end);
} else if (type === tt.regexp) {
token.type = Token.RegularExpression;
var value = token.value;
const value = token.value;
token.regex = {
flags: value.flags,
pattern: value.pattern
};
token.value = "/" + value.pattern + "/" + value.flags;
token.value = `/${value.pattern}/${value.flags}`;
}
return token;
@ -174,9 +175,9 @@ TokenTranslator.prototype = {
* @param {Object} extra The Espree extra object.
* @returns {void}
*/
onToken: function(token, extra) {
onToken(token, extra) {
var that = this,
const that = this,
tt = this._acornTokTypes,
tokens = extra.tokens,
templateTokens = this._tokens;
@ -218,11 +219,13 @@ TokenTranslator.prototype = {
}
return;
} else if (token.type === tt.dollarBraceL) {
}
if (token.type === tt.dollarBraceL) {
templateTokens.push(token);
translateTemplateTokens();
return;
} else if (token.type === tt.braceR) {
}
if (token.type === tt.braceR) {
// if there's already a curly, it's not part of the template
if (this._curlyBrace) {
@ -232,7 +235,8 @@ TokenTranslator.prototype = {
// store new curly for later
this._curlyBrace = token;
return;
} else if (token.type === tt.template || token.type === tt.invalidTemplate) {
}
if (token.type === tt.template || token.type === tt.invalidTemplate) {
if (this._curlyBrace) {
templateTokens.push(this._curlyBrace);
this._curlyBrace = null;

View File

@ -0,0 +1,123 @@
/**
* @fileoverview The visitor keys for the node types Espree supports
* @author Nicholas C. Zakas
*
* This file contains code from estraverse-fb.
*
* The MIT license. Copyright (c) 2014 Ingvar Stepanyan
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
// None!
//------------------------------------------------------------------------------
// Public
//------------------------------------------------------------------------------
module.exports = {
// ECMAScript
AssignmentExpression: ["left", "right"],
AssignmentPattern: ["left", "right"],
ArrayExpression: ["elements"],
ArrayPattern: ["elements"],
ArrowFunctionExpression: ["params", "body"],
BlockStatement: ["body"],
BinaryExpression: ["left", "right"],
BreakStatement: ["label"],
CallExpression: ["callee", "arguments"],
CatchClause: ["param", "body"],
ClassBody: ["body"],
ClassDeclaration: ["id", "superClass", "body"],
ClassExpression: ["id", "superClass", "body"],
ConditionalExpression: ["test", "consequent", "alternate"],
ContinueStatement: ["label"],
DebuggerStatement: [],
DirectiveStatement: [],
DoWhileStatement: ["body", "test"],
EmptyStatement: [],
ExportAllDeclaration: ["source"],
ExportDefaultDeclaration: ["declaration"],
ExportNamedDeclaration: ["declaration", "specifiers", "source"],
ExportSpecifier: ["exported", "local"],
ExpressionStatement: ["expression"],
ForStatement: ["init", "test", "update", "body"],
ForInStatement: ["left", "right", "body"],
ForOfStatement: ["left", "right", "body"],
FunctionDeclaration: ["id", "params", "body"],
FunctionExpression: ["id", "params", "body"],
Identifier: [],
IfStatement: ["test", "consequent", "alternate"],
ImportDeclaration: ["specifiers", "source"],
ImportDefaultSpecifier: ["local"],
ImportNamespaceSpecifier: ["local"],
ImportSpecifier: ["imported", "local"],
Literal: [],
LabeledStatement: ["label", "body"],
LogicalExpression: ["left", "right"],
MemberExpression: ["object", "property"],
MetaProperty: ["meta", "property"],
MethodDefinition: ["key", "value"],
ModuleSpecifier: [],
NewExpression: ["callee", "arguments"],
ObjectExpression: ["properties"],
ObjectPattern: ["properties"],
Program: ["body"],
Property: ["key", "value"],
RestElement: ["argument"],
ReturnStatement: ["argument"],
SequenceExpression: ["expressions"],
SpreadElement: ["argument"],
Super: [],
SwitchStatement: ["discriminant", "cases"],
SwitchCase: ["test", "consequent"],
TaggedTemplateExpression: ["tag", "quasi"],
TemplateElement: [],
TemplateLiteral: ["quasis", "expressions"],
ThisExpression: [],
ThrowStatement: ["argument"],
TryStatement: ["block", "handler", "finalizer"],
UnaryExpression: ["argument"],
UpdateExpression: ["argument"],
VariableDeclaration: ["declarations"],
VariableDeclarator: ["id", "init"],
WhileStatement: ["test", "body"],
WithStatement: ["object", "body"],
YieldExpression: ["argument"],
// JSX
JSXIdentifier: [],
JSXNamespacedName: ["namespace", "name"],
JSXMemberExpression: ["object", "property"],
JSXEmptyExpression: [],
JSXExpressionContainer: ["expression"],
JSXElement: ["openingElement", "closingElement", "children"],
JSXClosingElement: ["name"],
JSXOpeningElement: ["name", "attributes"],
JSXAttribute: ["name", "value"],
JSXText: null,
JSXSpreadAttribute: ["argument"]
};

View File

@ -17,8 +17,9 @@
"devDependencies": {
"browserify": "^7.0.0",
"chai": "^1.10.0",
"eslint": "^2.13.1",
"eslint-config-eslint": "^3.0.0",
"eslint": "^5.7.0",
"eslint-config-eslint": "^5.0.1",
"eslint-plugin-node": "^8.0.0",
"eslint-release": "^1.0.0",
"esprima": "latest",
"esprima-fb": "^8001.2001.0-dev-harmony-fb",
@ -65,5 +66,5 @@
"publish-release": "eslint-publish-release",
"test": "npm run-script lint && node Makefile.js test"
},
"version": "4.1.0"
"version": "5.0.0"
}

View File

@ -1,7 +1,7 @@
var path = require( 'path' );
var fs = require( 'graceful-fs' );
var del = require( 'del' ).sync;
var utils = require( './utils' );
var del = require( './del' );
var writeJSON = utils.writeJSON;
var cache = {
@ -125,9 +125,7 @@ var cache = {
* @return {Boolean} true or false if the file was successfully deleted
*/
removeCacheFile: function () {
return del( this._pathToFile, {
force: true
} );
return del( this._pathToFile );
},
/**
* Destroy the file cache and cache content.
@ -185,9 +183,7 @@ module.exports = {
*/
clearCacheById: function ( docId, cacheDir ) {
var filePath = cacheDir ? path.resolve( cacheDir, docId ) : path.resolve( __dirname, './.cache/', docId );
return del( filePath, {
force: true
} ).length > 0;
return del( filePath );
},
/**
* Remove all cache stored in the cache directory
@ -196,8 +192,6 @@ module.exports = {
*/
clearAll: function ( cacheDir ) {
var filePath = cacheDir ? path.resolve( cacheDir ) : path.resolve( __dirname, './.cache/' );
return del( filePath, {
force: true
} ).length > 0;
return del( filePath );
}
};

View File

@ -1,31 +1,56 @@
# flat-cache - Changelog
## v1.3.4
- **Refactoring**
- Add del.js and utils.js to the list of files to be beautified - [9d0ca9b]( https://github.com/royriojas/flat-cache/commit/9d0ca9b ), [Roy Riojas](https://github.com/Roy Riojas), 14/11/2018 12:19:02
## v1.3.3
- **Refactoring**
- Make sure package-lock.json is up to date - [a7d2598]( https://github.com/royriojas/flat-cache/commit/a7d2598 ), [Roy Riojas](https://github.com/Roy Riojas), 14/11/2018 11:36:08
- **Other changes**
- Removed the need for del ([#33](https://github.com/royriojas/flat-cache/issues/33)) - [c429012]( https://github.com/royriojas/flat-cache/commit/c429012 ), [S. Gilroy](https://github.com/S. Gilroy), 13/11/2018 13:56:37
* Removed the need for del
Removed the need for del as newer versions have broken backwards
compatibility. del mainly uses rimraf for deleting folders
and files, replaceing it with rimraf only is a minimal change.
* Disable glob on rimraf calls
* Added glob disable to wrong call
* Wrapped rimraf to simplify solution
## v1.3.2
- **Refactoring**
- remove yarn.lock file - [704c6c4]( https://github.com/royriojas/flat-cache/commit/704c6c4 ), [Roy Riojas](https://github.com/Roy Riojas), 07/11/2018 18:41:08
- remove yarn.lock file - [704c6c4]( https://github.com/royriojas/flat-cache/commit/704c6c4 ), [Roy Riojas](https://github.com/Roy Riojas), 07/11/2018 15:41:08
- **undefined**
- replace circular-json with flatted ([#23](https://github.com/royriojas/flat-cache/issues/23))" - [db12d74]( https://github.com/royriojas/flat-cache/commit/db12d74 ), [Roy Riojas](https://github.com/Roy Riojas), 07/11/2018 18:40:39
- replace circular-json with flatted ([#23](https://github.com/royriojas/flat-cache/issues/23))" - [db12d74]( https://github.com/royriojas/flat-cache/commit/db12d74 ), [Roy Riojas](https://github.com/Roy Riojas), 07/11/2018 15:40:39
This reverts commit 00f689277a75e85fef28e6a048fad227afc525e6.
## v1.3.1
- **Refactoring**
- upgrade deps to remove some security warnings - [f405719]( https://github.com/royriojas/flat-cache/commit/f405719 ), [Roy Riojas](https://github.com/Roy Riojas), 06/11/2018 15:07:31
- upgrade deps to remove some security warnings - [f405719]( https://github.com/royriojas/flat-cache/commit/f405719 ), [Roy Riojas](https://github.com/Roy Riojas), 06/11/2018 12:07:31
- **Bug Fixes**
- replace circular-json with flatted ([#23](https://github.com/royriojas/flat-cache/issues/23)) - [00f6892]( https://github.com/royriojas/flat-cache/commit/00f6892 ), [Terry](https://github.com/Terry), 05/11/2018 21:44:16
- replace circular-json with flatted ([#23](https://github.com/royriojas/flat-cache/issues/23)) - [00f6892]( https://github.com/royriojas/flat-cache/commit/00f6892 ), [Terry](https://github.com/Terry), 05/11/2018 18:44:16
- **undefined**
- update del to v3.0.0 ([#26](https://github.com/royriojas/flat-cache/issues/26)) - [d42883f]( https://github.com/royriojas/flat-cache/commit/d42883f ), [Patrick Silva](https://github.com/Patrick Silva), 03/11/2018 03:00:44
- update del to v3.0.0 ([#26](https://github.com/royriojas/flat-cache/issues/26)) - [d42883f]( https://github.com/royriojas/flat-cache/commit/d42883f ), [Patrick Silva](https://github.com/Patrick Silva), 03/11/2018 01:00:44
Closes <a target="_blank" class="info-link" href="https://github.com/royriojas/flat-cache/issues/25"><span>#25</span></a>
## v1.3.0
- **Other changes**
- Added #all method ([#16](https://github.com/royriojas/flat-cache/issues/16)) - [12293be]( https://github.com/royriojas/flat-cache/commit/12293be ), [Ozair Patel](https://github.com/Ozair Patel), 25/09/2017 16:46:38
- Added #all method ([#16](https://github.com/royriojas/flat-cache/issues/16)) - [12293be]( https://github.com/royriojas/flat-cache/commit/12293be ), [Ozair Patel](https://github.com/Ozair Patel), 25/09/2017 14:46:38
* Added #all method
@ -39,12 +64,12 @@
* Beautified file
- fix changelog title style ([#14](https://github.com/royriojas/flat-cache/issues/14)) - [af8338a]( https://github.com/royriojas/flat-cache/commit/af8338a ), [前端小武](https://github.com/前端小武), 19/12/2016 23:34:48
- fix changelog title style ([#14](https://github.com/royriojas/flat-cache/issues/14)) - [af8338a]( https://github.com/royriojas/flat-cache/commit/af8338a ), [前端小武](https://github.com/前端小武), 19/12/2016 20:34:48
## v1.2.2
- **Bug Fixes**
- Do not crash if cache file is invalid JSON. ([#13](https://github.com/royriojas/flat-cache/issues/13)) - [87beaa6]( https://github.com/royriojas/flat-cache/commit/87beaa6 ), [Roy Riojas](https://github.com/Roy Riojas), 19/12/2016 21:03:35
- Do not crash if cache file is invalid JSON. ([#13](https://github.com/royriojas/flat-cache/issues/13)) - [87beaa6]( https://github.com/royriojas/flat-cache/commit/87beaa6 ), [Roy Riojas](https://github.com/Roy Riojas), 19/12/2016 18:03:35
Fixes <a target="_blank" class="info-link" href="https://github.com/royriojas/flat-cache/issues/12"><span>#12</span></a>
@ -55,186 +80,186 @@
If the cache is somehow not valid the cache will be discarded an a
a new cache will be stored instead
- **Other changes**
- Added travis ci support for modern node versions ([#11](https://github.com/royriojas/flat-cache/issues/11)) - [1c2b1f7]( https://github.com/royriojas/flat-cache/commit/1c2b1f7 ), [Amila Welihinda](https://github.com/Amila Welihinda), 11/11/2016 02:47:52
- Added travis ci support for modern node versions ([#11](https://github.com/royriojas/flat-cache/issues/11)) - [1c2b1f7]( https://github.com/royriojas/flat-cache/commit/1c2b1f7 ), [Amila Welihinda](https://github.com/Amila Welihinda), 10/11/2016 23:47:52
- Bumping `circular-son` version ([#10](https://github.com/royriojas/flat-cache/issues/10)) - [4d5e861]( https://github.com/royriojas/flat-cache/commit/4d5e861 ), [Andrea Giammarchi](https://github.com/Andrea Giammarchi), 02/08/2016 09:13:52
- Bumping `circular-son` version ([#10](https://github.com/royriojas/flat-cache/issues/10)) - [4d5e861]( https://github.com/royriojas/flat-cache/commit/4d5e861 ), [Andrea Giammarchi](https://github.com/Andrea Giammarchi), 02/08/2016 07:13:52
As mentioned in https://github.com/WebReflection/circular-json/issues/25 `circular-json` wan't rightly implementing the license field.
Latest version bump changed only that bit so that ESLint should now be happy.
## v1.2.1
- **Bug Fixes**
- Add missing utils.js file to the package. closes [#8](https://github.com/royriojas/flat-cache/issues/8) - [ec10cf2]( https://github.com/royriojas/flat-cache/commit/ec10cf2 ), [Roy Riojas](https://github.com/Roy Riojas), 01/08/2016 04:18:57
- Add missing utils.js file to the package. closes [#8](https://github.com/royriojas/flat-cache/issues/8) - [ec10cf2]( https://github.com/royriojas/flat-cache/commit/ec10cf2 ), [Roy Riojas](https://github.com/Roy Riojas), 01/08/2016 02:18:57
## v1.2.0
- **Documentation**
- Add documentation about noPrune option - [23e11f9]( https://github.com/royriojas/flat-cache/commit/23e11f9 ), [Roy Riojas](https://github.com/Roy Riojas), 01/08/2016 04:06:49
- Add documentation about noPrune option - [23e11f9]( https://github.com/royriojas/flat-cache/commit/23e11f9 ), [Roy Riojas](https://github.com/Roy Riojas), 01/08/2016 02:06:49
## v1.1.0
- **Features**
- Add noPrune option to cache.save() method. closes [#7](https://github.com/royriojas/flat-cache/issues/7) - [2c8016a]( https://github.com/royriojas/flat-cache/commit/2c8016a ), [Roy Riojas](https://github.com/Roy Riojas), 01/08/2016 04:00:29
- Add noPrune option to cache.save() method. closes [#7](https://github.com/royriojas/flat-cache/issues/7) - [2c8016a]( https://github.com/royriojas/flat-cache/commit/2c8016a ), [Roy Riojas](https://github.com/Roy Riojas), 01/08/2016 02:00:29
- Add json read and write utility based on circular-json - [c31081e]( https://github.com/royriojas/flat-cache/commit/c31081e ), [Jean Ponchon](https://github.com/Jean Ponchon), 28/07/2016 10:58:17
- Add json read and write utility based on circular-json - [c31081e]( https://github.com/royriojas/flat-cache/commit/c31081e ), [Jean Ponchon](https://github.com/Jean Ponchon), 28/07/2016 08:58:17
- **Bug Fixes**
- Remove UTF16 BOM stripping - [4a41e22]( https://github.com/royriojas/flat-cache/commit/4a41e22 ), [Jean Ponchon](https://github.com/Jean Ponchon), 29/07/2016 04:18:06
- Remove UTF16 BOM stripping - [4a41e22]( https://github.com/royriojas/flat-cache/commit/4a41e22 ), [Jean Ponchon](https://github.com/Jean Ponchon), 29/07/2016 02:18:06
Since we control both writing and reading of JSON stream, there no needs
to handle unicode BOM.
- Use circular-json to handle circular references (fix [#5](https://github.com/royriojas/flat-cache/issues/5)) - [cd7aeed]( https://github.com/royriojas/flat-cache/commit/cd7aeed ), [Jean Ponchon](https://github.com/Jean Ponchon), 25/07/2016 13:11:59
- Use circular-json to handle circular references (fix [#5](https://github.com/royriojas/flat-cache/issues/5)) - [cd7aeed]( https://github.com/royriojas/flat-cache/commit/cd7aeed ), [Jean Ponchon](https://github.com/Jean Ponchon), 25/07/2016 11:11:59
- **Tests Related fixes**
- Add missing file from eslint test - [d6fa3c3]( https://github.com/royriojas/flat-cache/commit/d6fa3c3 ), [Jean Ponchon](https://github.com/Jean Ponchon), 29/07/2016 04:15:51
- Add missing file from eslint test - [d6fa3c3]( https://github.com/royriojas/flat-cache/commit/d6fa3c3 ), [Jean Ponchon](https://github.com/Jean Ponchon), 29/07/2016 02:15:51
- Add test for circular json serialization / deserialization - [07d2ddd]( https://github.com/royriojas/flat-cache/commit/07d2ddd ), [Jean Ponchon](https://github.com/Jean Ponchon), 28/07/2016 10:59:36
- Add test for circular json serialization / deserialization - [07d2ddd]( https://github.com/royriojas/flat-cache/commit/07d2ddd ), [Jean Ponchon](https://github.com/Jean Ponchon), 28/07/2016 08:59:36
- **Refactoring**
- Remove unused read-json-sync - [2be1c24]( https://github.com/royriojas/flat-cache/commit/2be1c24 ), [Jean Ponchon](https://github.com/Jean Ponchon), 28/07/2016 10:59:18
- Remove unused read-json-sync - [2be1c24]( https://github.com/royriojas/flat-cache/commit/2be1c24 ), [Jean Ponchon](https://github.com/Jean Ponchon), 28/07/2016 08:59:18
- **Build Scripts Changes**
- travis tests on 0.12 and 4x - [3a613fd]( https://github.com/royriojas/flat-cache/commit/3a613fd ), [royriojas](https://github.com/royriojas), 15/11/2015 17:34:40
- travis tests on 0.12 and 4x - [3a613fd]( https://github.com/royriojas/flat-cache/commit/3a613fd ), [royriojas](https://github.com/royriojas), 15/11/2015 14:34:40
- add eslint-fix task - [fd29e52]( https://github.com/royriojas/flat-cache/commit/fd29e52 ), [royriojas](https://github.com/royriojas), 01/11/2015 18:04:08
- add eslint-fix task - [fd29e52]( https://github.com/royriojas/flat-cache/commit/fd29e52 ), [royriojas](https://github.com/royriojas), 01/11/2015 15:04:08
- make sure the test script also verify beautification and linting of files before running tests - [e94e176]( https://github.com/royriojas/flat-cache/commit/e94e176 ), [royriojas](https://github.com/royriojas), 01/11/2015 14:54:48
- make sure the test script also verify beautification and linting of files before running tests - [e94e176]( https://github.com/royriojas/flat-cache/commit/e94e176 ), [royriojas](https://github.com/royriojas), 01/11/2015 11:54:48
- **Other changes**
- add clearAll for cacheDir - [97383d9]( https://github.com/royriojas/flat-cache/commit/97383d9 ), [xieyaowu](https://github.com/xieyaowu), 31/10/2015 23:02:18
- add clearAll for cacheDir - [97383d9]( https://github.com/royriojas/flat-cache/commit/97383d9 ), [xieyaowu](https://github.com/xieyaowu), 31/10/2015 21:02:18
## v1.0.9
- **Bug Fixes**
- wrong default values for changelogx user repo name - [7bb52d1]( https://github.com/royriojas/flat-cache/commit/7bb52d1 ), [royriojas](https://github.com/royriojas), 11/09/2015 17:59:30
- wrong default values for changelogx user repo name - [7bb52d1]( https://github.com/royriojas/flat-cache/commit/7bb52d1 ), [royriojas](https://github.com/royriojas), 11/09/2015 15:59:30
## v1.0.8
- **Build Scripts Changes**
- test against node 4 - [c395b66]( https://github.com/royriojas/flat-cache/commit/c395b66 ), [royriojas](https://github.com/royriojas), 11/09/2015 17:51:39
- test against node 4 - [c395b66]( https://github.com/royriojas/flat-cache/commit/c395b66 ), [royriojas](https://github.com/royriojas), 11/09/2015 15:51:39
## v1.0.7
- **Other changes**
- Move dependencies into devDep - [7e47099]( https://github.com/royriojas/flat-cache/commit/7e47099 ), [Bogdan Chadkin](https://github.com/Bogdan Chadkin), 11/09/2015 17:10:57
- Move dependencies into devDep - [7e47099]( https://github.com/royriojas/flat-cache/commit/7e47099 ), [Bogdan Chadkin](https://github.com/Bogdan Chadkin), 11/09/2015 15:10:57
- **Documentation**
- Add missing changelog link - [f51197a]( https://github.com/royriojas/flat-cache/commit/f51197a ), [royriojas](https://github.com/royriojas), 11/09/2015 16:48:05
- Add missing changelog link - [f51197a]( https://github.com/royriojas/flat-cache/commit/f51197a ), [royriojas](https://github.com/royriojas), 11/09/2015 14:48:05
## v1.0.6
- **Build Scripts Changes**
- Add helpers/code check scripts - [bdb82f3]( https://github.com/royriojas/flat-cache/commit/bdb82f3 ), [royriojas](https://github.com/royriojas), 11/09/2015 16:44:31
- Add helpers/code check scripts - [bdb82f3]( https://github.com/royriojas/flat-cache/commit/bdb82f3 ), [royriojas](https://github.com/royriojas), 11/09/2015 14:44:31
## v1.0.5
- **Documentation**
- better description for the module - [436817f]( https://github.com/royriojas/flat-cache/commit/436817f ), [royriojas](https://github.com/royriojas), 11/09/2015 16:35:33
- better description for the module - [436817f]( https://github.com/royriojas/flat-cache/commit/436817f ), [royriojas](https://github.com/royriojas), 11/09/2015 14:35:33
- **Other changes**
- Update dependencies - [be88aa3]( https://github.com/royriojas/flat-cache/commit/be88aa3 ), [Bogdan Chadkin](https://github.com/Bogdan Chadkin), 11/09/2015 15:47:41
- Update dependencies - [be88aa3]( https://github.com/royriojas/flat-cache/commit/be88aa3 ), [Bogdan Chadkin](https://github.com/Bogdan Chadkin), 11/09/2015 13:47:41
## v1.0.11
- **Features**
- Add noPrune option to cache.save() method. closes [#7](https://github.com/royriojas/flat-cache/issues/7) - [2c8016a]( https://github.com/royriojas/flat-cache/commit/2c8016a ), [Roy Riojas](https://github.com/Roy Riojas), 01/08/2016 04:00:29
- Add noPrune option to cache.save() method. closes [#7](https://github.com/royriojas/flat-cache/issues/7) - [2c8016a]( https://github.com/royriojas/flat-cache/commit/2c8016a ), [Roy Riojas](https://github.com/Roy Riojas), 01/08/2016 02:00:29
- Add json read and write utility based on circular-json - [c31081e]( https://github.com/royriojas/flat-cache/commit/c31081e ), [Jean Ponchon](https://github.com/Jean Ponchon), 28/07/2016 10:58:17
- Add json read and write utility based on circular-json - [c31081e]( https://github.com/royriojas/flat-cache/commit/c31081e ), [Jean Ponchon](https://github.com/Jean Ponchon), 28/07/2016 08:58:17
- **Bug Fixes**
- Remove UTF16 BOM stripping - [4a41e22]( https://github.com/royriojas/flat-cache/commit/4a41e22 ), [Jean Ponchon](https://github.com/Jean Ponchon), 29/07/2016 04:18:06
- Remove UTF16 BOM stripping - [4a41e22]( https://github.com/royriojas/flat-cache/commit/4a41e22 ), [Jean Ponchon](https://github.com/Jean Ponchon), 29/07/2016 02:18:06
Since we control both writing and reading of JSON stream, there no needs
to handle unicode BOM.
- Use circular-json to handle circular references (fix [#5](https://github.com/royriojas/flat-cache/issues/5)) - [cd7aeed]( https://github.com/royriojas/flat-cache/commit/cd7aeed ), [Jean Ponchon](https://github.com/Jean Ponchon), 25/07/2016 13:11:59
- Use circular-json to handle circular references (fix [#5](https://github.com/royriojas/flat-cache/issues/5)) - [cd7aeed]( https://github.com/royriojas/flat-cache/commit/cd7aeed ), [Jean Ponchon](https://github.com/Jean Ponchon), 25/07/2016 11:11:59
- **Tests Related fixes**
- Add missing file from eslint test - [d6fa3c3]( https://github.com/royriojas/flat-cache/commit/d6fa3c3 ), [Jean Ponchon](https://github.com/Jean Ponchon), 29/07/2016 04:15:51
- Add missing file from eslint test - [d6fa3c3]( https://github.com/royriojas/flat-cache/commit/d6fa3c3 ), [Jean Ponchon](https://github.com/Jean Ponchon), 29/07/2016 02:15:51
- Add test for circular json serialization / deserialization - [07d2ddd]( https://github.com/royriojas/flat-cache/commit/07d2ddd ), [Jean Ponchon](https://github.com/Jean Ponchon), 28/07/2016 10:59:36
- Add test for circular json serialization / deserialization - [07d2ddd]( https://github.com/royriojas/flat-cache/commit/07d2ddd ), [Jean Ponchon](https://github.com/Jean Ponchon), 28/07/2016 08:59:36
- **Refactoring**
- Remove unused read-json-sync - [2be1c24]( https://github.com/royriojas/flat-cache/commit/2be1c24 ), [Jean Ponchon](https://github.com/Jean Ponchon), 28/07/2016 10:59:18
- Remove unused read-json-sync - [2be1c24]( https://github.com/royriojas/flat-cache/commit/2be1c24 ), [Jean Ponchon](https://github.com/Jean Ponchon), 28/07/2016 08:59:18
- **Build Scripts Changes**
- travis tests on 0.12 and 4x - [3a613fd]( https://github.com/royriojas/flat-cache/commit/3a613fd ), [royriojas](https://github.com/royriojas), 15/11/2015 17:34:40
- travis tests on 0.12 and 4x - [3a613fd]( https://github.com/royriojas/flat-cache/commit/3a613fd ), [royriojas](https://github.com/royriojas), 15/11/2015 14:34:40
## v1.0.10
- **Build Scripts Changes**
- add eslint-fix task - [fd29e52]( https://github.com/royriojas/flat-cache/commit/fd29e52 ), [royriojas](https://github.com/royriojas), 01/11/2015 18:04:08
- add eslint-fix task - [fd29e52]( https://github.com/royriojas/flat-cache/commit/fd29e52 ), [royriojas](https://github.com/royriojas), 01/11/2015 15:04:08
- make sure the test script also verify beautification and linting of files before running tests - [e94e176]( https://github.com/royriojas/flat-cache/commit/e94e176 ), [royriojas](https://github.com/royriojas), 01/11/2015 14:54:48
- make sure the test script also verify beautification and linting of files before running tests - [e94e176]( https://github.com/royriojas/flat-cache/commit/e94e176 ), [royriojas](https://github.com/royriojas), 01/11/2015 11:54:48
- test against node 4 - [c395b66]( https://github.com/royriojas/flat-cache/commit/c395b66 ), [royriojas](https://github.com/royriojas), 11/09/2015 17:51:39
- test against node 4 - [c395b66]( https://github.com/royriojas/flat-cache/commit/c395b66 ), [royriojas](https://github.com/royriojas), 11/09/2015 15:51:39
- Add helpers/code check scripts - [bdb82f3]( https://github.com/royriojas/flat-cache/commit/bdb82f3 ), [royriojas](https://github.com/royriojas), 11/09/2015 16:44:31
- Add helpers/code check scripts - [bdb82f3]( https://github.com/royriojas/flat-cache/commit/bdb82f3 ), [royriojas](https://github.com/royriojas), 11/09/2015 14:44:31
- **Other changes**
- add clearAll for cacheDir - [97383d9]( https://github.com/royriojas/flat-cache/commit/97383d9 ), [xieyaowu](https://github.com/xieyaowu), 31/10/2015 23:02:18
- add clearAll for cacheDir - [97383d9]( https://github.com/royriojas/flat-cache/commit/97383d9 ), [xieyaowu](https://github.com/xieyaowu), 31/10/2015 21:02:18
- Move dependencies into devDep - [7e47099]( https://github.com/royriojas/flat-cache/commit/7e47099 ), [Bogdan Chadkin](https://github.com/Bogdan Chadkin), 11/09/2015 17:10:57
- Move dependencies into devDep - [7e47099]( https://github.com/royriojas/flat-cache/commit/7e47099 ), [Bogdan Chadkin](https://github.com/Bogdan Chadkin), 11/09/2015 15:10:57
- Update dependencies - [be88aa3]( https://github.com/royriojas/flat-cache/commit/be88aa3 ), [Bogdan Chadkin](https://github.com/Bogdan Chadkin), 11/09/2015 15:47:41
- Update dependencies - [be88aa3]( https://github.com/royriojas/flat-cache/commit/be88aa3 ), [Bogdan Chadkin](https://github.com/Bogdan Chadkin), 11/09/2015 13:47:41
- **Bug Fixes**
- wrong default values for changelogx user repo name - [7bb52d1]( https://github.com/royriojas/flat-cache/commit/7bb52d1 ), [royriojas](https://github.com/royriojas), 11/09/2015 17:59:30
- wrong default values for changelogx user repo name - [7bb52d1]( https://github.com/royriojas/flat-cache/commit/7bb52d1 ), [royriojas](https://github.com/royriojas), 11/09/2015 15:59:30
- **Documentation**
- Add missing changelog link - [f51197a]( https://github.com/royriojas/flat-cache/commit/f51197a ), [royriojas](https://github.com/royriojas), 11/09/2015 16:48:05
- Add missing changelog link - [f51197a]( https://github.com/royriojas/flat-cache/commit/f51197a ), [royriojas](https://github.com/royriojas), 11/09/2015 14:48:05
- better description for the module - [436817f]( https://github.com/royriojas/flat-cache/commit/436817f ), [royriojas](https://github.com/royriojas), 11/09/2015 16:35:33
- better description for the module - [436817f]( https://github.com/royriojas/flat-cache/commit/436817f ), [royriojas](https://github.com/royriojas), 11/09/2015 14:35:33
- Add documentation about `clearAll` and `clearCacheById` - [13947c1]( https://github.com/royriojas/flat-cache/commit/13947c1 ), [Roy Riojas](https://github.com/Roy Riojas), 02/03/2015 02:44:05
- Add documentation about `clearAll` and `clearCacheById` - [13947c1]( https://github.com/royriojas/flat-cache/commit/13947c1 ), [Roy Riojas](https://github.com/Roy Riojas), 01/03/2015 23:44:05
- **Refactoring**
- load a cache file using the full filepath - [b8f68c2]( https://github.com/royriojas/flat-cache/commit/b8f68c2 ), [Roy Riojas](https://github.com/Roy Riojas), 30/08/2015 06:19:14
- load a cache file using the full filepath - [b8f68c2]( https://github.com/royriojas/flat-cache/commit/b8f68c2 ), [Roy Riojas](https://github.com/Roy Riojas), 30/08/2015 04:19:14
- **Features**
- Add methods to remove the cache documents created - [af40443]( https://github.com/royriojas/flat-cache/commit/af40443 ), [Roy Riojas](https://github.com/Roy Riojas), 02/03/2015 02:39:27
- Add methods to remove the cache documents created - [af40443]( https://github.com/royriojas/flat-cache/commit/af40443 ), [Roy Riojas](https://github.com/Roy Riojas), 01/03/2015 23:39:27
## v1.0.1
- **Other changes**
- Update README.md - [c2b6805]( https://github.com/royriojas/flat-cache/commit/c2b6805 ), [Roy Riojas](https://github.com/Roy Riojas), 26/02/2015 07:28:07
- Update README.md - [c2b6805]( https://github.com/royriojas/flat-cache/commit/c2b6805 ), [Roy Riojas](https://github.com/Roy Riojas), 26/02/2015 04:28:07
## v1.0.0
- **Refactoring**
- flat-cache v.1.0.0 - [c984274]( https://github.com/royriojas/flat-cache/commit/c984274 ), [Roy Riojas](https://github.com/Roy Riojas), 26/02/2015 07:11:50
- flat-cache v.1.0.0 - [c984274]( https://github.com/royriojas/flat-cache/commit/c984274 ), [Roy Riojas](https://github.com/Roy Riojas), 26/02/2015 04:11:50
- **Other changes**
- Initial commit - [d43cccf]( https://github.com/royriojas/flat-cache/commit/d43cccf ), [Roy Riojas](https://github.com/Roy Riojas), 26/02/2015 04:12:16
- Initial commit - [d43cccf]( https://github.com/royriojas/flat-cache/commit/d43cccf ), [Roy Riojas](https://github.com/Roy Riojas), 26/02/2015 01:12:16

View File

@ -0,0 +1,13 @@
var rimraf = require( 'rimraf' ).sync;
var fs = require( 'graceful-fs' );
module.exports = function del( file ) {
if ( fs.existsSync( file ) ) {
//if rimraf doesn't throw then the file has been deleted or didn't exist
rimraf( file, {
glob: false
} );
return true;
}
return false;
};

View File

@ -21,8 +21,8 @@
},
"dependencies": {
"circular-json": "^0.3.1",
"del": "^3.0.0",
"graceful-fs": "^4.1.2",
"rimraf": "~2.6.2",
"write": "^0.2.1"
},
"deprecated": false,
@ -47,7 +47,8 @@
},
"files": [
"cache.js",
"utils.js"
"utils.js",
"del.js"
],
"homepage": "https://github.com/royriojas/flat-cache#readme",
"keywords": [
@ -73,7 +74,7 @@
},
"scripts": {
"autofix": "npm run beautify && npm run eslint-fix",
"beautify": "esbeautifier 'cache.js' 'test/specs/**/*.js'",
"beautify": "esbeautifier 'cache.js' 'utils.js' 'del.js' 'test/specs/**/*.js'",
"beautify-check": "npm run beautify -- -k",
"bump-major": "npm run pre-v && npm version major -m 'BLD: Release v%s' && npm run post-v",
"bump-minor": "npm run pre-v && npm version minor -m 'BLD: Release v%s' && npm run post-v",
@ -82,7 +83,7 @@
"check": "npm run beautify-check && npm run eslint",
"cover": "istanbul cover test/runner.js html text-summary",
"do-changelog": "npm run changelog && git add ./changelog.md && git commit -m 'DOC: Generate changelog' --no-verify",
"eslint": "eslinter 'cache.js' 'utils.js' 'specs/**/*.js'",
"eslint": "eslinter 'cache.js' 'utils.js' 'del.js' 'specs/**/*.js'",
"eslint-fix": "npm run eslint -- --fix",
"install-hooks": "prepush install && changelogx install-hook && precommit install",
"post-v": "npm run do-changelog && git push --no-verify && git push --tags --no-verify",
@ -92,5 +93,5 @@
"verify": "npm run check && npm run test:cache",
"watch": "watch-run -i -p 'test/specs/**/*.js' istanbul cover test/runner.js html text-summary"
},
"version": "1.3.2"
"version": "1.3.4"
}

View File

@ -4,7 +4,7 @@ var circularJson = require( 'circular-json' );
module.exports = {
tryParse: function ( filePath, defaultValue) {
tryParse: function ( filePath, defaultValue ) {
var result;
try {
result = this.readJSON( filePath );
@ -32,7 +32,7 @@ module.exports = {
* @param {String} filePath Json filepath
* @param {*} data Object to serialize
*/
writeJSON: function (filePath, data ) {
writeJSON: function ( filePath, data ) {
write.sync( filePath, circularJson.stringify( data ) );
}

View File

@ -698,6 +698,7 @@
"PushManager": false,
"PushSubscription": false,
"PushSubscriptionOptions": false,
"queueMicrotask": false,
"RadioNodeList": false,
"Range": false,
"ReadableStream": false,
@ -984,6 +985,7 @@
"PerformanceTiming": false,
"postMessage": true,
"Promise": false,
"queueMicrotask": false,
"Request": false,
"Response": false,
"self": true,
@ -1012,10 +1014,13 @@
"Intl": false,
"module": false,
"process": false,
"queueMicrotask": false,
"require": false,
"setImmediate": false,
"setInterval": false,
"setTimeout": false,
"TextDecoder": false,
"TextEncoder": false,
"URL": false,
"URLSearchParams": false
},

View File

@ -41,7 +41,7 @@
"scripts": {
"test": "xo && ava"
},
"version": "11.8.0",
"version": "11.9.0",
"xo": {
"ignores": [
"get-browser-globals.js"

View File

@ -1,88 +0,0 @@
'use strict';
var Promise = require('pinkie-promise');
var arrayUnion = require('array-union');
var objectAssign = require('object-assign');
var glob = require('glob');
var pify = require('pify');
var globP = pify(glob, Promise).bind(glob);
function isNegative(pattern) {
return pattern[0] === '!';
}
function isString(value) {
return typeof value === 'string';
}
function assertPatternsInput(patterns) {
if (!patterns.every(isString)) {
throw new TypeError('patterns must be a string or an array of strings');
}
}
function generateGlobTasks(patterns, opts) {
patterns = [].concat(patterns);
assertPatternsInput(patterns);
var globTasks = [];
opts = objectAssign({
cache: Object.create(null),
statCache: Object.create(null),
realpathCache: Object.create(null),
symlinks: Object.create(null),
ignore: []
}, opts);
patterns.forEach(function (pattern, i) {
if (isNegative(pattern)) {
return;
}
var ignore = patterns.slice(i).filter(isNegative).map(function (pattern) {
return pattern.slice(1);
});
globTasks.push({
pattern: pattern,
opts: objectAssign({}, opts, {
ignore: opts.ignore.concat(ignore)
})
});
});
return globTasks;
}
module.exports = function (patterns, opts) {
var globTasks;
try {
globTasks = generateGlobTasks(patterns, opts);
} catch (err) {
return Promise.reject(err);
}
return Promise.all(globTasks.map(function (task) {
return globP(task.pattern, task.opts);
})).then(function (paths) {
return arrayUnion.apply(null, paths);
});
};
module.exports.sync = function (patterns, opts) {
var globTasks = generateGlobTasks(patterns, opts);
return globTasks.reduce(function (matches, task) {
return arrayUnion(matches, glob.sync(task.pattern, task.opts));
}, []);
};
module.exports.generateGlobTasks = generateGlobTasks;
module.exports.hasMagic = function (patterns, opts) {
return [].concat(patterns).some(function (pattern) {
return glob.hasMagic(pattern, opts);
});
};

View File

@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -1,68 +0,0 @@
'use strict';
var processFn = function (fn, P, opts) {
return function () {
var that = this;
var args = new Array(arguments.length);
for (var i = 0; i < arguments.length; i++) {
args[i] = arguments[i];
}
return new P(function (resolve, reject) {
args.push(function (err, result) {
if (err) {
reject(err);
} else if (opts.multiArgs) {
var results = new Array(arguments.length - 1);
for (var i = 1; i < arguments.length; i++) {
results[i - 1] = arguments[i];
}
resolve(results);
} else {
resolve(result);
}
});
fn.apply(that, args);
});
};
};
var pify = module.exports = function (obj, P, opts) {
if (typeof P !== 'function') {
opts = P;
P = Promise;
}
opts = opts || {};
opts.exclude = opts.exclude || [/.+Sync$/];
var filter = function (key) {
var match = function (pattern) {
return typeof pattern === 'string' ? key === pattern : pattern.test(key);
};
return opts.include ? opts.include.some(match) : !opts.exclude.some(match);
};
var ret = typeof obj === 'function' ? function () {
if (opts.excludeMain) {
return obj.apply(this, arguments);
}
return processFn(obj, P, opts).apply(this, arguments);
} : {};
return Object.keys(obj).reduce(function (ret, key) {
var x = obj[key];
ret[key] = typeof x === 'function' && filter(key) ? processFn(x, P, opts) : x;
return ret;
}, ret);
};
pify.all = pify;

View File

@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -1,57 +0,0 @@
{
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/sindresorhus/pify/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Promisify a callback-style function",
"devDependencies": {
"ava": "*",
"pinkie-promise": "^1.0.0",
"v8-natives": "0.0.2",
"xo": "*"
},
"engines": {
"node": ">=0.10.0"
},
"files": [
"index.js"
],
"homepage": "https://github.com/sindresorhus/pify#readme",
"keywords": [
"promise",
"promises",
"promisify",
"denodify",
"denodeify",
"callback",
"cb",
"node",
"then",
"thenify",
"convert",
"transform",
"wrap",
"wrapper",
"bind",
"to",
"async",
"es2015"
],
"license": "MIT",
"name": "pify",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/pify.git"
},
"scripts": {
"optimization-test": "node --allow-natives-syntax optimization-test.js",
"test": "xo && ava && npm run optimization-test"
},
"version": "2.3.0"
}

View File

@ -1,119 +0,0 @@
# pify [![Build Status](https://travis-ci.org/sindresorhus/pify.svg?branch=master)](https://travis-ci.org/sindresorhus/pify)
> Promisify a callback-style function
## Install
```
$ npm install --save pify
```
## Usage
```js
const fs = require('fs');
const pify = require('pify');
// promisify a single function
pify(fs.readFile)('package.json', 'utf8').then(data => {
console.log(JSON.parse(data).name);
//=> 'pify'
});
// or promisify all methods in a module
pify(fs).readFile('package.json', 'utf8').then(data => {
console.log(JSON.parse(data).name);
//=> 'pify'
});
```
## API
### pify(input, [promiseModule], [options])
Returns a promise wrapped version of the supplied function or module.
#### input
Type: `function`, `object`
Callback-style function or module whose methods you want to promisify.
#### promiseModule
Type: `function`
Custom promise module to use instead of the native one.
Check out [`pinkie-promise`](https://github.com/floatdrop/pinkie-promise) if you need a tiny promise polyfill.
#### options
##### multiArgs
Type: `boolean`
Default: `false`
By default, the promisified function will only return the second argument from the callback, which works fine for most APIs. This option can be useful for modules like `request` that return multiple arguments. Turning this on will make it return an array of all arguments from the callback, excluding the error argument, instead of just the second argument.
```js
const request = require('request');
const pify = require('pify');
pify(request, {multiArgs: true})('https://sindresorhus.com').then(result => {
const [httpResponse, body] = result;
});
```
##### include
Type: `array` of (`string`|`regex`)
Methods in a module to promisify. Remaining methods will be left untouched.
##### exclude
Type: `array` of (`string`|`regex`)
Default: `[/.+Sync$/]`
Methods in a module **not** to promisify. Methods with names ending with `'Sync'` are excluded by default.
##### excludeMain
Type: `boolean`
Default: `false`
By default, if given module is a function itself, this function will be promisified. Turn this option on if you want to promisify only methods of the module.
```js
const pify = require('pify');
function fn() {
return true;
}
fn.method = (data, callback) => {
setImmediate(() => {
callback(data, null);
});
};
// promisify methods but not fn()
const promiseFn = pify(fn, {excludeMain: true});
if (promiseFn()) {
promiseFn.method('hi').then(data => {
console.log(data);
});
}
```
## License
MIT © [Sindre Sorhus](http://sindresorhus.com)

View File

@ -1,78 +0,0 @@
{
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/sindresorhus/globby/issues"
},
"bundleDependencies": false,
"dependencies": {
"array-union": "^1.0.1",
"glob": "^7.0.3",
"object-assign": "^4.0.1",
"pify": "^2.0.0",
"pinkie-promise": "^2.0.0"
},
"deprecated": false,
"description": "Extends `glob` with support for multiple patterns and exposes a Promise API",
"devDependencies": {
"ava": "*",
"glob-stream": "github:gulpjs/glob-stream#master",
"globby": "github:sindresorhus/globby#master",
"matcha": "^0.7.0",
"rimraf": "^2.2.8",
"xo": "^0.16.0"
},
"engines": {
"node": ">=0.10.0"
},
"files": [
"index.js"
],
"homepage": "https://github.com/sindresorhus/globby#readme",
"keywords": [
"all",
"array",
"directories",
"dirs",
"expand",
"files",
"filesystem",
"filter",
"find",
"fnmatch",
"folders",
"fs",
"glob",
"globbing",
"globs",
"gulpfriendly",
"match",
"matcher",
"minimatch",
"multi",
"multiple",
"paths",
"pattern",
"patterns",
"traverse",
"util",
"utility",
"wildcard",
"wildcards",
"promise"
],
"license": "MIT",
"name": "globby",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/globby.git"
},
"scripts": {
"bench": "npm update glob-stream && matcha bench.js",
"test": "xo && ava"
},
"version": "6.1.0"
}

View File

@ -1,88 +0,0 @@
# globby [![Build Status](https://travis-ci.org/sindresorhus/globby.svg?branch=master)](https://travis-ci.org/sindresorhus/globby)
> Extends [glob](https://github.com/isaacs/node-glob) with support for multiple patterns and exposes a Promise API
## Install
```
$ npm install --save globby
```
## Usage
```
├── unicorn
├── cake
└── rainbow
```
```js
const globby = require('globby');
globby(['*', '!cake']).then(paths => {
console.log(paths);
//=> ['unicorn', 'rainbow']
});
```
## API
### globby(patterns, [options])
Returns a Promise for an array of matching paths.
### globby.sync(patterns, [options])
Returns an array of matching paths.
### globby.generateGlobTasks(patterns, [options])
Returns an array of objects in the format `{ pattern: string, opts: Object }`, which can be passed as arguments to [`node-glob`](https://github.com/isaacs/node-glob). This is useful for other globbing-related packages.
Note that you should avoid running the same tasks multiple times as they contain a file system cache. Instead, run this method each time to ensure file system changes are taken into consideration.
### globby.hasMagic(patterns, [options])
Returns a `boolean` of whether there are any special glob characters in the `patterns`.
Note that the options affect the results. If `noext: true` is set, then `+(a|b)` will not be considered a magic pattern. If the pattern has a brace expansion, like `a/{b/c,x/y}`, then that is considered magical, unless `nobrace: true` is set.
#### patterns
Type: `string` `Array`
See supported `minimatch` [patterns](https://github.com/isaacs/minimatch#usage).
#### options
Type: `Object`
See the `node-glob` [options](https://github.com/isaacs/node-glob#options).
## Globbing patterns
Just a quick overview.
- `*` matches any number of characters, but not `/`
- `?` matches a single character, but not `/`
- `**` matches any number of characters, including `/`, as long as it's the only thing in a path part
- `{}` allows for a comma-separated list of "or" expressions
- `!` at the beginning of a pattern will negate the match
[Various patterns and expected matches.](https://github.com/sindresorhus/multimatch/blob/master/test.js)
## Related
- [multimatch](https://github.com/sindresorhus/multimatch) - Match against a list instead of the filesystem
- [glob-stream](https://github.com/wearefractal/glob-stream) - Streaming alternative
- [matcher](https://github.com/sindresorhus/matcher) - Simple wildcard matching
## License
MIT © [Sindre Sorhus](https://sindresorhus.com)

View File

@ -0,0 +1,424 @@
<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"/>
# 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)
A collection of common interactive command line user interfaces.
**Version 4.x** only supports Node 6 and over. For Node 4 support please use [version 3.x](https://github.com/SBoudrias/Inquirer.js/tree/v3.3.0).
## Table of Contents
1. [Documentation](#documentation)
1. [Installation](#installation)
2. [Examples](#examples)
3. [Methods](#methods)
4. [Objects](#objects)
5. [Questions](#questions)
6. [Answers](#answers)
7. [Separator](#separator)
8. [Prompt Types](#prompt)
2. [User Interfaces and Layouts](#layouts)
1. [Reactive Interface](#reactive)
3. [Support](#support)
4. [News](#news)
5. [Contributing](#contributing)
6. [License](#license)
7. [Plugins](#plugins)
## Goal and Philosophy
**`Inquirer.js`** strives to be an easily embeddable and beautiful command line interface for [Node.js](https://nodejs.org/) (and perhaps the "CLI [Xanadu](https://en.wikipedia.org/wiki/Citizen_Kane)").
**`Inquirer.js`** should ease the process of
- providing _error feedback_
- _asking questions_
- _parsing_ input
- _validating_ answers
- managing _hierarchical prompts_
> **Note:** **`Inquirer.js`** provides the user interface and the inquiry session flow. If you're searching for a full blown command line program utility, then check out [commander](https://github.com/visionmedia/commander.js), [vorpal](https://github.com/dthree/vorpal) or [args](https://github.com/leo/args).
## [Documentation](#documentation)
<a name="documentation"></a>
### Installation
<a name="installation"></a>
```shell
npm install inquirer
```
```javascript
var inquirer = require('inquirer');
inquirer
.prompt([
/* Pass your questions in here */
])
.then(answers => {
// Use user feedback for... whatever!!
});
```
<a name="examples"></a>
### Examples (Run it and see it)
Check out the [`packages/inquirer/examples/`](https://github.com/SBoudrias/Inquirer.js/tree/master/packages/inquirer/examples) folder for code and interface examples.
```shell
node packages/inquirer/examples/pizza.js
node packages/inquirer/examples/checkbox.js
# etc...
```
### Methods
<a name="methods"></a>
#### `inquirer.prompt(questions) -> promise`
Launch the prompt interface (inquiry session)
- **questions** (Array) containing [Question Object](#question) (using the [reactive interface](#reactive-interface), you can also pass a `Rx.Observable` instance)
- returns a **Promise**
#### `inquirer.registerPrompt(name, prompt)`
Register prompt plugins under `name`.
- **name** (string) name of the this new prompt. (used for question `type`)
- **prompt** (object) the prompt object itself (the plugin)
#### `inquirer.createPromptModule() -> prompt function`
Create a self contained inquirer module. If you don't want to affect other libraries that also rely on inquirer when you overwrite or add new prompt types.
```js
var prompt = inquirer.createPromptModule();
prompt(questions).then(/* ... */);
```
### Objects
<a name="objects"></a>
#### Question
<a name="questions"></a>
A question object is a `hash` containing question related values:
- **type**: (String) Type of the prompt. Defaults: `input` - Possible values: `input`, `confirm`,
`list`, `rawlist`, `expand`, `checkbox`, `password`, `editor`
- **name**: (String) The name to use when storing the answer in the answers hash. If the name contains periods, it will define a path in the answers hash.
- **message**: (String|Function) The question to print. If defined as a function, the first parameter will be the current inquirer session answers. Defaults to the value of `name` (followed by a colon).
- **default**: (String|Number|Boolean|Array|Function) Default value(s) to use if nothing is entered, or a function that returns the default value(s). If defined as a function, the first parameter will be the current inquirer session answers.
- **choices**: (Array|Function) Choices array or a function returning a choices array. If defined as a function, the first parameter will be the current inquirer session answers.
Array values can be simple `strings`, or `objects` containing a `name` (to display in list), a `value` (to save in the answers hash) and a `short` (to display after selection) properties. The choices array can also contain [a `Separator`](#separator).
- **validate**: (Function) Receive the user input and answers hash. Should return `true` if the value is valid, and an error message (`String`) otherwise. If `false` is returned, a default error message is provided.
- **filter**: (Function) Receive the user input and return the filtered value to be used inside the program. The value returned will be added to the _Answers_ hash.
- **transformer**: (Function) Receive the user input, answers hash and option flags, and return a transformed value to display to the user. The transformation only impacts what is shown while editing. It does not modify the answers hash.
- **when**: (Function, Boolean) Receive the current user answers hash and should return `true` or `false` depending on whether or not this question should be asked. The value can also be a simple boolean.
- **pageSize**: (Number) Change the number of lines that will be rendered when using `list`, `rawList`, `expand` or `checkbox`.
- **prefix**: (String) Change the default _prefix_ message.
- **suffix**: (String) Change the default _suffix_ message.
`default`, `choices`(if defined as functions), `validate`, `filter` and `when` functions can be called asynchronously. Either return a promise or use `this.async()` to get a callback you'll call with the final value.
```javascript
{
/* Preferred way: with promise */
filter() {
return new Promise(/* etc... */);
},
/* Legacy way: with this.async */
validate: function (input) {
// Declare function as asynchronous, and save the done callback
var done = this.async();
// Do async stuff
setTimeout(function() {
if (typeof input !== 'number') {
// Pass the return value in the done callback
done('You need to provide a number');
return;
}
// Pass the return value in the done callback
done(null, true);
}, 3000);
}
}
```
### Answers
<a name="answers"></a>
A key/value hash containing the client answers in each prompt.
- **Key** The `name` property of the _question_ object
- **Value** (Depends on the prompt)
- `confirm`: (Boolean)
- `input` : User input (filtered if `filter` is defined) (String)
- `rawlist`, `list` : Selected choice value (or name if no value specified) (String)
### Separator
<a name="separator"></a>
A separator can be added to any `choices` array:
```
// In the question object
choices: [ "Choice A", new inquirer.Separator(), "choice B" ]
// Which'll be displayed this way
[?] What do you want to do?
> Order a pizza
Make a reservation
--------
Ask opening hours
Talk to the receptionist
```
The constructor takes a facultative `String` value that'll be use as the separator. If omitted, the separator will be `--------`.
Separator instances have a property `type` equal to `separator`. This should allow tools façading Inquirer interface from detecting separator types in lists.
<a name="prompt"></a>
### Prompt types
---
> **Note:**: _allowed options written inside square brackets (`[]`) are optional. Others are required._
#### List - `{type: 'list'}`
Take `type`, `name`, `message`, `choices`[, `default`, `filter`] properties. (Note that
default must be the choice `index` in the array or a choice `value`)
![List prompt](https://cdn.rawgit.com/SBoudrias/Inquirer.js/28ae8337ba51d93e359ef4f7ee24e79b69898962/assets/screenshots/list.svg)
---
#### Raw List - `{type: 'rawlist'}`
Take `type`, `name`, `message`, `choices`[, `default`, `filter`] properties. (Note that
default must be the choice `index` in the array)
![Raw list prompt](https://cdn.rawgit.com/SBoudrias/Inquirer.js/28ae8337ba51d93e359ef4f7ee24e79b69898962/assets/screenshots/rawlist.svg)
---
#### Expand - `{type: 'expand'}`
Take `type`, `name`, `message`, `choices`[, `default`] properties. (Note that
default must be the choice `index` in the array. If `default` key not provided, then `help` will be used as default choice)
Note that the `choices` object will take an extra parameter called `key` for the `expand` prompt. This parameter must be a single (lowercased) character. The `h` option is added by the prompt and shouldn't be defined by the user.
See `examples/expand.js` for a running example.
![Expand prompt closed](https://cdn.rawgit.com/SBoudrias/Inquirer.js/28ae8337ba51d93e359ef4f7ee24e79b69898962/assets/screenshots/expand-y.svg)
![Expand prompt expanded](https://cdn.rawgit.com/SBoudrias/Inquirer.js/28ae8337ba51d93e359ef4f7ee24e79b69898962/assets/screenshots/expand-d.svg)
---
#### Checkbox - `{type: 'checkbox'}`
Take `type`, `name`, `message`, `choices`[, `filter`, `validate`, `default`] properties. `default` is expected to be an Array of the checked choices value.
Choices marked as `{checked: true}` will be checked by default.
Choices whose property `disabled` is truthy will be unselectable. If `disabled` is a string, then the string will be outputted next to the disabled choice, otherwise it'll default to `"Disabled"`. The `disabled` property can also be a synchronous function receiving the current answers as argument and returning a boolean or a string.
![Checkbox prompt](https://cdn.rawgit.com/SBoudrias/Inquirer.js/28ae8337ba51d93e359ef4f7ee24e79b69898962/assets/screenshots/checkbox.svg)
---
#### Confirm - `{type: 'confirm'}`
Take `type`, `name`, `message`, [`default`] properties. `default` is expected to be a boolean if used.
![Confirm prompt](https://cdn.rawgit.com/SBoudrias/Inquirer.js/28ae8337ba51d93e359ef4f7ee24e79b69898962/assets/screenshots/confirm.svg)
---
#### Input - `{type: 'input'}`
Take `type`, `name`, `message`[, `default`, `filter`, `validate`, `transformer`] properties.
![Input prompt](https://cdn.rawgit.com/SBoudrias/Inquirer.js/28ae8337ba51d93e359ef4f7ee24e79b69898962/assets/screenshots/input.svg)
---
#### Password - `{type: 'password'}`
Take `type`, `name`, `message`, `mask`,[, `default`, `filter`, `validate`] properties.
![Password prompt](https://cdn.rawgit.com/SBoudrias/Inquirer.js/28ae8337ba51d93e359ef4f7ee24e79b69898962/assets/screenshots/password.svg)
---
Note that `mask` is required to hide the actual user input.
#### Editor - `{type: 'editor'}`
Take `type`, `name`, `message`[, `default`, `filter`, `validate`] properties
Launches an instance of the users preferred editor on a temporary file. Once the user exits their editor, the contents of the temporary file are read in as the result. The editor to use is determined by reading the $VISUAL or $EDITOR environment variables. If neither of those are present, notepad (on Windows) or vim (Linux or Mac) is used.
<a name="layouts"></a>
## User Interfaces and layouts
Along with the prompts, Inquirer offers some basic text UI.
#### Bottom Bar - `inquirer.ui.BottomBar`
This UI present a fixed text at the bottom of a free text zone. This is useful to keep a message to the bottom of the screen while outputting command outputs on the higher section.
```javascript
var ui = new inquirer.ui.BottomBar();
// pipe a Stream to the log zone
outputStream.pipe(ui.log);
// Or simply write output
ui.log.write('something just happened.');
ui.log.write('Almost over, standby!');
// During processing, update the bottom bar content to display a loader
// or output a progress bar, etc
ui.updateBottomBar('new bottom bar content');
```
<a name="reactive"></a>
## Reactive interface
Internally, Inquirer uses the [JS reactive extension](https://github.com/ReactiveX/rxjs) to handle events and async flows.
This mean you can take advantage of this feature to provide more advanced flows. For example, you can dynamically add questions to be asked:
```js
var prompts = new Rx.Subject();
inquirer.prompt(prompts);
// At some point in the future, push new questions
prompts.next({
/* question... */
});
prompts.next({
/* question... */
});
// When you're done
prompts.complete();
```
And using the return value `process` property, you can access more fine grained callbacks:
```js
inquirer.prompt(prompts).ui.process.subscribe(onEachAnswer, onError, onComplete);
```
## Support (OS Terminals)
<a name="support"></a>
You should expect mostly good support for the CLI below. This does not mean we won't
look at issues found on other command line - feel free to report any!
- **Mac OS**:
- Terminal.app
- iTerm
- **Windows**:
- [ConEmu](https://conemu.github.io/)
- cmd.exe
- Powershell
- Cygwin
- **Linux (Ubuntu, openSUSE, Arch Linux, etc)**:
- gnome-terminal (Terminal GNOME)
- konsole
## News on the march (Release notes)
<a name="news"></a>
Please refer to the [Github releases section for the changelog](https://github.com/SBoudrias/Inquirer.js/releases)
## Contributing
<a name="contributing"></a>
**Unit test**
Unit test are written in [Mocha](https://mochajs.org/). Please add a unit test for every new feature or bug fix. `npm test` to run the test suite.
**Documentation**
Add documentation for every API change. Feel free to send typo fixes and better docs!
We're looking to offer good support for multiple prompts and environments. If you want to
help, we'd like to keep a list of testers for each terminal/OS so we can contact you and
get feedback before release. Let us know if you want to be added to the list (just tweet
to [@vaxilart](https://twitter.com/Vaxilart)) or just add your name to [the wiki](https://github.com/SBoudrias/Inquirer.js/wiki/Testers)
## License
<a name="license"></a>
Copyright (c) 2016 Simon Boudrias (twitter: [@vaxilart](https://twitter.com/Vaxilart))
Licensed under the MIT license.
## Plugins
<a name="plugins"></a>
### Prompts
[**autocomplete**](https://github.com/mokkabonna/inquirer-autocomplete-prompt)<br>
Presents a list of options as the user types, compatible with other packages such as fuzzy (for search)<br>
<br>
![autocomplete prompt](https://github.com/mokkabonna/inquirer-autocomplete-prompt/raw/master/inquirer.gif)
[**checkbox-plus**](https://github.com/faressoft/inquirer-checkbox-plus-prompt)<br>
Checkbox list with autocomplete and other additions<br>
<br>
![checkbox-plus](https://github.com/faressoft/inquirer-checkbox-plus-prompt/raw/master/demo.gif)
[**datetime**](https://github.com/DerekTBrown/inquirer-datepicker-prompt)<br>
Customizable date/time selector using both number pad and arrow keys<br>
<br>
![Datetime Prompt](https://github.com/DerekTBrown/inquirer-datepicker-prompt/raw/master/example/datetime-prompt.png)
[**inquirer-select-line**](https://github.com/adam-golab/inquirer-select-line)<br>
Prompt for selecting index in array where add new element<br>
<br>
![inquirer-select-line gif](https://media.giphy.com/media/xUA7b1MxpngddUvdHW/giphy.gif)
[**command**](https://github.com/sullof/inquirer-command-prompt)<br>
<br>
Simple prompt with command history and dynamic autocomplete
[**inquirer-fuzzy-path**](https://github.com/adelsz/inquirer-fuzzy-path)<br>
Prompt for fuzzy file/directory selection.<br>
<br>
![inquirer-fuzzy-path](https://raw.githubusercontent.com/adelsz/inquirer-fuzzy-path/master/recording.gif)
[**inquirer-chalk-pipe**](https://github.com/LitoMore/inquirer-chalk-pipe)<br>
Prompt for input chalk-pipe style strings<br>
<br>
![inquirer-chalk-pipe](https://github.com/LitoMore/inquirer-chalk-pipe/raw/master/screenshot.gif)
[**inquirer-search-checkbox**](https://github.com/clinyong/inquirer-search-checkbox)<br>
Searchable Inquirer checkbox<br>
[**inquirer-prompt-suggest**](https://github.com/olistic/inquirer-prompt-suggest)<br>
Inquirer prompt for your less creative users.
![inquirer-prompt-suggest](https://user-images.githubusercontent.com/5600126/40391192-d4f3d6d0-5ded-11e8-932f-4b75b642c09e.gif)

View File

@ -29,7 +29,6 @@ class CheckboxPrompt extends Base {
}
this.pointer = 0;
this.firstRender = true;
// Make sure no default is set (so it won't be printed)
this.opt.default = null;
@ -87,7 +86,7 @@ class CheckboxPrompt extends Base {
var message = this.getQuestion();
var bottomContent = '';
if (this.firstRender) {
if (!this.spaceKeyPressed) {
message +=
'(Press ' +
chalk.cyan.bold('<space>') +
@ -166,6 +165,7 @@ class CheckboxPrompt extends Base {
}
onSpaceKey() {
this.spaceKeyPressed = true;
this.toggleChoice(this.pointer);
this.render();
}

View File

@ -37,11 +37,9 @@ class PasswordPrompt extends Base {
validation.success.forEach(this.onEnd.bind(this));
validation.error.forEach(this.onError.bind(this));
if (this.opt.mask) {
events.keypress
.pipe(takeUntil(validation.success))
.forEach(this.onKeypress.bind(this));
}
// Init
this.render();

View File

@ -67,6 +67,10 @@ class RawListPrompt extends Base {
events.keypress
.pipe(takeUntil(validation.success))
.forEach(this.onKeypress.bind(this));
events.normalizedUpKey.pipe(takeUntil(events.line)).forEach(this.onUpKey.bind(this));
events.normalizedDownKey
.pipe(takeUntil(events.line))
.forEach(this.onDownKey.bind(this));
// Init the prompt
this.render();
@ -146,6 +150,34 @@ class RawListPrompt extends Base {
this.render();
}
/**
* When user press up key
*/
onUpKey() {
this.onArrowKey('up');
}
/**
* When user press down key
*/
onDownKey() {
this.onArrowKey('down');
}
/**
* When user press up or down key
* @param {String} type Arrow type: up or down
*/
onArrowKey(type) {
var index = this.rl.line.length ? Number(this.rl.line) - 1 : 0;
index += type === 'up' ? -1 : 1;
this.rl.line = String(index + 1);
this.onKeypress();
}
}
/**

View File

@ -0,0 +1,14 @@
'use strict';
module.exports = options => {
options = Object.assign({
onlyFirst: false
}, options);
const pattern = [
'[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[a-zA-Z\\d]*)*)?\\u0007)',
'(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))'
].join('|');
return new RegExp(pattern, options.onlyFirst ? undefined : 'g');
};

View File

@ -0,0 +1,62 @@
{
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/chalk/ansi-regex/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Regular expression for matching ANSI escape codes",
"devDependencies": {
"ava": "^0.25.0",
"xo": "^0.23.0"
},
"engines": {
"node": ">=6"
},
"files": [
"index.js"
],
"homepage": "https://github.com/chalk/ansi-regex#readme",
"keywords": [
"ansi",
"styles",
"color",
"colour",
"colors",
"terminal",
"console",
"cli",
"string",
"tty",
"escape",
"formatting",
"rgb",
"256",
"shell",
"xterm",
"command-line",
"text",
"regex",
"regexp",
"re",
"match",
"test",
"find",
"pattern"
],
"license": "MIT",
"name": "ansi-regex",
"repository": {
"type": "git",
"url": "git+https://github.com/chalk/ansi-regex.git"
},
"scripts": {
"test": "xo && ava",
"view-supported": "node fixtures/view-codes.js"
},
"version": "4.0.0"
}

View File

@ -0,0 +1,65 @@
# ansi-regex [![Build Status](https://travis-ci.org/chalk/ansi-regex.svg?branch=master)](https://travis-ci.org/chalk/ansi-regex)
> Regular expression for matching [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code)
## Install
```
$ npm install ansi-regex
```
## Usage
```js
const ansiRegex = require('ansi-regex');
ansiRegex().test('\u001B[4mcake\u001B[0m');
//=> true
ansiRegex().test('cake');
//=> false
'\u001B[4mcake\u001B[0m'.match(ansiRegex());
//=> ['\u001B[4m', '\u001B[0m']
'\u001B[4mcake\u001B[0m'.match(ansiRegex({onlyFirst: true}));
//=> ['\u001B[4m']
```
## API
### ansiRegex([options])
Returns a regex for matching ANSI escape codes.
#### options
##### onlyFirst
Type: `boolean`<br>
Default: `false` *(Matches any ANSI escape codes in a string)*
Match only the first ANSI escape.
## FAQ
### Why do you test for codes not in the ECMA 48 standard?
Some of the codes we run as a test are codes that we acquired finding various lists of non-standard or manufacturer specific codes. We test for both standard and non-standard codes, as most of them follow the same or similar format and can be safely matched in strings without the risk of removing actual string content. There are a few non-standard control codes that do not follow the traditional format (i.e. they end in numbers) thus forcing us to exclude them from the test because we cannot reliably match them.
On the historical side, those ECMA standards were established in the early 90's whereas the VT100, for example, was designed in the mid/late 70's. At that point in time, control codes were still pretty ungoverned and engineers used them for a multitude of things, namely to activate hardware ports that may have been proprietary. Somewhere else you see a similar 'anarchy' of codes is in the x86 architecture for processors; there are a ton of "interrupts" that can mean different things on certain brands of processors, most of which have been phased out.
## Maintainers
- [Sindre Sorhus](https://github.com/sindresorhus)
- [Josh Junon](https://github.com/qix-)
## License
MIT

View File

@ -0,0 +1,4 @@
'use strict';
const ansiRegex = require('ansi-regex');
module.exports = input => typeof input === 'string' ? input.replace(ansiRegex(), '') : input;

View File

@ -0,0 +1,61 @@
{
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/chalk/strip-ansi/issues"
},
"bundleDependencies": false,
"dependencies": {
"ansi-regex": "^4.0.0"
},
"deprecated": false,
"description": "Strip ANSI escape codes",
"devDependencies": {
"ava": "^0.25.0",
"xo": "^0.23.0"
},
"engines": {
"node": ">=6"
},
"files": [
"index.js"
],
"homepage": "https://github.com/chalk/strip-ansi#readme",
"keywords": [
"strip",
"trim",
"remove",
"ansi",
"styles",
"color",
"colour",
"colors",
"terminal",
"console",
"string",
"tty",
"escape",
"formatting",
"rgb",
"256",
"shell",
"xterm",
"log",
"logging",
"command-line",
"text"
],
"license": "MIT",
"name": "strip-ansi",
"repository": {
"type": "git",
"url": "git+https://github.com/chalk/strip-ansi.git"
},
"scripts": {
"test": "xo && ava"
},
"version": "5.0.0"
}

View File

@ -0,0 +1,53 @@
# strip-ansi [![Build Status](https://travis-ci.org/chalk/strip-ansi.svg?branch=master)](https://travis-ci.org/chalk/strip-ansi)
> Strip [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code)
---
<div align="center">
<b>
<a href="https://tidelift.com/subscription/pkg/npm-strip-ansi?utm_source=npm-strip-ansi&utm_medium=referral&utm_campaign=readme">Get professional support for 'strip-ansi' with a Tidelift subscription</a>
</b>
<br>
<sub>
Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
</sub>
</div>
---
## Install
```
$ npm install strip-ansi
```
## Usage
```js
const stripAnsi = require('strip-ansi');
stripAnsi('\u001B[4mUnicorn\u001B[0m');
//=> 'Unicorn'
```
## Related
- [strip-ansi-cli](https://github.com/chalk/strip-ansi-cli) - CLI for this module
- [strip-ansi-stream](https://github.com/chalk/strip-ansi-stream) - Streaming version of this module
- [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes
- [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes
- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right
## Maintainers
- [Sindre Sorhus](https://github.com/sindresorhus)
- [Josh Junon](https://github.com/qix-)
## License
MIT

View File

@ -19,26 +19,26 @@
"run-async": "^2.2.0",
"rxjs": "^6.1.0",
"string-width": "^2.1.0",
"strip-ansi": "^4.0.0",
"strip-ansi": "^5.0.0",
"through": "^2.3.6"
},
"deprecated": false,
"description": "A collection of common interactive command line user interfaces.",
"devDependencies": {
"chai": "^4.0.1",
"chalk-pipe": "^1.2.0",
"chalk-pipe": "^2.0.0",
"cmdify": "^0.0.4",
"mocha": "^5.0.0",
"mockery": "^2.1.0",
"nsp": "^3.0.0",
"nyc": "^12.0.1",
"sinon": "^5.0.0"
"nyc": "^13.1.0",
"sinon": "^7.1.1"
},
"engines": {
"node": ">=6.0.0"
},
"files": [
"lib"
"lib",
"README.md"
],
"homepage": "https://github.com/SBoudrias/Inquirer.js#readme",
"keywords": [
@ -57,9 +57,10 @@
"url": "git+https://github.com/SBoudrias/Inquirer.js.git"
},
"scripts": {
"postpublish": "rm -f README.md",
"posttest": "nyc report --reporter=text-lcov > ../../coverage/nyc-report.lcov",
"prepublish": "nsp check",
"prepublishOnly": "cp ../../README.md .",
"test": "nyc mocha test/**/* -r ./test/before"
},
"version": "6.2.0"
"version": "6.2.1"
}

View File

@ -1,6 +0,0 @@
'use strict';
var path = require('path');
module.exports = function (str) {
return path.resolve(str) === path.resolve(process.cwd());
};

View File

@ -1,42 +0,0 @@
{
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "http://sindresorhus.com"
},
"bugs": {
"url": "https://github.com/sindresorhus/is-path-cwd/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Check if a path is CWD",
"devDependencies": {
"mocha": "*"
},
"engines": {
"node": ">=0.10.0"
},
"files": [
"index.js"
],
"homepage": "https://github.com/sindresorhus/is-path-cwd#readme",
"keywords": [
"path",
"cwd",
"pwd",
"check",
"filepath",
"file",
"folder"
],
"license": "MIT",
"name": "is-path-cwd",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/is-path-cwd.git"
},
"scripts": {
"test": "mocha"
},
"version": "1.0.0"
}

View File

@ -1,28 +0,0 @@
# is-path-cwd [![Build Status](https://travis-ci.org/sindresorhus/is-path-cwd.svg?branch=master)](https://travis-ci.org/sindresorhus/is-path-cwd)
> Check if a path is [CWD](http://en.wikipedia.org/wiki/Working_directory)
## Install
```sh
$ npm install --save is-path-cwd
```
## Usage
```js
var isPathCwd = require('is-path-cwd');
isPathCwd(process.cwd());
//=> true
isPathCwd('unicorn');
//=> false
```
## License
MIT © [Sindre Sorhus](http://sindresorhus.com)

Some files were not shown because too many files have changed in this diff Show More