build: update npm install command to use --legacy-peer-deps

This change modifies the build scripts to use --legacy-peer-deps flag when installing npm dependencies to resolve potential peer dependency conflicts during the build process. The change is applied to both bash (build.sh) and batch (build.bat) build scripts.
This commit is contained in:
Luiz Costa
2025-11-18 10:23:55 -03:00
parent 20129a1ac7
commit ac4f232e5e
787 changed files with 82341 additions and 121690 deletions
+14 -14
View File
@@ -9,26 +9,26 @@
//------------------------------------------------------------------------------
const Ajv = require("ajv"),
metaSchema = require("ajv/lib/refs/json-schema-draft-04.json");
metaSchema = require("ajv/lib/refs/json-schema-draft-04.json");
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
module.exports = (additionalOptions = {}) => {
const ajv = new Ajv({
meta: false,
useDefaults: true,
validateSchema: false,
missingRefs: "ignore",
verbose: true,
schemaId: "auto",
...additionalOptions,
});
const ajv = new Ajv({
meta: false,
useDefaults: true,
validateSchema: false,
missingRefs: "ignore",
verbose: true,
schemaId: "auto",
...additionalOptions
});
ajv.addMetaSchema(metaSchema);
// eslint-disable-next-line no-underscore-dangle -- Ajv's API
ajv._opts.defaultMeta = metaSchema.id;
ajv.addMetaSchema(metaSchema);
// eslint-disable-next-line no-underscore-dangle -- Ajv's API
ajv._opts.defaultMeta = metaSchema.id;
return ajv;
return ajv;
};
-21
View File
@@ -1,21 +0,0 @@
/**
* @fileoverview Assertion utilities equivalent to the Node.js node:asserts module.
* @author Josh Goldberg
*/
"use strict";
/**
* Throws an error if the input is not truthy.
* @param {unknown} value The input that is checked for being truthy.
* @param {string} message Message to throw if the input is not truthy.
* @returns {void}
* @throws {Error} When the condition is not truthy.
*/
function ok(value, message = "Assertion failed.") {
if (!value) {
throw new Error(message);
}
}
module.exports = ok;
+6 -7
View File
@@ -8,8 +8,7 @@
*/
"use strict";
const breakableTypePattern =
/^(?:(?:Do)?While|For(?:In|Of)?|Switch)Statement$/u;
const breakableTypePattern = /^(?:(?:Do)?While|For(?:In|Of)?|Switch)Statement$/u;
const lineBreakPattern = /\r\n|[\r\n\u2028\u2029]/u;
const shebangPattern = /^#!([^\r\n]+)/u;
@@ -19,12 +18,12 @@ const shebangPattern = /^#!([^\r\n]+)/u;
* @returns {RegExp} A global regular expression that matches line terminators
*/
function createGlobalLinebreakMatcher() {
return new RegExp(lineBreakPattern.source, "gu");
return new RegExp(lineBreakPattern.source, "gu");
}
module.exports = {
breakableTypePattern,
lineBreakPattern,
createGlobalLinebreakMatcher,
shebangPattern,
breakableTypePattern,
lineBreakPattern,
createGlobalLinebreakMatcher,
shebangPattern
};
+347
View File
@@ -0,0 +1,347 @@
/*
* STOP!!! DO NOT MODIFY.
*
* This file is part of the ongoing work to move the eslintrc-style config
* system into the @eslint/eslintrc package. This file needs to remain
* unchanged in order for this work to proceed.
*
* If you think you need to change this file, please contact @nzakas first.
*
* Thanks in advance for your cooperation.
*/
/**
* @fileoverview Validates configs.
* @author Brandon Mills
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const
util = require("util"),
configSchema = require("../../conf/config-schema"),
BuiltInRules = require("../rules"),
{
Legacy: {
ConfigOps,
environments: BuiltInEnvironments
}
} = require("@eslint/eslintrc"),
{ emitDeprecationWarning } = require("./deprecation-warnings");
const ajv = require("./ajv")();
const ruleValidators = new WeakMap();
const noop = Function.prototype;
//------------------------------------------------------------------------------
// Private
//------------------------------------------------------------------------------
let validateSchema;
const severityMap = {
error: 2,
warn: 1,
off: 0
};
/**
* Gets a complete options schema for a rule.
* @param {{create: Function, schema: (Array|null)}} rule A new-style rule object
* @returns {Object} JSON Schema for the rule's options.
*/
function getRuleOptionsSchema(rule) {
if (!rule) {
return null;
}
const schema = rule.schema || rule.meta && rule.meta.schema;
// Given a tuple of schemas, insert warning level at the beginning
if (Array.isArray(schema)) {
if (schema.length) {
return {
type: "array",
items: schema,
minItems: 0,
maxItems: schema.length
};
}
return {
type: "array",
minItems: 0,
maxItems: 0
};
}
// Given a full schema, leave it alone
return schema || null;
}
/**
* Validates a rule's severity and returns the severity value. Throws an error if the severity is invalid.
* @param {options} options The given options for the rule.
* @throws {Error} Wrong severity value.
* @returns {number|string} The rule's severity value
*/
function validateRuleSeverity(options) {
const severity = Array.isArray(options) ? options[0] : options;
const normSeverity = typeof severity === "string" ? severityMap[severity.toLowerCase()] : severity;
if (normSeverity === 0 || normSeverity === 1 || normSeverity === 2) {
return normSeverity;
}
throw new Error(`\tSeverity should be one of the following: 0 = off, 1 = warn, 2 = error (you passed '${util.inspect(severity).replace(/'/gu, "\"").replace(/\n/gu, "")}').\n`);
}
/**
* Validates the non-severity options passed to a rule, based on its schema.
* @param {{create: Function}} rule The rule to validate
* @param {Array} localOptions The options for the rule, excluding severity
* @throws {Error} Any rule validation errors.
* @returns {void}
*/
function validateRuleSchema(rule, localOptions) {
if (!ruleValidators.has(rule)) {
const schema = getRuleOptionsSchema(rule);
if (schema) {
ruleValidators.set(rule, ajv.compile(schema));
}
}
const validateRule = ruleValidators.get(rule);
if (validateRule) {
validateRule(localOptions);
if (validateRule.errors) {
throw new Error(validateRule.errors.map(
error => `\tValue ${JSON.stringify(error.data)} ${error.message}.\n`
).join(""));
}
}
}
/**
* Validates a rule's options against its schema.
* @param {{create: Function}|null} rule The rule that the config is being validated for
* @param {string} ruleId The rule's unique name.
* @param {Array|number} options The given options for the rule.
* @param {string|null} source The name of the configuration source to report in any errors. If null or undefined,
* no source is prepended to the message.
* @throws {Error} Upon any bad rule configuration.
* @returns {void}
*/
function validateRuleOptions(rule, ruleId, options, source = null) {
try {
const severity = validateRuleSeverity(options);
if (severity !== 0) {
validateRuleSchema(rule, Array.isArray(options) ? options.slice(1) : []);
}
} catch (err) {
const enhancedMessage = `Configuration for rule "${ruleId}" is invalid:\n${err.message}`;
if (typeof source === "string") {
throw new Error(`${source}:\n\t${enhancedMessage}`);
} else {
throw new Error(enhancedMessage);
}
}
}
/**
* Validates an environment object
* @param {Object} environment The environment config object to validate.
* @param {string} source The name of the configuration source to report in any errors.
* @param {(envId:string) => Object} [getAdditionalEnv] A map from strings to loaded environments.
* @returns {void}
*/
function validateEnvironment(
environment,
source,
getAdditionalEnv = noop
) {
// not having an environment is ok
if (!environment) {
return;
}
Object.keys(environment).forEach(id => {
const env = getAdditionalEnv(id) || BuiltInEnvironments.get(id) || null;
if (!env) {
const message = `${source}:\n\tEnvironment key "${id}" is unknown\n`;
throw new Error(message);
}
});
}
/**
* Validates a rules config object
* @param {Object} rulesConfig The rules config object to validate.
* @param {string} source The name of the configuration source to report in any errors.
* @param {(ruleId:string) => Object} getAdditionalRule A map from strings to loaded rules
* @returns {void}
*/
function validateRules(
rulesConfig,
source,
getAdditionalRule = noop
) {
if (!rulesConfig) {
return;
}
Object.keys(rulesConfig).forEach(id => {
const rule = getAdditionalRule(id) || BuiltInRules.get(id) || null;
validateRuleOptions(rule, id, rulesConfig[id], source);
});
}
/**
* Validates a `globals` section of a config file
* @param {Object} globalsConfig The `globals` section
* @param {string|null} source The name of the configuration source to report in the event of an error.
* @returns {void}
*/
function validateGlobals(globalsConfig, source = null) {
if (!globalsConfig) {
return;
}
Object.entries(globalsConfig)
.forEach(([configuredGlobal, configuredValue]) => {
try {
ConfigOps.normalizeConfigGlobal(configuredValue);
} catch (err) {
throw new Error(`ESLint configuration of global '${configuredGlobal}' in ${source} is invalid:\n${err.message}`);
}
});
}
/**
* Validate `processor` configuration.
* @param {string|undefined} processorName The processor name.
* @param {string} source The name of config file.
* @param {(id:string) => Processor} getProcessor The getter of defined processors.
* @throws {Error} For invalid processor configuration.
* @returns {void}
*/
function validateProcessor(processorName, source, getProcessor) {
if (processorName && !getProcessor(processorName)) {
throw new Error(`ESLint configuration of processor in '${source}' is invalid: '${processorName}' was not found.`);
}
}
/**
* Formats an array of schema validation errors.
* @param {Array} errors An array of error messages to format.
* @returns {string} Formatted error message
*/
function formatErrors(errors) {
return errors.map(error => {
if (error.keyword === "additionalProperties") {
const formattedPropertyPath = error.dataPath.length ? `${error.dataPath.slice(1)}.${error.params.additionalProperty}` : error.params.additionalProperty;
return `Unexpected top-level property "${formattedPropertyPath}"`;
}
if (error.keyword === "type") {
const formattedField = error.dataPath.slice(1);
const formattedExpectedType = Array.isArray(error.schema) ? error.schema.join("/") : error.schema;
const formattedValue = JSON.stringify(error.data);
return `Property "${formattedField}" is the wrong type (expected ${formattedExpectedType} but got \`${formattedValue}\`)`;
}
const field = error.dataPath[0] === "." ? error.dataPath.slice(1) : error.dataPath;
return `"${field}" ${error.message}. Value: ${JSON.stringify(error.data)}`;
}).map(message => `\t- ${message}.\n`).join("");
}
/**
* Validates the top level properties of the config object.
* @param {Object} config The config object to validate.
* @param {string} source The name of the configuration source to report in any errors.
* @throws {Error} For any config invalid per the schema.
* @returns {void}
*/
function validateConfigSchema(config, source = null) {
validateSchema = validateSchema || ajv.compile(configSchema);
if (!validateSchema(config)) {
throw new Error(`ESLint configuration in ${source} is invalid:\n${formatErrors(validateSchema.errors)}`);
}
if (Object.hasOwnProperty.call(config, "ecmaFeatures")) {
emitDeprecationWarning(source, "ESLINT_LEGACY_ECMAFEATURES");
}
}
/**
* Validates an entire config object.
* @param {Object} config The config object to validate.
* @param {string} source The name of the configuration source to report in any errors.
* @param {(ruleId:string) => Object} [getAdditionalRule] A map from strings to loaded rules.
* @param {(envId:string) => Object} [getAdditionalEnv] A map from strings to loaded envs.
* @returns {void}
*/
function validate(config, source, getAdditionalRule, getAdditionalEnv) {
validateConfigSchema(config, source);
validateRules(config.rules, source, getAdditionalRule);
validateEnvironment(config.env, source, getAdditionalEnv);
validateGlobals(config.globals, source);
for (const override of config.overrides || []) {
validateRules(override.rules, source, getAdditionalRule);
validateEnvironment(override.env, source, getAdditionalEnv);
validateGlobals(config.globals, source);
}
}
const validated = new WeakSet();
/**
* Validate config array object.
* @param {ConfigArray} configArray The config array to validate.
* @returns {void}
*/
function validateConfigArray(configArray) {
const getPluginEnv = Map.prototype.get.bind(configArray.pluginEnvironments);
const getPluginProcessor = Map.prototype.get.bind(configArray.pluginProcessors);
const getPluginRule = Map.prototype.get.bind(configArray.pluginRules);
// Validate.
for (const element of configArray) {
if (validated.has(element)) {
continue;
}
validated.add(element);
validateEnvironment(element.env, element.name, getPluginEnv);
validateGlobals(element.globals, element.name);
validateProcessor(element.processor, element.name, getPluginProcessor);
validateRules(element.rules, element.name, getPluginRule);
}
}
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
module.exports = {
getRuleOptionsSchema,
validate,
validateConfigArray,
validateConfigSchema,
validateRuleOptions
};
-62
View File
@@ -1,62 +0,0 @@
/**
* @fileoverview Applies default rule options
* @author JoshuaKGoldberg
*/
"use strict";
/**
* Check if the variable contains an object strictly rejecting arrays
* @param {unknown} value an object
* @returns {boolean} Whether value is an object
*/
function isObjectNotArray(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
/**
* Deeply merges second on top of first, creating a new {} object if needed.
* @param {T} first Base, default value.
* @param {U} second User-specified value.
* @returns {T | U | (T & U)} Merged equivalent of second on top of first.
*/
function deepMergeObjects(first, second) {
if (second === void 0) {
return first;
}
if (!isObjectNotArray(first) || !isObjectNotArray(second)) {
return second;
}
const result = { ...first, ...second };
for (const key of Object.keys(second)) {
if (Object.prototype.propertyIsEnumerable.call(first, key)) {
result[key] = deepMergeObjects(first[key], second[key]);
}
}
return result;
}
/**
* Deeply merges second on top of first, creating a new [] array if needed.
* @param {T[]} first Base, default values.
* @param {U[]} second User-specified values.
* @returns {(T | U | (T & U))[]} Merged equivalent of second on top of first.
*/
function deepMergeArrays(first, second) {
if (!first || !second) {
return second || first || [];
}
return [
...first.map((value, i) =>
deepMergeObjects(value, i < second.length ? second[i] : void 0),
),
...second.slice(first.length),
];
}
module.exports = { deepMergeArrays };
+58
View File
@@ -0,0 +1,58 @@
/**
* @fileoverview Provide the function that emits deprecation warnings.
* @author Toru Nagashima <http://github.com/mysticatea>
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const path = require("path");
//------------------------------------------------------------------------------
// Private
//------------------------------------------------------------------------------
// Definitions for deprecation warnings.
const deprecationWarningMessages = {
ESLINT_LEGACY_ECMAFEATURES:
"The 'ecmaFeatures' config file property is deprecated and has no effect."
};
const sourceFileErrorCache = new Set();
/**
* Emits a deprecation warning containing a given filepath. A new deprecation warning is emitted
* for each unique file path, but repeated invocations with the same file path have no effect.
* No warnings are emitted if the `--no-deprecation` or `--no-warnings` Node runtime flags are active.
* @param {string} source The name of the configuration source to report the warning for.
* @param {string} errorCode The warning message to show.
* @returns {void}
*/
function emitDeprecationWarning(source, errorCode) {
const cacheKey = JSON.stringify({ source, errorCode });
if (sourceFileErrorCache.has(cacheKey)) {
return;
}
sourceFileErrorCache.add(cacheKey);
const rel = path.relative(process.cwd(), source);
const message = deprecationWarningMessages[errorCode];
process.emitWarning(
`${message} (found in "${rel}")`,
"DeprecationWarning",
errorCode
);
}
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
module.exports = {
emitDeprecationWarning
};
+2 -3
View File
@@ -8,9 +8,8 @@
*/
"use strict";
const directivesPattern =
/^(eslint(?:-env|-enable|-disable(?:(?:-next)?-line)?)?|exported|globals?)(?:\s|$)/u;
const directivesPattern = /^(eslint(?:-env|-enable|-disable(?:(?:-next)?-line)?)?|exported|globals?)(?:\s|$)/u;
module.exports = {
directivesPattern,
directivesPattern
};
-108
View File
@@ -1,108 +0,0 @@
/**
* @fileoverview Shared flags for ESLint.
*/
"use strict";
//------------------------------------------------------------------------------
// Typedefs
//------------------------------------------------------------------------------
/**
* @typedef {Object} InactiveFlagData
* @property {string} description Flag description
* @property {string | null} [replacedBy] Can be either:
* - An active flag (string) that enables the same feature.
* - `null` if the feature is now enabled by default.
* - Omitted if the feature has been abandoned.
*/
//-----------------------------------------------------------------------------
// Exports
//-----------------------------------------------------------------------------
/**
* The set of flags that change ESLint behavior with a description.
* @type {Map<string, string>}
*/
const activeFlags = new Map([
["test_only", "Used only for testing."],
["test_only_2", "Used only for testing."],
[
"v10_config_lookup_from_file",
"Look up `eslint.config.js` from the file being linted.",
],
[
"unstable_native_nodejs_ts_config",
"Use native Node.js to load TypeScript configuration.",
],
]);
/**
* The set of flags that used to be active.
* @type {Map<string, InactiveFlagData>}
*/
const inactiveFlags = new Map([
[
"test_only_replaced",
{
description:
"Used only for testing flags that have been replaced by other flags.",
replacedBy: "test_only",
},
],
[
"test_only_enabled_by_default",
{
description:
"Used only for testing flags whose features have been enabled by default.",
replacedBy: null,
},
],
[
"test_only_abandoned",
{
description:
"Used only for testing flags whose features have been abandoned.",
},
],
[
"unstable_ts_config",
{
description: "Enable TypeScript configuration files.",
replacedBy: null,
},
],
[
"unstable_config_lookup_from_file",
{
description:
"Look up `eslint.config.js` from the file being linted.",
replacedBy: "v10_config_lookup_from_file",
},
],
]);
/**
* Creates a message that describes the reason the flag is inactive.
* @param {InactiveFlagData} inactiveFlagData Data for the inactive flag.
* @returns {string} Message describing the reason the flag is inactive.
*/
function getInactivityReasonMessage({ replacedBy }) {
if (typeof replacedBy === "undefined") {
return "This feature has been abandoned.";
}
if (typeof replacedBy === "string") {
return `This flag has been renamed '${replacedBy}' to reflect its stabilization. Please use '${replacedBy}' instead.`;
}
// null
return "This feature is now enabled by default.";
}
module.exports = {
activeFlags,
inactiveFlags,
getInactivityReasonMessage,
};
+16 -24
View File
@@ -9,30 +9,22 @@
/* c8 ignore next */
module.exports = {
/**
* Cover for console.info
* @param {...any} args The elements to log.
* @returns {void}
*/
info(...args) {
console.log(...args);
},
/**
* Cover for console.warn
* @param {...any} args The elements to log.
* @returns {void}
*/
warn(...args) {
console.warn(...args);
},
/**
* Cover for console.log
* @param {...any} args The elements to log.
* @returns {void}
*/
info(...args) {
console.log(...args);
},
/**
* Cover for console.error
* @param {...any} args The elements to log.
* @returns {void}
*/
error(...args) {
console.error(...args);
},
/**
* Cover for console.error
* @param {...any} args The elements to log.
* @returns {void}
*/
error(...args) {
console.error(...args);
}
};
-109
View File
@@ -1,109 +0,0 @@
/**
* @fileoverview Common helpers for naming of plugins, formatters and configs
*/
"use strict";
const NAMESPACE_REGEX = /^@.*\//u;
/**
* Brings package name to correct format based on prefix
* @param {string} name The name of the package.
* @param {string} prefix Can be either "eslint-plugin", "eslint-config" or "eslint-formatter"
* @returns {string} Normalized name of the package
* @private
*/
function normalizePackageName(name, prefix) {
let normalizedName = name;
/**
* On Windows, name can come in with Windows slashes instead of Unix slashes.
* Normalize to Unix first to avoid errors later on.
* https://github.com/eslint/eslint/issues/5644
*/
if (normalizedName.includes("\\")) {
normalizedName = normalizedName.replace(/\\/gu, "/");
}
if (normalizedName.charAt(0) === "@") {
/**
* it's a scoped package
* package name is the prefix, or just a username
*/
const scopedPackageShortcutRegex = new RegExp(
`^(@[^/]+)(?:/(?:${prefix})?)?$`,
"u",
),
scopedPackageNameRegex = new RegExp(`^${prefix}(-|$)`, "u");
if (scopedPackageShortcutRegex.test(normalizedName)) {
normalizedName = normalizedName.replace(
scopedPackageShortcutRegex,
`$1/${prefix}`,
);
} else if (!scopedPackageNameRegex.test(normalizedName.split("/")[1])) {
/**
* for scoped packages, insert the prefix after the first / unless
* the path is already @scope/eslint or @scope/eslint-xxx-yyy
*/
normalizedName = normalizedName.replace(
/^@([^/]+)\/(.*)$/u,
`@$1/${prefix}-$2`,
);
}
} else if (!normalizedName.startsWith(`${prefix}-`)) {
normalizedName = `${prefix}-${normalizedName}`;
}
return normalizedName;
}
/**
* Removes the prefix from a fullname.
* @param {string} fullname The term which may have the prefix.
* @param {string} prefix The prefix to remove.
* @returns {string} The term without prefix.
*/
function getShorthandName(fullname, prefix) {
if (fullname[0] === "@") {
let matchResult = new RegExp(`^(@[^/]+)/${prefix}$`, "u").exec(
fullname,
);
if (matchResult) {
return matchResult[1];
}
matchResult = new RegExp(`^(@[^/]+)/${prefix}-(.+)$`, "u").exec(
fullname,
);
if (matchResult) {
return `${matchResult[1]}/${matchResult[2]}`;
}
} else if (fullname.startsWith(`${prefix}-`)) {
return fullname.slice(prefix.length + 1);
}
return fullname;
}
/**
* Gets the scope (namespace) of a term.
* @param {string} term The term which may have the namespace.
* @returns {string} The namespace of the term if it has one.
*/
function getNamespaceFromTerm(term) {
const match = term.match(NAMESPACE_REGEX);
return match ? match[0] : "";
}
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
module.exports = {
normalizePackageName,
getShorthandName,
getNamespaceFromTerm,
};
-63
View File
@@ -1,63 +0,0 @@
/**
* @fileoverview Utilities to operate on option objects.
* @author Josh Goldberg
*/
"use strict";
/**
* Determines whether any of input's properties are different
* from values that already exist in original.
* @template T
* @param {Partial<T>} input New value.
* @param {T} original Original value.
* @returns {boolean} Whether input includes an explicit difference.
*/
function containsDifferentProperty(input, original) {
if (input === original) {
return false;
}
if (
typeof input !== typeof original ||
Array.isArray(input) !== Array.isArray(original)
) {
return true;
}
if (Array.isArray(input)) {
return (
input.length !== original.length ||
input.some((value, i) =>
containsDifferentProperty(value, original[i]),
)
);
}
if (typeof input === "object") {
if (input === null || original === null) {
return true;
}
const inputKeys = Object.keys(input);
const originalKeys = Object.keys(original);
return (
inputKeys.length !== originalKeys.length ||
inputKeys.some(
inputKey =>
!Object.hasOwn(original, inputKey) ||
containsDifferentProperty(
input[inputKey],
original[inputKey],
),
)
);
}
return true;
}
module.exports = {
containsDifferentProperty,
};
+40 -18
View File
@@ -1,3 +1,15 @@
/*
* STOP!!! DO NOT MODIFY.
*
* This file is part of the ongoing work to move the eslintrc-style config
* system into the @eslint/eslintrc package. This file needs to remain
* unchanged in order for this work to proceed.
*
* If you think you need to change this file, please contact @nzakas first.
*
* Thanks in advance for your cooperation.
*/
/**
* Utility for resolving a module relative to another module
* @author Teddy Katz
@@ -5,24 +17,34 @@
"use strict";
const Module = require("node:module");
const { createRequire } = require("module");
/*
* `Module.createRequire` is added in v12.2.0. It supports URL as well.
* We only support the case where the argument is a filepath, not a URL.
*/
const createRequire = Module.createRequire;
module.exports = {
/**
* Resolves a Node module relative to another module
* @param {string} moduleName The name of a Node module, or a path to a Node module.
* @param {string} relativeToPath An absolute path indicating the module that `moduleName` should be resolved relative to. This must be
* a file rather than a directory, but the file need not actually exist.
* @returns {string} The absolute path that would result from calling `require.resolve(moduleName)` in a file located at `relativeToPath`
* @throws {Error} When the module cannot be resolved.
*/
function resolve(moduleName, relativeToPath) {
return createRequire(relativeToPath).resolve(moduleName);
}
/**
* Resolves a Node module relative to another module
* @param {string} moduleName The name of a Node module, or a path to a Node module.
* @param {string} relativeToPath An absolute path indicating the module that `moduleName` should be resolved relative to. This must be
* a file rather than a directory, but the file need not actually exist.
* @throws {Error} Any error from `module.createRequire` or its `resolve`.
* @returns {string} The absolute path that would result from calling `require.resolve(moduleName)` in a file located at `relativeToPath`
*/
resolve(moduleName, relativeToPath) {
try {
return createRequire(relativeToPath).resolve(moduleName);
} catch (error) {
exports.resolve = resolve;
// This `if` block is for older Node.js than 12.0.0. We can remove this block in the future.
if (
typeof error === "object" &&
error !== null &&
error.code === "MODULE_NOT_FOUND" &&
!error.requireStack &&
error.message.includes(moduleName)
) {
error.message += `\nRequire stack:\n- ${relativeToPath}`;
}
throw error;
}
}
};
+108 -118
View File
@@ -9,9 +9,9 @@
// Requirements
//------------------------------------------------------------------------------
const path = require("node:path");
const path = require("path");
const spawn = require("cross-spawn");
const os = require("node:os");
const os = require("os");
const log = require("../shared/logging");
const packageJson = require("../../package.json");
@@ -24,138 +24,129 @@ const packageJson = require("../../package.json");
* @returns {string} A string that contains execution environment information.
*/
function environment() {
const cache = new Map();
const cache = new Map();
/**
* Checks if a path is a child of a directory.
* @param {string} parentPath The parent path to check.
* @param {string} childPath The path to check.
* @returns {boolean} Whether or not the given path is a child of a directory.
*/
function isChildOfDirectory(parentPath, childPath) {
return !path.relative(parentPath, childPath).startsWith("..");
}
/**
* Checks if a path is a child of a directory.
* @param {string} parentPath The parent path to check.
* @param {string} childPath The path to check.
* @returns {boolean} Whether or not the given path is a child of a directory.
*/
function isChildOfDirectory(parentPath, childPath) {
return !path.relative(parentPath, childPath).startsWith("..");
}
/**
* Synchronously executes a shell command and formats the result.
* @param {string} cmd The command to execute.
* @param {Array} args The arguments to be executed with the command.
* @throws {Error} As may be collected by `cross-spawn.sync`.
* @returns {string} The version returned by the command.
*/
function execCommand(cmd, args) {
const key = [cmd, ...args].join(" ");
/**
* Synchronously executes a shell command and formats the result.
* @param {string} cmd The command to execute.
* @param {Array} args The arguments to be executed with the command.
* @throws {Error} As may be collected by `cross-spawn.sync`.
* @returns {string} The version returned by the command.
*/
function execCommand(cmd, args) {
const key = [cmd, ...args].join(" ");
if (cache.has(key)) {
return cache.get(key);
}
if (cache.has(key)) {
return cache.get(key);
}
const process = spawn.sync(cmd, args, { encoding: "utf8" });
const process = spawn.sync(cmd, args, { encoding: "utf8" });
if (process.error) {
throw process.error;
}
if (process.error) {
throw process.error;
}
const result = process.stdout.trim();
const result = process.stdout.trim();
cache.set(key, result);
return result;
}
cache.set(key, result);
return result;
}
/**
* Normalizes a version number.
* @param {string} versionStr The string to normalize.
* @returns {string} The normalized version number.
*/
function normalizeVersionStr(versionStr) {
return versionStr.startsWith("v") ? versionStr : `v${versionStr}`;
}
/**
* Normalizes a version number.
* @param {string} versionStr The string to normalize.
* @returns {string} The normalized version number.
*/
function normalizeVersionStr(versionStr) {
return versionStr.startsWith("v") ? versionStr : `v${versionStr}`;
}
/**
* Gets bin version.
* @param {string} bin The bin to check.
* @throws {Error} As may be collected by `cross-spawn.sync`.
* @returns {string} The normalized version returned by the command.
*/
function getBinVersion(bin) {
const binArgs = ["--version"];
/**
* Gets bin version.
* @param {string} bin The bin to check.
* @throws {Error} As may be collected by `cross-spawn.sync`.
* @returns {string} The normalized version returned by the command.
*/
function getBinVersion(bin) {
const binArgs = ["--version"];
try {
return normalizeVersionStr(execCommand(bin, binArgs));
} catch (e) {
log.error(
`Error finding ${bin} version running the command \`${bin} ${binArgs.join(" ")}\``,
);
throw e;
}
}
try {
return normalizeVersionStr(execCommand(bin, binArgs));
} catch (e) {
log.error(`Error finding ${bin} version running the command \`${bin} ${binArgs.join(" ")}\``);
throw e;
}
}
/**
* Gets installed npm package version.
* @param {string} pkg The package to check.
* @param {boolean} global Whether to check globally or not.
* @throws {Error} As may be collected by `cross-spawn.sync`.
* @returns {string} The normalized version returned by the command.
*/
function getNpmPackageVersion(pkg, { global = false } = {}) {
const npmBinArgs = ["bin", "-g"];
const npmLsArgs = ["ls", "--depth=0", "--json", pkg];
/**
* Gets installed npm package version.
* @param {string} pkg The package to check.
* @param {boolean} global Whether to check globally or not.
* @throws {Error} As may be collected by `cross-spawn.sync`.
* @returns {string} The normalized version returned by the command.
*/
function getNpmPackageVersion(pkg, { global = false } = {}) {
const npmBinArgs = ["bin", "-g"];
const npmLsArgs = ["ls", "--depth=0", "--json", pkg];
if (global) {
npmLsArgs.push("-g");
}
if (global) {
npmLsArgs.push("-g");
}
try {
const parsedStdout = JSON.parse(execCommand("npm", npmLsArgs));
try {
const parsedStdout = JSON.parse(execCommand("npm", npmLsArgs));
/*
* Checking globally returns an empty JSON object, while local checks
* include the name and version of the local project.
*/
if (
Object.keys(parsedStdout).length === 0 ||
!(parsedStdout.dependencies && parsedStdout.dependencies.eslint)
) {
return "Not found";
}
/*
* Checking globally returns an empty JSON object, while local checks
* include the name and version of the local project.
*/
if (Object.keys(parsedStdout).length === 0 || !(parsedStdout.dependencies && parsedStdout.dependencies.eslint)) {
return "Not found";
}
const [, processBinPath] = process.argv;
let npmBinPath;
const [, processBinPath] = process.argv;
let npmBinPath;
try {
npmBinPath = execCommand("npm", npmBinArgs);
} catch (e) {
log.error(
`Error finding npm binary path when running command \`npm ${npmBinArgs.join(" ")}\``,
);
throw e;
}
try {
npmBinPath = execCommand("npm", npmBinArgs);
} catch (e) {
log.error(`Error finding npm binary path when running command \`npm ${npmBinArgs.join(" ")}\``);
throw e;
}
const isGlobal = isChildOfDirectory(npmBinPath, processBinPath);
let pkgVersion = parsedStdout.dependencies.eslint.version;
const isGlobal = isChildOfDirectory(npmBinPath, processBinPath);
let pkgVersion = parsedStdout.dependencies.eslint.version;
if ((global && isGlobal) || (!global && !isGlobal)) {
pkgVersion += " (Currently used)";
}
if ((global && isGlobal) || (!global && !isGlobal)) {
pkgVersion += " (Currently used)";
}
return normalizeVersionStr(pkgVersion);
} catch (e) {
log.error(
`Error finding ${pkg} version running the command \`npm ${npmLsArgs.join(" ")}\``,
);
throw e;
}
}
return normalizeVersionStr(pkgVersion);
} catch (e) {
log.error(`Error finding ${pkg} version running the command \`npm ${npmLsArgs.join(" ")}\``);
throw e;
}
}
return [
"Environment Info:",
"",
`Node version: ${process.version}`,
`npm version: ${getBinVersion("npm")}`,
`Local ESLint version: ${getNpmPackageVersion("eslint", { global: false })}`,
`Global ESLint version: ${getNpmPackageVersion("eslint", { global: true })}`,
`Operating System: ${os.platform()} ${os.release()}`,
].join("\n");
return [
"Environment Info:",
"",
`Node version: ${getBinVersion("node")}`,
`npm version: ${getBinVersion("npm")}`,
`Local ESLint version: ${getNpmPackageVersion("eslint", { global: false })}`,
`Global ESLint version: ${getNpmPackageVersion("eslint", { global: true })}`,
`Operating System: ${os.platform()} ${os.release()}`
].join("\n");
}
/**
@@ -163,7 +154,7 @@ function environment() {
* @returns {string} The version from the currently executing ESLint's package.json.
*/
function version() {
return `v${packageJson.version}`;
return `v${packageJson.version}`;
}
//------------------------------------------------------------------------------
@@ -171,7 +162,6 @@ function version() {
//------------------------------------------------------------------------------
module.exports = {
__esModule: true, // Indicate intent for imports, remove ambiguity for Knip (see: https://github.com/eslint/eslint/pull/18005#discussion_r1484422616)
environment,
version,
environment,
version
};
-78
View File
@@ -1,78 +0,0 @@
/**
* @fileoverview Serialization utils.
* @author Bryan Mishkin
*/
"use strict";
/**
* Check if a value is a primitive or plain object created by the Object constructor.
* @param {any} val the value to check
* @returns {boolean} true if so
* @private
*/
function isSerializablePrimitiveOrPlainObject(val) {
return (
val === null ||
typeof val === "string" ||
typeof val === "boolean" ||
typeof val === "number" ||
(typeof val === "object" && val.constructor === Object) ||
Array.isArray(val)
);
}
/**
* Check if a value is serializable.
* Functions or objects like RegExp cannot be serialized by JSON.stringify().
* Inspired by: https://stackoverflow.com/questions/30579940/reliable-way-to-check-if-objects-is-serializable-in-javascript
* @param {any} val The value
* @param {Set<Object>} seenObjects Objects already seen in this path from the root object.
* @returns {boolean} `true` if the value is serializable
*/
function isSerializable(val, seenObjects = new Set()) {
if (!isSerializablePrimitiveOrPlainObject(val)) {
return false;
}
if (typeof val === "object" && val !== null) {
if (seenObjects.has(val)) {
/*
* Since this is a depth-first traversal, encountering
* the same object again means there is a circular reference.
* Objects with circular references are not serializable.
*/
return false;
}
for (const property in val) {
if (Object.hasOwn(val, property)) {
if (!isSerializablePrimitiveOrPlainObject(val[property])) {
return false;
}
if (
typeof val[property] === "object" &&
val[property] !== null
) {
if (
/*
* We're creating a new Set of seen objects because we want to
* ensure that `val` doesn't appear again in this path, but it can appear
* in other paths. This allows for reusing objects in the graph, as long as
* there are no cycles.
*/
!isSerializable(
val[property],
new Set([...seenObjects, val]),
)
) {
return false;
}
}
}
}
}
return true;
}
module.exports = {
isSerializable,
};
+22 -22
View File
@@ -12,16 +12,16 @@
* @returns {string} severity string
*/
function normalizeSeverityToString(severity) {
if ([2, "2", "error"].includes(severity)) {
return "error";
}
if ([1, "1", "warn"].includes(severity)) {
return "warn";
}
if ([0, "0", "off"].includes(severity)) {
return "off";
}
throw new Error(`Invalid severity value: ${severity}`);
if ([2, "2", "error"].includes(severity)) {
return "error";
}
if ([1, "1", "warn"].includes(severity)) {
return "warn";
}
if ([0, "0", "off"].includes(severity)) {
return "off";
}
throw new Error(`Invalid severity value: ${severity}`);
}
/**
@@ -31,19 +31,19 @@ function normalizeSeverityToString(severity) {
* @returns {number} severity number
*/
function normalizeSeverityToNumber(severity) {
if ([2, "2", "error"].includes(severity)) {
return 2;
}
if ([1, "1", "warn"].includes(severity)) {
return 1;
}
if ([0, "0", "off"].includes(severity)) {
return 0;
}
throw new Error(`Invalid severity value: ${severity}`);
if ([2, "2", "error"].includes(severity)) {
return 2;
}
if ([1, "1", "warn"].includes(severity)) {
return 1;
}
if ([0, "0", "off"].includes(severity)) {
return 0;
}
throw new Error(`Invalid severity value: ${severity}`);
}
module.exports = {
normalizeSeverityToString,
normalizeSeverityToNumber,
normalizeSeverityToString,
normalizeSeverityToNumber
};
-30
View File
@@ -1,30 +0,0 @@
/**
* @fileoverview Provides helper functions to start/stop the time measurements
* that are provided by the ESLint 'stats' option.
* @author Mara Kiefer <http://github.com/mnkiefer>
*/
"use strict";
/**
* Start time measurement
* @returns {[number, number]} t variable for tracking time
*/
function startTime() {
return process.hrtime();
}
/**
* End time measurement
* @param {[number, number]} t Variable for tracking time
* @returns {number} The measured time in milliseconds
*/
function endTime(t) {
const time = process.hrtime(t);
return time[0] * 1e3 + time[1] / 1e6;
}
module.exports = {
startTime,
endTime,
};
+21 -19
View File
@@ -5,6 +5,12 @@
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const Graphemer = require("graphemer").default;
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
@@ -12,8 +18,8 @@
// eslint-disable-next-line no-control-regex -- intentionally including control characters
const ASCII_REGEX = /^[\u0000-\u007f]*$/u;
/** @type {Intl.Segmenter | undefined} */
let segmenter;
/** @type {Graphemer | undefined} */
let splitter;
//------------------------------------------------------------------------------
// Public Interface
@@ -25,10 +31,10 @@ let segmenter;
* @returns {string} The converted string
*/
function upperCaseFirst(string) {
if (string.length <= 1) {
return string.toUpperCase();
}
return string[0].toUpperCase() + string.slice(1);
if (string.length <= 1) {
return string.toUpperCase();
}
return string[0].toUpperCase() + string.slice(1);
}
/**
@@ -37,22 +43,18 @@ function upperCaseFirst(string) {
* @returns {number} The number of graphemes in `value`.
*/
function getGraphemeCount(value) {
if (ASCII_REGEX.test(value)) {
return value.length;
}
if (ASCII_REGEX.test(value)) {
return value.length;
}
segmenter ??= new Intl.Segmenter("en-US"); // en-US locale should be supported everywhere
let graphemeCount = 0;
if (!splitter) {
splitter = new Graphemer();
}
// eslint-disable-next-line no-unused-vars -- for-of needs a variable
for (const unused of segmenter.segment(value)) {
graphemeCount++;
}
return graphemeCount;
return splitter.countGraphemes(value);
}
module.exports = {
upperCaseFirst,
getGraphemeCount,
upperCaseFirst,
getGraphemeCount
};
-68
View File
@@ -1,68 +0,0 @@
/**
* @fileoverview Optimized version of the `text-table` npm module to improve performance by replacing inefficient regex-based
* whitespace trimming with a modern built-in method.
*
* This modification addresses a performance issue reported in https://github.com/eslint/eslint/issues/18709
*
* The `text-table` module is published under the MIT License. For the original source, refer to:
* https://www.npmjs.com/package/text-table.
*/
/*
*
* This software is released under the MIT license:
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
"use strict";
module.exports = function (rows_, opts) {
const hsep = " ";
const align = opts.align;
const stringLength = opts.stringLength;
const sizes = rows_.reduce((acc, row) => {
row.forEach((c, ix) => {
const n = stringLength(c);
if (!acc[ix] || n > acc[ix]) {
acc[ix] = n;
}
});
return acc;
}, []);
return rows_
.map(row =>
row
.map((c, ix) => {
const n = sizes[ix] - stringLength(c) || 0;
const s = Array(Math.max(n + 1, 1)).join(" ");
if (align[ix] === "r") {
return s + c;
}
return c + s;
})
.join(hsep)
.trimEnd(),
)
.join("\n");
};
-281
View File
@@ -1,281 +0,0 @@
/**
* @fileoverview Translates CLI options into ESLint constructor options.
* @author Nicholas C. Zakas
* @author Francesco Trotta
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const { normalizeSeverityToString } = require("./severity");
const { getShorthandName, normalizePackageName } = require("./naming");
const { ModuleImporter } = require("@humanwhocodes/module-importer");
//------------------------------------------------------------------------------
// Types
//------------------------------------------------------------------------------
/** @typedef {import("../types").ESLint.Options} ESLintOptions */
/** @typedef {import("../types").ESLint.LegacyOptions} LegacyESLintOptions */
/** @typedef {import("../types").Linter.LintMessage} LintMessage */
/** @typedef {import("../options").ParsedCLIOptions} ParsedCLIOptions */
/** @typedef {import("../types").ESLint.Plugin} Plugin */
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* Loads plugins with the specified names.
* @param {{ "import": (name: string) => Promise<any> }} importer An object with an `import` method called once for each plugin.
* @param {string[]} pluginNames The names of the plugins to be loaded, with or without the "eslint-plugin-" prefix.
* @returns {Promise<Record<string, Plugin>>} A mapping of plugin short names to implementations.
*/
async function loadPlugins(importer, pluginNames) {
const plugins = {};
await Promise.all(
pluginNames.map(async pluginName => {
const longName = normalizePackageName(pluginName, "eslint-plugin");
const module = await importer.import(longName);
if (!("default" in module)) {
throw new Error(
`"${longName}" cannot be used with the \`--plugin\` option because its default module does not provide a \`default\` export`,
);
}
const shortName = getShorthandName(pluginName, "eslint-plugin");
plugins[shortName] = module.default;
}),
);
return plugins;
}
/**
* Predicate function for whether or not to apply fixes in quiet mode.
* If a message is a warning, do not apply a fix.
* @param {LintMessage} message The lint result.
* @returns {boolean} True if the lint message is an error (and thus should be
* autofixed), false otherwise.
*/
function quietFixPredicate(message) {
return message.severity === 2;
}
/**
* Predicate function for whether or not to run a rule in quiet mode.
* If a rule is set to warning, do not run it.
* @param {{ ruleId: string; severity: number; }} rule The rule id and severity.
* @returns {boolean} True if the lint rule should run, false otherwise.
*/
function quietRuleFilter(rule) {
return rule.severity === 2;
}
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
/**
* Translates the CLI options into the options expected by the ESLint constructor.
* @param {ParsedCLIOptions} cliOptions The CLI options to translate.
* @param {"flat"|"eslintrc"} [configType="eslintrc"] The format of the config to generate.
* @returns {Promise<ESLintOptions | LegacyESLintOptions>} The options object for the ESLint constructor.
*/
async function translateOptions(
{
cache,
cacheFile,
cacheLocation,
cacheStrategy,
concurrency,
config,
configLookup,
env,
errorOnUnmatchedPattern,
eslintrc,
ext,
fix,
fixDryRun,
fixType,
flag,
global,
ignore,
ignorePath,
ignorePattern,
inlineConfig,
parser,
parserOptions,
plugin,
quiet,
reportUnusedDisableDirectives,
reportUnusedDisableDirectivesSeverity,
reportUnusedInlineConfigs,
resolvePluginsRelativeTo,
rule,
rulesdir,
stats,
warnIgnored,
passOnNoPatterns,
maxWarnings,
},
configType,
) {
let overrideConfig, overrideConfigFile;
const importer = new ModuleImporter();
if (configType === "flat") {
overrideConfigFile =
typeof config === "string" ? config : !configLookup;
if (overrideConfigFile === false) {
overrideConfigFile = void 0;
}
const languageOptions = {};
if (global) {
languageOptions.globals = global.reduce((obj, name) => {
if (name.endsWith(":true")) {
obj[name.slice(0, -5)] = "writable";
} else {
obj[name] = "readonly";
}
return obj;
}, {});
}
if (parserOptions) {
languageOptions.parserOptions = parserOptions;
}
if (parser) {
languageOptions.parser = await importer.import(parser);
}
overrideConfig = [
{
...(Object.keys(languageOptions).length > 0
? { languageOptions }
: {}),
rules: rule ? rule : {},
},
];
if (
reportUnusedDisableDirectives ||
reportUnusedDisableDirectivesSeverity !== void 0
) {
overrideConfig[0].linterOptions = {
reportUnusedDisableDirectives: reportUnusedDisableDirectives
? "error"
: normalizeSeverityToString(
reportUnusedDisableDirectivesSeverity,
),
};
}
if (reportUnusedInlineConfigs !== void 0) {
overrideConfig[0].linterOptions = {
...overrideConfig[0].linterOptions,
reportUnusedInlineConfigs: normalizeSeverityToString(
reportUnusedInlineConfigs,
),
};
}
if (plugin) {
overrideConfig[0].plugins = await loadPlugins(importer, plugin);
}
if (ext) {
overrideConfig.push({
files: ext.map(
extension =>
`**/*${extension.startsWith(".") ? "" : "."}${extension}`,
),
});
}
} else {
overrideConfigFile = config;
overrideConfig = {
env:
env &&
env.reduce((obj, name) => {
obj[name] = true;
return obj;
}, {}),
globals:
global &&
global.reduce((obj, name) => {
if (name.endsWith(":true")) {
obj[name.slice(0, -5)] = "writable";
} else {
obj[name] = "readonly";
}
return obj;
}, {}),
ignorePatterns: ignorePattern,
parser,
parserOptions,
plugins: plugin,
rules: rule,
};
}
const options = {
allowInlineConfig: inlineConfig,
cache,
cacheLocation: cacheLocation || cacheFile,
cacheStrategy,
errorOnUnmatchedPattern,
fix: (fix || fixDryRun) && (quiet ? quietFixPredicate : true),
fixTypes: fixType,
ignore,
overrideConfig,
overrideConfigFile,
passOnNoPatterns,
};
if (configType === "flat") {
options.concurrency = concurrency;
options.flags = flag;
options.ignorePatterns = ignorePattern;
options.stats = stats;
options.warnIgnored = warnIgnored;
/*
* For performance reasons rules not marked as 'error' are filtered out in quiet mode. As maxWarnings
* requires rules set to 'warn' to be run, we only filter out 'warn' rules if maxWarnings is not specified.
*/
options.ruleFilter =
quiet && maxWarnings === -1 ? quietRuleFilter : () => true;
} else {
options.resolvePluginsRelativeTo = resolvePluginsRelativeTo;
options.rulePaths = rulesdir;
options.useEslintrc = eslintrc;
options.extensions = ext;
options.ignorePath = ignorePath;
if (
reportUnusedDisableDirectives ||
reportUnusedDisableDirectivesSeverity !== void 0
) {
options.reportUnusedDisableDirectives =
reportUnusedDisableDirectives
? "error"
: normalizeSeverityToString(
reportUnusedDisableDirectivesSeverity,
);
}
}
return options;
}
module.exports = translateOptions;
+129 -136
View File
@@ -21,7 +21,8 @@ const debug = require("debug")("eslint:traverser");
* @returns {void}
*/
function noop() {
// do nothing.
// do nothing.
}
/**
@@ -30,7 +31,7 @@ function noop() {
* @returns {boolean} `true` if the value is an ASTNode.
*/
function isNode(x) {
return x !== null && typeof x === "object" && typeof x.type === "string";
return x !== null && typeof x === "object" && typeof x.type === "string";
}
/**
@@ -40,163 +41,155 @@ function isNode(x) {
* @returns {string[]} The visitor keys of the node.
*/
function getVisitorKeys(visitorKeys, node) {
let keys = visitorKeys[node.type];
let keys = visitorKeys[node.type];
if (!keys) {
keys = vk.getKeys(node);
debug(
'Unknown node type "%s": Estimated visitor keys %j',
node.type,
keys,
);
}
if (!keys) {
keys = vk.getKeys(node);
debug("Unknown node type \"%s\": Estimated visitor keys %j", node.type, keys);
}
return keys;
return keys;
}
/**
* The traverser class to traverse AST trees.
*/
class Traverser {
constructor() {
this._current = null;
this._parents = [];
this._skipped = false;
this._broken = false;
this._visitorKeys = null;
this._enter = null;
this._leave = null;
}
constructor() {
this._current = null;
this._parents = [];
this._skipped = false;
this._broken = false;
this._visitorKeys = null;
this._enter = null;
this._leave = null;
}
/**
* Gives current node.
* @returns {ASTNode} The current node.
*/
current() {
return this._current;
}
/**
* Gives current node.
* @returns {ASTNode} The current node.
*/
current() {
return this._current;
}
/**
* Gives a copy of the ancestor nodes.
* @returns {ASTNode[]} The ancestor nodes.
*/
parents() {
return this._parents.slice(0);
}
/**
* Gives a copy of the ancestor nodes.
* @returns {ASTNode[]} The ancestor nodes.
*/
parents() {
return this._parents.slice(0);
}
/**
* Break the current traversal.
* @returns {void}
*/
break() {
this._broken = true;
}
/**
* Break the current traversal.
* @returns {void}
*/
break() {
this._broken = true;
}
/**
* Skip child nodes for the current traversal.
* @returns {void}
*/
skip() {
this._skipped = true;
}
/**
* Skip child nodes for the current traversal.
* @returns {void}
*/
skip() {
this._skipped = true;
}
/**
* Traverse the given AST tree.
* @param {ASTNode} node The root node to traverse.
* @param {Object} options The option object.
* @param {Object} [options.visitorKeys=DEFAULT_VISITOR_KEYS] The keys of each node types to traverse child nodes. Default is `./default-visitor-keys.json`.
* @param {Function} [options.enter=noop] The callback function which is called on entering each node.
* @param {Function} [options.leave=noop] The callback function which is called on leaving each node.
* @returns {void}
*/
traverse(node, options) {
this._current = null;
this._parents = [];
this._skipped = false;
this._broken = false;
this._visitorKeys = options.visitorKeys || vk.KEYS;
this._enter = options.enter || noop;
this._leave = options.leave || noop;
this._traverse(node, null);
}
/**
* Traverse the given AST tree.
* @param {ASTNode} node The root node to traverse.
* @param {Object} options The option object.
* @param {Object} [options.visitorKeys=DEFAULT_VISITOR_KEYS] The keys of each node types to traverse child nodes. Default is `./default-visitor-keys.json`.
* @param {Function} [options.enter=noop] The callback function which is called on entering each node.
* @param {Function} [options.leave=noop] The callback function which is called on leaving each node.
* @returns {void}
*/
traverse(node, options) {
this._current = null;
this._parents = [];
this._skipped = false;
this._broken = false;
this._visitorKeys = options.visitorKeys || vk.KEYS;
this._enter = options.enter || noop;
this._leave = options.leave || noop;
this._traverse(node, null);
}
/**
* Traverse the given AST tree recursively.
* @param {ASTNode} node The current node.
* @param {ASTNode|null} parent The parent node.
* @returns {void}
* @private
*/
_traverse(node, parent) {
if (!isNode(node)) {
return;
}
/**
* Traverse the given AST tree recursively.
* @param {ASTNode} node The current node.
* @param {ASTNode|null} parent The parent node.
* @returns {void}
* @private
*/
_traverse(node, parent) {
if (!isNode(node)) {
return;
}
this._current = node;
this._skipped = false;
this._enter(node, parent);
this._current = node;
this._skipped = false;
this._enter(node, parent);
if (!this._skipped && !this._broken) {
const keys = getVisitorKeys(this._visitorKeys, node);
if (!this._skipped && !this._broken) {
const keys = getVisitorKeys(this._visitorKeys, node);
if (keys.length >= 1) {
this._parents.push(node);
for (let i = 0; i < keys.length && !this._broken; ++i) {
const child = node[keys[i]];
if (keys.length >= 1) {
this._parents.push(node);
for (let i = 0; i < keys.length && !this._broken; ++i) {
const child = node[keys[i]];
if (Array.isArray(child)) {
for (
let j = 0;
j < child.length && !this._broken;
++j
) {
this._traverse(child[j], node);
}
} else {
this._traverse(child, node);
}
}
this._parents.pop();
}
}
if (Array.isArray(child)) {
for (let j = 0; j < child.length && !this._broken; ++j) {
this._traverse(child[j], node);
}
} else {
this._traverse(child, node);
}
}
this._parents.pop();
}
}
if (!this._broken) {
this._leave(node, parent);
}
if (!this._broken) {
this._leave(node, parent);
}
this._current = parent;
}
this._current = parent;
}
/**
* Calculates the keys to use for traversal.
* @param {ASTNode} node The node to read keys from.
* @returns {string[]} An array of keys to visit on the node.
* @private
*/
static getKeys(node) {
return vk.getKeys(node);
}
/**
* Calculates the keys to use for traversal.
* @param {ASTNode} node The node to read keys from.
* @returns {string[]} An array of keys to visit on the node.
* @private
*/
static getKeys(node) {
return vk.getKeys(node);
}
/**
* Traverse the given AST tree.
* @param {ASTNode} node The root node to traverse.
* @param {Object} options The option object.
* @param {Object} [options.visitorKeys=DEFAULT_VISITOR_KEYS] The keys of each node types to traverse child nodes. Default is `./default-visitor-keys.json`.
* @param {Function} [options.enter=noop] The callback function which is called on entering each node.
* @param {Function} [options.leave=noop] The callback function which is called on leaving each node.
* @returns {void}
*/
static traverse(node, options) {
new Traverser().traverse(node, options);
}
/**
* Traverse the given AST tree.
* @param {ASTNode} node The root node to traverse.
* @param {Object} options The option object.
* @param {Object} [options.visitorKeys=DEFAULT_VISITOR_KEYS] The keys of each node types to traverse child nodes. Default is `./default-visitor-keys.json`.
* @param {Function} [options.enter=noop] The callback function which is called on entering each node.
* @param {Function} [options.leave=noop] The callback function which is called on leaving each node.
* @returns {void}
*/
static traverse(node, options) {
new Traverser().traverse(node, options);
}
/**
* The default visitor keys.
* @type {Object}
*/
static get DEFAULT_VISITOR_KEYS() {
return vk.KEYS;
}
/**
* The default visitor keys.
* @type {Object}
*/
static get DEFAULT_VISITOR_KEYS() {
return vk.KEYS;
}
}
module.exports = Traverser;
+216
View File
@@ -0,0 +1,216 @@
/**
* @fileoverview Define common types for input completion.
* @author Toru Nagashima <https://github.com/mysticatea>
*/
"use strict";
/** @type {any} */
module.exports = {};
/** @typedef {boolean | "off" | "readable" | "readonly" | "writable" | "writeable"} GlobalConf */
/** @typedef {0 | 1 | 2 | "off" | "warn" | "error"} SeverityConf */
/** @typedef {SeverityConf | [SeverityConf, ...any[]]} RuleConf */
/**
* @typedef {Object} EcmaFeatures
* @property {boolean} [globalReturn] Enabling `return` statements at the top-level.
* @property {boolean} [jsx] Enabling JSX syntax.
* @property {boolean} [impliedStrict] Enabling strict mode always.
*/
/**
* @typedef {Object} ParserOptions
* @property {EcmaFeatures} [ecmaFeatures] The optional features.
* @property {3|5|6|7|8|9|10|11|12|13|14|15|2015|2016|2017|2018|2019|2020|2021|2022|2023|2024} [ecmaVersion] The ECMAScript version (or revision number).
* @property {"script"|"module"} [sourceType] The source code type.
* @property {boolean} [allowReserved] Allowing the use of reserved words as identifiers in ES3.
*/
/**
* @typedef {Object} LanguageOptions
* @property {number|"latest"} [ecmaVersion] The ECMAScript version (or revision number).
* @property {Record<string, GlobalConf>} [globals] The global variable settings.
* @property {"script"|"module"|"commonjs"} [sourceType] The source code type.
* @property {string|Object} [parser] The parser to use.
* @property {Object} [parserOptions] The parser options to use.
*/
/**
* @typedef {Object} ConfigData
* @property {Record<string, boolean>} [env] The environment settings.
* @property {string | string[]} [extends] The path to other config files or the package name of shareable configs.
* @property {Record<string, GlobalConf>} [globals] The global variable settings.
* @property {string | string[]} [ignorePatterns] The glob patterns that ignore to lint.
* @property {boolean} [noInlineConfig] The flag that disables directive comments.
* @property {OverrideConfigData[]} [overrides] The override settings per kind of files.
* @property {string} [parser] The path to a parser or the package name of a parser.
* @property {ParserOptions} [parserOptions] The parser options.
* @property {string[]} [plugins] The plugin specifiers.
* @property {string} [processor] The processor specifier.
* @property {boolean} [reportUnusedDisableDirectives] The flag to report unused `eslint-disable` comments.
* @property {boolean} [root] The root flag.
* @property {Record<string, RuleConf>} [rules] The rule settings.
* @property {Object} [settings] The shared settings.
*/
/**
* @typedef {Object} OverrideConfigData
* @property {Record<string, boolean>} [env] The environment settings.
* @property {string | string[]} [excludedFiles] The glob patterns for excluded files.
* @property {string | string[]} [extends] The path to other config files or the package name of shareable configs.
* @property {string | string[]} files The glob patterns for target files.
* @property {Record<string, GlobalConf>} [globals] The global variable settings.
* @property {boolean} [noInlineConfig] The flag that disables directive comments.
* @property {OverrideConfigData[]} [overrides] The override settings per kind of files.
* @property {string} [parser] The path to a parser or the package name of a parser.
* @property {ParserOptions} [parserOptions] The parser options.
* @property {string[]} [plugins] The plugin specifiers.
* @property {string} [processor] The processor specifier.
* @property {boolean} [reportUnusedDisableDirectives] The flag to report unused `eslint-disable` comments.
* @property {Record<string, RuleConf>} [rules] The rule settings.
* @property {Object} [settings] The shared settings.
*/
/**
* @typedef {Object} ParseResult
* @property {Object} ast The AST.
* @property {ScopeManager} [scopeManager] The scope manager of the AST.
* @property {Record<string, any>} [services] The services that the parser provides.
* @property {Record<string, string[]>} [visitorKeys] The visitor keys of the AST.
*/
/**
* @typedef {Object} Parser
* @property {(text:string, options:ParserOptions) => Object} parse The definition of global variables.
* @property {(text:string, options:ParserOptions) => ParseResult} [parseForESLint] The parser options that will be enabled under this environment.
*/
/**
* @typedef {Object} Environment
* @property {Record<string, GlobalConf>} [globals] The definition of global variables.
* @property {ParserOptions} [parserOptions] The parser options that will be enabled under this environment.
*/
/**
* @typedef {Object} LintMessage
* @property {number|undefined} column The 1-based column number.
* @property {number} [endColumn] The 1-based column number of the end location.
* @property {number} [endLine] The 1-based line number of the end location.
* @property {boolean} [fatal] If `true` then this is a fatal error.
* @property {{range:[number,number], text:string}} [fix] Information for autofix.
* @property {number|undefined} line The 1-based line number.
* @property {string} message The error message.
* @property {string} [messageId] The ID of the message in the rule's meta.
* @property {(string|null)} nodeType Type of node
* @property {string|null} ruleId The ID of the rule which makes this message.
* @property {0|1|2} severity The severity of this message.
* @property {Array<{desc?: string, messageId?: string, fix: {range: [number, number], text: string}}>} [suggestions] Information for suggestions.
*/
/**
* @typedef {Object} SuppressedLintMessage
* @property {number|undefined} column The 1-based column number.
* @property {number} [endColumn] The 1-based column number of the end location.
* @property {number} [endLine] The 1-based line number of the end location.
* @property {boolean} [fatal] If `true` then this is a fatal error.
* @property {{range:[number,number], text:string}} [fix] Information for autofix.
* @property {number|undefined} line The 1-based line number.
* @property {string} message The error message.
* @property {string} [messageId] The ID of the message in the rule's meta.
* @property {(string|null)} nodeType Type of node
* @property {string|null} ruleId The ID of the rule which makes this message.
* @property {0|1|2} severity The severity of this message.
* @property {Array<{kind: string, justification: string}>} suppressions The suppression info.
* @property {Array<{desc?: string, messageId?: string, fix: {range: [number, number], text: string}}>} [suggestions] Information for suggestions.
*/
/**
* @typedef {Object} SuggestionResult
* @property {string} desc A short description.
* @property {string} [messageId] Id referencing a message for the description.
* @property {{ text: string, range: number[] }} fix fix result info
*/
/**
* @typedef {Object} Processor
* @property {(text:string, filename:string) => Array<string | { text:string, filename:string }>} [preprocess] The function to extract code blocks.
* @property {(messagesList:LintMessage[][], filename:string) => LintMessage[]} [postprocess] The function to merge messages.
* @property {boolean} [supportsAutofix] If `true` then it means the processor supports autofix.
*/
/**
* @typedef {Object} RuleMetaDocs
* @property {string} description The description of the rule.
* @property {boolean} recommended If `true` then the rule is included in `eslint:recommended` preset.
* @property {string} url The URL of the rule documentation.
*/
/**
* @typedef {Object} RuleMeta
* @property {boolean} [deprecated] If `true` then the rule has been deprecated.
* @property {RuleMetaDocs} docs The document information of the rule.
* @property {"code"|"whitespace"} [fixable] The autofix type.
* @property {boolean} [hasSuggestions] If `true` then the rule provides suggestions.
* @property {Record<string,string>} [messages] The messages the rule reports.
* @property {string[]} [replacedBy] The IDs of the alternative rules.
* @property {Array|Object} schema The option schema of the rule.
* @property {"problem"|"suggestion"|"layout"} type The rule type.
*/
/**
* @typedef {Object} Rule
* @property {Function} create The factory of the rule.
* @property {RuleMeta} meta The meta data of the rule.
*/
/**
* @typedef {Object} Plugin
* @property {Record<string, ConfigData>} [configs] The definition of plugin configs.
* @property {Record<string, Environment>} [environments] The definition of plugin environments.
* @property {Record<string, Processor>} [processors] The definition of plugin processors.
* @property {Record<string, Function | Rule>} [rules] The definition of plugin rules.
*/
/**
* Information of deprecated rules.
* @typedef {Object} DeprecatedRuleInfo
* @property {string} ruleId The rule ID.
* @property {string[]} replacedBy The rule IDs that replace this deprecated rule.
*/
/**
* A linting result.
* @typedef {Object} LintResult
* @property {string} filePath The path to the file that was linted.
* @property {LintMessage[]} messages All of the messages for the result.
* @property {SuppressedLintMessage[]} suppressedMessages All of the suppressed messages for the result.
* @property {number} errorCount Number of errors for the result.
* @property {number} fatalErrorCount Number of fatal errors for the result.
* @property {number} warningCount Number of warnings for the result.
* @property {number} fixableErrorCount Number of fixable errors for the result.
* @property {number} fixableWarningCount Number of fixable warnings for the result.
* @property {string} [source] The source code of the file that was linted.
* @property {string} [output] The source code of the file that was linted, with as many fixes applied as possible.
* @property {DeprecatedRuleInfo[]} usedDeprecatedRules The list of used deprecated rules.
*/
/**
* Information provided when the maximum warning threshold is exceeded.
* @typedef {Object} MaxWarningsExceeded
* @property {number} maxWarnings Number of warnings to trigger nonzero exit code.
* @property {number} foundWarnings Number of warnings found while linting.
*/
/**
* Metadata about results for formatters.
* @typedef {Object} ResultsMeta
* @property {MaxWarningsExceeded} [maxWarningsExceeded] Present if the maxWarnings threshold was exceeded.
*/
/**
* A formatter function.
* @callback FormatterFunction
* @param {LintResult[]} results The list of linting results.
* @param {{cwd: string, maxWarningsExceeded?: MaxWarningsExceeded, rulesMeta: Record<string, RuleMeta>}} [context] A context object.
* @returns {string | Promise<string>} Formatted text.
*/