This commit is contained in:
2025-05-09 05:30:08 +02:00
parent 7bb10e7df4
commit 73367bad9e
5322 changed files with 1266973 additions and 313 deletions

View File

@@ -0,0 +1,239 @@
'use strict';
module.exports = {
copy: copy,
checkDataType: checkDataType,
checkDataTypes: checkDataTypes,
coerceToTypes: coerceToTypes,
toHash: toHash,
getProperty: getProperty,
escapeQuotes: escapeQuotes,
equal: require('fast-deep-equal'),
ucs2length: require('./ucs2length'),
varOccurences: varOccurences,
varReplace: varReplace,
schemaHasRules: schemaHasRules,
schemaHasRulesExcept: schemaHasRulesExcept,
schemaUnknownRules: schemaUnknownRules,
toQuotedString: toQuotedString,
getPathExpr: getPathExpr,
getPath: getPath,
getData: getData,
unescapeFragment: unescapeFragment,
unescapeJsonPointer: unescapeJsonPointer,
escapeFragment: escapeFragment,
escapeJsonPointer: escapeJsonPointer
};
function copy(o, to) {
to = to || {};
for (var key in o) to[key] = o[key];
return to;
}
function checkDataType(dataType, data, strictNumbers, negate) {
var EQUAL = negate ? ' !== ' : ' === '
, AND = negate ? ' || ' : ' && '
, OK = negate ? '!' : ''
, NOT = negate ? '' : '!';
switch (dataType) {
case 'null': return data + EQUAL + 'null';
case 'array': return OK + 'Array.isArray(' + data + ')';
case 'object': return '(' + OK + data + AND +
'typeof ' + data + EQUAL + '"object"' + AND +
NOT + 'Array.isArray(' + data + '))';
case 'integer': return '(typeof ' + data + EQUAL + '"number"' + AND +
NOT + '(' + data + ' % 1)' +
AND + data + EQUAL + data +
(strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')';
case 'number': return '(typeof ' + data + EQUAL + '"' + dataType + '"' +
(strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')';
default: return 'typeof ' + data + EQUAL + '"' + dataType + '"';
}
}
function checkDataTypes(dataTypes, data, strictNumbers) {
switch (dataTypes.length) {
case 1: return checkDataType(dataTypes[0], data, strictNumbers, true);
default:
var code = '';
var types = toHash(dataTypes);
if (types.array && types.object) {
code = types.null ? '(': '(!' + data + ' || ';
code += 'typeof ' + data + ' !== "object")';
delete types.null;
delete types.array;
delete types.object;
}
if (types.number) delete types.integer;
for (var t in types)
code += (code ? ' && ' : '' ) + checkDataType(t, data, strictNumbers, true);
return code;
}
}
var COERCE_TO_TYPES = toHash([ 'string', 'number', 'integer', 'boolean', 'null' ]);
function coerceToTypes(optionCoerceTypes, dataTypes) {
if (Array.isArray(dataTypes)) {
var types = [];
for (var i=0; i<dataTypes.length; i++) {
var t = dataTypes[i];
if (COERCE_TO_TYPES[t]) types[types.length] = t;
else if (optionCoerceTypes === 'array' && t === 'array') types[types.length] = t;
}
if (types.length) return types;
} else if (COERCE_TO_TYPES[dataTypes]) {
return [dataTypes];
} else if (optionCoerceTypes === 'array' && dataTypes === 'array') {
return ['array'];
}
}
function toHash(arr) {
var hash = {};
for (var i=0; i<arr.length; i++) hash[arr[i]] = true;
return hash;
}
var IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
var SINGLE_QUOTE = /'|\\/g;
function getProperty(key) {
return typeof key == 'number'
? '[' + key + ']'
: IDENTIFIER.test(key)
? '.' + key
: "['" + escapeQuotes(key) + "']";
}
function escapeQuotes(str) {
return str.replace(SINGLE_QUOTE, '\\$&')
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r')
.replace(/\f/g, '\\f')
.replace(/\t/g, '\\t');
}
function varOccurences(str, dataVar) {
dataVar += '[^0-9]';
var matches = str.match(new RegExp(dataVar, 'g'));
return matches ? matches.length : 0;
}
function varReplace(str, dataVar, expr) {
dataVar += '([^0-9])';
expr = expr.replace(/\$/g, '$$$$');
return str.replace(new RegExp(dataVar, 'g'), expr + '$1');
}
function schemaHasRules(schema, rules) {
if (typeof schema == 'boolean') return !schema;
for (var key in schema) if (rules[key]) return true;
}
function schemaHasRulesExcept(schema, rules, exceptKeyword) {
if (typeof schema == 'boolean') return !schema && exceptKeyword != 'not';
for (var key in schema) if (key != exceptKeyword && rules[key]) return true;
}
function schemaUnknownRules(schema, rules) {
if (typeof schema == 'boolean') return;
for (var key in schema) if (!rules[key]) return key;
}
function toQuotedString(str) {
return '\'' + escapeQuotes(str) + '\'';
}
function getPathExpr(currentPath, expr, jsonPointers, isNumber) {
var path = jsonPointers // false by default
? '\'/\' + ' + expr + (isNumber ? '' : '.replace(/~/g, \'~0\').replace(/\\//g, \'~1\')')
: (isNumber ? '\'[\' + ' + expr + ' + \']\'' : '\'[\\\'\' + ' + expr + ' + \'\\\']\'');
return joinPaths(currentPath, path);
}
function getPath(currentPath, prop, jsonPointers) {
var path = jsonPointers // false by default
? toQuotedString('/' + escapeJsonPointer(prop))
: toQuotedString(getProperty(prop));
return joinPaths(currentPath, path);
}
var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
function getData($data, lvl, paths) {
var up, jsonPointer, data, matches;
if ($data === '') return 'rootData';
if ($data[0] == '/') {
if (!JSON_POINTER.test($data)) throw new Error('Invalid JSON-pointer: ' + $data);
jsonPointer = $data;
data = 'rootData';
} else {
matches = $data.match(RELATIVE_JSON_POINTER);
if (!matches) throw new Error('Invalid JSON-pointer: ' + $data);
up = +matches[1];
jsonPointer = matches[2];
if (jsonPointer == '#') {
if (up >= lvl) throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl);
return paths[lvl - up];
}
if (up > lvl) throw new Error('Cannot access data ' + up + ' levels up, current level is ' + lvl);
data = 'data' + ((lvl - up) || '');
if (!jsonPointer) return data;
}
var expr = data;
var segments = jsonPointer.split('/');
for (var i=0; i<segments.length; i++) {
var segment = segments[i];
if (segment) {
data += getProperty(unescapeJsonPointer(segment));
expr += ' && ' + data;
}
}
return expr;
}
function joinPaths (a, b) {
if (a == '""') return b;
return (a + ' + ' + b).replace(/([^\\])' \+ '/g, '$1');
}
function unescapeFragment(str) {
return unescapeJsonPointer(decodeURIComponent(str));
}
function escapeFragment(str) {
return encodeURIComponent(escapeJsonPointer(str));
}
function escapeJsonPointer(str) {
return str.replace(/~/g, '~0').replace(/\//g, '~1');
}
function unescapeJsonPointer(str) {
return str.replace(/~1/g, '/').replace(/~0/g, '~');
}

View File

@@ -0,0 +1,13 @@
import type { NavigateOptions } from './link'
import type { RegisteredRouter } from './router'
export type UseNavigateResult<TDefaultFrom extends string> = <
TRouter extends RegisteredRouter,
TTo extends string | undefined,
TFrom extends string = TDefaultFrom,
TMaskFrom extends string = TFrom,
TMaskTo extends string = '',
>({
from,
...rest
}: NavigateOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>) => Promise<void>

View File

@@ -0,0 +1,76 @@
/**
* @fileoverview This file contains the core types for ESLint. It was initially extracted
* from the `@types/eslint__eslintrc` package.
*/
/*
* MIT License
* Copyright (c) Microsoft Corporation.
*
* 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
*/
import type { Linter } from "eslint";
/**
* A compatibility class for working with configs.
*/
export class FlatCompat {
constructor({
baseDirectory,
resolvePluginsRelativeTo,
recommendedConfig,
allConfig,
}?: {
/**
* default: process.cwd()
*/
baseDirectory?: string;
resolvePluginsRelativeTo?: string;
recommendedConfig?: Linter.LegacyConfig;
allConfig?: Linter.LegacyConfig;
});
/**
* Translates an ESLintRC-style config into a flag-config-style config.
* @param eslintrcConfig The ESLintRC-style config object.
* @returns A flag-config-style config object.
*/
config(eslintrcConfig: Linter.LegacyConfig): Linter.Config[];
/**
* Translates the `env` section of an ESLintRC-style config.
* @param envConfig The `env` section of an ESLintRC config.
* @returns An array of flag-config objects representing the environments.
*/
env(envConfig: { [name: string]: boolean }): Linter.Config[];
/**
* Translates the `extends` section of an ESLintRC-style config.
* @param configsToExtend The names of the configs to load.
* @returns An array of flag-config objects representing the config.
*/
extends(...configsToExtend: string[]): Linter.Config[];
/**
* Translates the `plugins` section of an ESLintRC-style config.
* @param plugins The names of the plugins to load.
* @returns An array of flag-config objects representing the plugins.
*/
plugins(...plugins: string[]): Linter.Config[];
}

View File

@@ -0,0 +1,786 @@
/**
* @fileoverview Main API Class
* @author Kai Cataldo
* @author Toru Nagashima
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const path = require("node:path");
const fs = require("node:fs");
const { promisify } = require("node:util");
const {
CLIEngine,
getCLIEngineInternalSlots,
} = require("../cli-engine/cli-engine");
const BuiltinRules = require("../rules");
const {
Legacy: {
ConfigOps: { getRuleSeverity },
},
} = require("@eslint/eslintrc");
const { version } = require("../../package.json");
//------------------------------------------------------------------------------
// Typedefs
//------------------------------------------------------------------------------
/** @typedef {import("../cli-engine/cli-engine").LintReport} CLIEngineLintReport */
/** @typedef {import("../shared/types").DeprecatedRuleInfo} DeprecatedRuleInfo */
/** @typedef {import("../shared/types").ConfigData} ConfigData */
/** @typedef {import("../shared/types").LintMessage} LintMessage */
/** @typedef {import("../shared/types").SuppressedLintMessage} SuppressedLintMessage */
/** @typedef {import("../shared/types").Plugin} Plugin */
/** @typedef {import("../shared/types").Rule} Rule */
/** @typedef {import("../shared/types").LintResult} LintResult */
/** @typedef {import("../shared/types").ResultsMeta} ResultsMeta */
/**
* The main formatter object.
* @typedef LoadedFormatter
* @property {(results: LintResult[], resultsMeta: ResultsMeta) => string | Promise<string>} format format function.
*/
/**
* The options with which to configure the LegacyESLint instance.
* @typedef {Object} LegacyESLintOptions
* @property {boolean} [allowInlineConfig] Enable or disable inline configuration comments.
* @property {ConfigData} [baseConfig] Base config object, extended by all configs used with this instance
* @property {boolean} [cache] Enable result caching.
* @property {string} [cacheLocation] The cache file to use instead of .eslintcache.
* @property {"metadata" | "content"} [cacheStrategy] The strategy used to detect changed files.
* @property {string} [cwd] The value to use for the current working directory.
* @property {boolean} [errorOnUnmatchedPattern] If `false` then `ESLint#lintFiles()` doesn't throw even if no target files found. Defaults to `true`.
* @property {string[]} [extensions] An array of file extensions to check.
* @property {boolean|Function} [fix] Execute in autofix mode. If a function, should return a boolean.
* @property {string[]} [fixTypes] Array of rule types to apply fixes for.
* @property {boolean} [globInputPaths] Set to false to skip glob resolution of input file paths to lint (default: true). If false, each input file paths is assumed to be a non-glob path to an existing file.
* @property {boolean} [ignore] False disables use of .eslintignore.
* @property {string} [ignorePath] The ignore file to use instead of .eslintignore.
* @property {ConfigData} [overrideConfig] Override config object, overrides all configs used with this instance
* @property {string} [overrideConfigFile] The configuration file to use.
* @property {Record<string,Plugin>|null} [plugins] Preloaded plugins. This is a map-like object, keys are plugin IDs and each value is implementation.
* @property {"error" | "warn" | "off"} [reportUnusedDisableDirectives] the severity to report unused eslint-disable directives.
* @property {string} [resolvePluginsRelativeTo] The folder where plugins should be resolved from, defaulting to the CWD.
* @property {string[]} [rulePaths] An array of directories to load custom rules from.
* @property {boolean} [useEslintrc] False disables looking for .eslintrc.* files.
* @property {boolean} [passOnNoPatterns=false] When set to true, missing patterns cause
* the linting operation to short circuit and not report any failures.
*/
/**
* A rules metadata object.
* @typedef {Object} RulesMeta
* @property {string} id The plugin ID.
* @property {Object} definition The plugin definition.
*/
/**
* Private members for the `ESLint` instance.
* @typedef {Object} ESLintPrivateMembers
* @property {CLIEngine} cliEngine The wrapped CLIEngine instance.
* @property {LegacyESLintOptions} options The options used to instantiate the ESLint instance.
*/
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
const writeFile = promisify(fs.writeFile);
/**
* The map with which to store private class members.
* @type {WeakMap<ESLint, ESLintPrivateMembers>}
*/
const privateMembersMap = new WeakMap();
/**
* Check if a given value is a non-empty string or not.
* @param {any} value The value to check.
* @returns {boolean} `true` if `value` is a non-empty string.
*/
function isNonEmptyString(value) {
return typeof value === "string" && value.trim() !== "";
}
/**
* Check if a given value is an array of non-empty strings or not.
* @param {any} value The value to check.
* @returns {boolean} `true` if `value` is an array of non-empty strings.
*/
function isArrayOfNonEmptyString(value) {
return (
Array.isArray(value) && value.length && value.every(isNonEmptyString)
);
}
/**
* Check if a given value is an empty array or an array of non-empty strings.
* @param {any} value The value to check.
* @returns {boolean} `true` if `value` is an empty array or an array of non-empty
* strings.
*/
function isEmptyArrayOrArrayOfNonEmptyString(value) {
return Array.isArray(value) && value.every(isNonEmptyString);
}
/**
* Check if a given value is a valid fix type or not.
* @param {any} value The value to check.
* @returns {boolean} `true` if `value` is valid fix type.
*/
function isFixType(value) {
return (
value === "directive" ||
value === "problem" ||
value === "suggestion" ||
value === "layout"
);
}
/**
* Check if a given value is an array of fix types or not.
* @param {any} value The value to check.
* @returns {boolean} `true` if `value` is an array of fix types.
*/
function isFixTypeArray(value) {
return Array.isArray(value) && value.every(isFixType);
}
/**
* The error for invalid options.
*/
class ESLintInvalidOptionsError extends Error {
constructor(messages) {
super(`Invalid Options:\n- ${messages.join("\n- ")}`);
this.code = "ESLINT_INVALID_OPTIONS";
Error.captureStackTrace(this, ESLintInvalidOptionsError);
}
}
/**
* Validates and normalizes options for the wrapped CLIEngine instance.
* @param {LegacyESLintOptions} options The options to process.
* @throws {ESLintInvalidOptionsError} If of any of a variety of type errors.
* @returns {LegacyESLintOptions} The normalized options.
*/
function processOptions({
allowInlineConfig = true, // ← we cannot use `overrideConfig.noInlineConfig` instead because `allowInlineConfig` has side-effect that suppress warnings that show inline configs are ignored.
baseConfig = null,
cache = false,
cacheLocation = ".eslintcache",
cacheStrategy = "metadata",
cwd = process.cwd(),
errorOnUnmatchedPattern = true,
extensions = null, // ← should be null by default because if it's an array then it suppresses RFC20 feature.
fix = false,
fixTypes = null, // ← should be null by default because if it's an array then it suppresses rules that don't have the `meta.type` property.
flags /* eslint-disable-line no-unused-vars -- leaving for compatibility with ESLint#hasFlag */,
globInputPaths = true,
ignore = true,
ignorePath = null, // ← should be null by default because if it's a string then it may throw ENOENT.
overrideConfig = null,
overrideConfigFile = null,
plugins = {},
reportUnusedDisableDirectives = null, // ← should be null by default because if it's a string then it overrides the 'reportUnusedDisableDirectives' setting in config files. And we cannot use `overrideConfig.reportUnusedDisableDirectives` instead because we cannot configure the `error` severity with that.
resolvePluginsRelativeTo = null, // ← should be null by default because if it's a string then it suppresses RFC47 feature.
rulePaths = [],
useEslintrc = true,
passOnNoPatterns = false,
...unknownOptions
}) {
const errors = [];
const unknownOptionKeys = Object.keys(unknownOptions);
if (unknownOptionKeys.length >= 1) {
errors.push(`Unknown options: ${unknownOptionKeys.join(", ")}`);
if (unknownOptionKeys.includes("cacheFile")) {
errors.push(
"'cacheFile' has been removed. Please use the 'cacheLocation' option instead.",
);
}
if (unknownOptionKeys.includes("configFile")) {
errors.push(
"'configFile' has been removed. Please use the 'overrideConfigFile' option instead.",
);
}
if (unknownOptionKeys.includes("envs")) {
errors.push(
"'envs' has been removed. Please use the 'overrideConfig.env' option instead.",
);
}
if (unknownOptionKeys.includes("globals")) {
errors.push(
"'globals' has been removed. Please use the 'overrideConfig.globals' option instead.",
);
}
if (unknownOptionKeys.includes("ignorePattern")) {
errors.push(
"'ignorePattern' has been removed. Please use the 'overrideConfig.ignorePatterns' option instead.",
);
}
if (unknownOptionKeys.includes("parser")) {
errors.push(
"'parser' has been removed. Please use the 'overrideConfig.parser' option instead.",
);
}
if (unknownOptionKeys.includes("parserOptions")) {
errors.push(
"'parserOptions' has been removed. Please use the 'overrideConfig.parserOptions' option instead.",
);
}
if (unknownOptionKeys.includes("rules")) {
errors.push(
"'rules' has been removed. Please use the 'overrideConfig.rules' option instead.",
);
}
}
if (typeof allowInlineConfig !== "boolean") {
errors.push("'allowInlineConfig' must be a boolean.");
}
if (typeof baseConfig !== "object") {
errors.push("'baseConfig' must be an object or null.");
}
if (typeof cache !== "boolean") {
errors.push("'cache' must be a boolean.");
}
if (!isNonEmptyString(cacheLocation)) {
errors.push("'cacheLocation' must be a non-empty string.");
}
if (cacheStrategy !== "metadata" && cacheStrategy !== "content") {
errors.push('\'cacheStrategy\' must be any of "metadata", "content".');
}
if (!isNonEmptyString(cwd) || !path.isAbsolute(cwd)) {
errors.push("'cwd' must be an absolute path.");
}
if (typeof errorOnUnmatchedPattern !== "boolean") {
errors.push("'errorOnUnmatchedPattern' must be a boolean.");
}
if (
!isEmptyArrayOrArrayOfNonEmptyString(extensions) &&
extensions !== null
) {
errors.push(
"'extensions' must be an array of non-empty strings or null.",
);
}
if (typeof fix !== "boolean" && typeof fix !== "function") {
errors.push("'fix' must be a boolean or a function.");
}
if (fixTypes !== null && !isFixTypeArray(fixTypes)) {
errors.push(
'\'fixTypes\' must be an array of any of "directive", "problem", "suggestion", and "layout".',
);
}
if (typeof globInputPaths !== "boolean") {
errors.push("'globInputPaths' must be a boolean.");
}
if (typeof ignore !== "boolean") {
errors.push("'ignore' must be a boolean.");
}
if (!isNonEmptyString(ignorePath) && ignorePath !== null) {
errors.push("'ignorePath' must be a non-empty string or null.");
}
if (typeof overrideConfig !== "object") {
errors.push("'overrideConfig' must be an object or null.");
}
if (!isNonEmptyString(overrideConfigFile) && overrideConfigFile !== null) {
errors.push("'overrideConfigFile' must be a non-empty string or null.");
}
if (typeof plugins !== "object") {
errors.push("'plugins' must be an object or null.");
} else if (plugins !== null && Object.keys(plugins).includes("")) {
errors.push("'plugins' must not include an empty string.");
}
if (Array.isArray(plugins)) {
errors.push(
"'plugins' doesn't add plugins to configuration to load. Please use the 'overrideConfig.plugins' option instead.",
);
}
if (
reportUnusedDisableDirectives !== "error" &&
reportUnusedDisableDirectives !== "warn" &&
reportUnusedDisableDirectives !== "off" &&
reportUnusedDisableDirectives !== null
) {
errors.push(
'\'reportUnusedDisableDirectives\' must be any of "error", "warn", "off", and null.',
);
}
if (
!isNonEmptyString(resolvePluginsRelativeTo) &&
resolvePluginsRelativeTo !== null
) {
errors.push(
"'resolvePluginsRelativeTo' must be a non-empty string or null.",
);
}
if (!isEmptyArrayOrArrayOfNonEmptyString(rulePaths)) {
errors.push("'rulePaths' must be an array of non-empty strings.");
}
if (typeof useEslintrc !== "boolean") {
errors.push("'useEslintrc' must be a boolean.");
}
if (typeof passOnNoPatterns !== "boolean") {
errors.push("'passOnNoPatterns' must be a boolean.");
}
if (errors.length > 0) {
throw new ESLintInvalidOptionsError(errors);
}
return {
allowInlineConfig,
baseConfig,
cache,
cacheLocation,
cacheStrategy,
configFile: overrideConfigFile,
cwd: path.normalize(cwd),
errorOnUnmatchedPattern,
extensions,
fix,
fixTypes,
flags: [], // LegacyESLint does not support flags, so just ignore them.
globInputPaths,
ignore,
ignorePath,
reportUnusedDisableDirectives,
resolvePluginsRelativeTo,
rulePaths,
useEslintrc,
passOnNoPatterns,
};
}
/**
* Check if a value has one or more properties and that value is not undefined.
* @param {any} obj The value to check.
* @returns {boolean} `true` if `obj` has one or more properties that value is not undefined.
*/
function hasDefinedProperty(obj) {
if (typeof obj === "object" && obj !== null) {
for (const key in obj) {
if (typeof obj[key] !== "undefined") {
return true;
}
}
}
return false;
}
/**
* Create rulesMeta object.
* @param {Map<string,Rule>} rules a map of rules from which to generate the object.
* @returns {Object} metadata for all enabled rules.
*/
function createRulesMeta(rules) {
return Array.from(rules).reduce((retVal, [id, rule]) => {
retVal[id] = rule.meta;
return retVal;
}, {});
}
/** @type {WeakMap<ExtractedConfig, DeprecatedRuleInfo[]>} */
const usedDeprecatedRulesCache = new WeakMap();
/**
* Create used deprecated rule list.
* @param {CLIEngine} cliEngine The CLIEngine instance.
* @param {string} maybeFilePath The absolute path to a lint target file or `"<text>"`.
* @returns {DeprecatedRuleInfo[]} The used deprecated rule list.
*/
function getOrFindUsedDeprecatedRules(cliEngine, maybeFilePath) {
const {
configArrayFactory,
options: { cwd },
} = getCLIEngineInternalSlots(cliEngine);
const filePath = path.isAbsolute(maybeFilePath)
? maybeFilePath
: path.join(cwd, "__placeholder__.js");
const configArray = configArrayFactory.getConfigArrayForFile(filePath);
const config = configArray.extractConfig(filePath);
// Most files use the same config, so cache it.
if (!usedDeprecatedRulesCache.has(config)) {
const pluginRules = configArray.pluginRules;
const retv = [];
for (const [ruleId, ruleConf] of Object.entries(config.rules)) {
if (getRuleSeverity(ruleConf) === 0) {
continue;
}
const rule = pluginRules.get(ruleId) || BuiltinRules.get(ruleId);
const meta = rule && rule.meta;
if (meta && meta.deprecated) {
retv.push({ ruleId, replacedBy: meta.replacedBy || [] });
}
}
usedDeprecatedRulesCache.set(config, Object.freeze(retv));
}
return usedDeprecatedRulesCache.get(config);
}
/**
* Processes the linting results generated by a CLIEngine linting report to
* match the ESLint class's API.
* @param {CLIEngine} cliEngine The CLIEngine instance.
* @param {CLIEngineLintReport} report The CLIEngine linting report to process.
* @returns {LintResult[]} The processed linting results.
*/
function processCLIEngineLintReport(cliEngine, { results }) {
const descriptor = {
configurable: true,
enumerable: true,
get() {
return getOrFindUsedDeprecatedRules(cliEngine, this.filePath);
},
};
for (const result of results) {
Object.defineProperty(result, "usedDeprecatedRules", descriptor);
}
return results;
}
/**
* An Array.prototype.sort() compatible compare function to order results by their file path.
* @param {LintResult} a The first lint result.
* @param {LintResult} b The second lint result.
* @returns {number} An integer representing the order in which the two results should occur.
*/
function compareResultsByFilePath(a, b) {
if (a.filePath < b.filePath) {
return -1;
}
if (a.filePath > b.filePath) {
return 1;
}
return 0;
}
/**
* Main API.
*/
class LegacyESLint {
/**
* The type of configuration used by this class.
* @type {string}
*/
static configType = "eslintrc";
/**
* Creates a new instance of the main ESLint API.
* @param {LegacyESLintOptions} options The options for this instance.
*/
constructor(options = {}) {
const processedOptions = processOptions(options);
const cliEngine = new CLIEngine(processedOptions, {
preloadedPlugins: options.plugins,
});
const { configArrayFactory, lastConfigArrays } =
getCLIEngineInternalSlots(cliEngine);
let updated = false;
/*
* Address `overrideConfig` to set override config.
* Operate the `configArrayFactory` internal slot directly because this
* functionality doesn't exist as the public API of CLIEngine.
*/
if (hasDefinedProperty(options.overrideConfig)) {
configArrayFactory.setOverrideConfig(options.overrideConfig);
updated = true;
}
// Update caches.
if (updated) {
configArrayFactory.clearCache();
lastConfigArrays[0] = configArrayFactory.getConfigArrayForFile();
}
// Initialize private properties.
privateMembersMap.set(this, {
cliEngine,
options: processedOptions,
});
}
/**
* The version text.
* @type {string}
*/
static get version() {
return version;
}
/**
* Outputs fixes from the given results to files.
* @param {LintResult[]} results The lint results.
* @returns {Promise<void>} Returns a promise that is used to track side effects.
*/
static async outputFixes(results) {
if (!Array.isArray(results)) {
throw new Error("'results' must be an array");
}
await Promise.all(
results
.filter(result => {
if (typeof result !== "object" || result === null) {
throw new Error("'results' must include only objects");
}
return (
typeof result.output === "string" &&
path.isAbsolute(result.filePath)
);
})
.map(r => writeFile(r.filePath, r.output)),
);
}
/**
* Returns results that only contains errors.
* @param {LintResult[]} results The results to filter.
* @returns {LintResult[]} The filtered results.
*/
static getErrorResults(results) {
return CLIEngine.getErrorResults(results);
}
/**
* Returns meta objects for each rule represented in the lint results.
* @param {LintResult[]} results The results to fetch rules meta for.
* @returns {Object} A mapping of ruleIds to rule meta objects.
*/
getRulesMetaForResults(results) {
const resultRuleIds = new Set();
// first gather all ruleIds from all results
for (const result of results) {
for (const { ruleId } of result.messages) {
resultRuleIds.add(ruleId);
}
for (const { ruleId } of result.suppressedMessages) {
resultRuleIds.add(ruleId);
}
}
// create a map of all rules in the results
const { cliEngine } = privateMembersMap.get(this);
const rules = cliEngine.getRules();
const resultRules = new Map();
for (const [ruleId, rule] of rules) {
if (resultRuleIds.has(ruleId)) {
resultRules.set(ruleId, rule);
}
}
return createRulesMeta(resultRules);
}
/* eslint-disable no-unused-vars, class-methods-use-this -- leaving for compatibility with ESLint#hasFlag */
/**
* Indicates if the given feature flag is enabled for this instance. For this
* class, this always returns `false` because it does not support feature flags.
* @param {string} flag The feature flag to check.
* @returns {boolean} Always false.
*/
hasFlag(flag) {
return false;
}
/* eslint-enable no-unused-vars, class-methods-use-this -- reenable rules for the rest of the file */
/**
* Executes the current configuration on an array of file and directory names.
* @param {string[]} patterns An array of file and directory names.
* @returns {Promise<LintResult[]>} The results of linting the file patterns given.
*/
async lintFiles(patterns) {
const { cliEngine, options } = privateMembersMap.get(this);
if (
options.passOnNoPatterns &&
(patterns === "" ||
(Array.isArray(patterns) && patterns.length === 0))
) {
return [];
}
if (!isNonEmptyString(patterns) && !isArrayOfNonEmptyString(patterns)) {
throw new Error(
"'patterns' must be a non-empty string or an array of non-empty strings",
);
}
return processCLIEngineLintReport(
cliEngine,
cliEngine.executeOnFiles(patterns),
);
}
/**
* Executes the current configuration on text.
* @param {string} code A string of JavaScript code to lint.
* @param {Object} [options] The options.
* @param {string} [options.filePath] The path to the file of the source code.
* @param {boolean} [options.warnIgnored] When set to true, warn if given filePath is an ignored path.
* @returns {Promise<LintResult[]>} The results of linting the string of code given.
*/
async lintText(code, options = {}) {
if (typeof code !== "string") {
throw new Error("'code' must be a string");
}
if (typeof options !== "object") {
throw new Error("'options' must be an object, null, or undefined");
}
const {
filePath,
warnIgnored = false,
...unknownOptions
} = options || {};
const unknownOptionKeys = Object.keys(unknownOptions);
if (unknownOptionKeys.length > 0) {
throw new Error(
`'options' must not include the unknown option(s): ${unknownOptionKeys.join(", ")}`,
);
}
if (filePath !== void 0 && !isNonEmptyString(filePath)) {
throw new Error(
"'options.filePath' must be a non-empty string or undefined",
);
}
if (typeof warnIgnored !== "boolean") {
throw new Error(
"'options.warnIgnored' must be a boolean or undefined",
);
}
const { cliEngine } = privateMembersMap.get(this);
return processCLIEngineLintReport(
cliEngine,
cliEngine.executeOnText(code, filePath, warnIgnored),
);
}
/**
* Returns the formatter representing the given formatter name.
* @param {string} [name] The name of the formatter to load.
* The following values are allowed:
* - `undefined` ... Load `stylish` builtin formatter.
* - A builtin formatter name ... Load the builtin formatter.
* - A third-party formatter name:
* - `foo` → `eslint-formatter-foo`
* - `@foo` → `@foo/eslint-formatter`
* - `@foo/bar` → `@foo/eslint-formatter-bar`
* - A file path ... Load the file.
* @returns {Promise<LoadedFormatter>} A promise resolving to the formatter object.
* This promise will be rejected if the given formatter was not found or not
* a function.
*/
async loadFormatter(name = "stylish") {
if (typeof name !== "string") {
throw new Error("'name' must be a string");
}
const { cliEngine, options } = privateMembersMap.get(this);
const formatter = cliEngine.getFormatter(name);
if (typeof formatter !== "function") {
throw new Error(
`Formatter must be a function, but got a ${typeof formatter}.`,
);
}
return {
/**
* The main formatter method.
* @param {LintResult[]} results The lint results to format.
* @param {ResultsMeta} resultsMeta Warning count and max threshold.
* @returns {string | Promise<string>} The formatted lint results.
*/
format(results, resultsMeta) {
let rulesMeta = null;
results.sort(compareResultsByFilePath);
return formatter(results, {
...resultsMeta,
get cwd() {
return options.cwd;
},
get rulesMeta() {
if (!rulesMeta) {
rulesMeta = createRulesMeta(cliEngine.getRules());
}
return rulesMeta;
},
});
},
};
}
/**
* Returns a configuration object for the given file based on the CLI options.
* This is the same logic used by the ESLint CLI executable to determine
* configuration for each file it processes.
* @param {string} filePath The path of the file to retrieve a config object for.
* @returns {Promise<ConfigData>} A configuration object for the file.
*/
async calculateConfigForFile(filePath) {
if (!isNonEmptyString(filePath)) {
throw new Error("'filePath' must be a non-empty string");
}
const { cliEngine } = privateMembersMap.get(this);
return cliEngine.getConfigForFile(filePath);
}
/**
* Checks if a given path is ignored by ESLint.
* @param {string} filePath The path of the file to check.
* @returns {Promise<boolean>} Whether or not the given path is ignored.
*/
async isPathIgnored(filePath) {
if (!isNonEmptyString(filePath)) {
throw new Error("'filePath' must be a non-empty string");
}
const { cliEngine } = privateMembersMap.get(this);
return cliEngine.isPathIgnored(filePath);
}
}
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
module.exports = {
LegacyESLint,
/**
* Get the private class members of a given ESLint instance for tests.
* @param {ESLint} instance The ESLint instance to get.
* @returns {ESLintPrivateMembers} The instance's private class members.
*/
getESLintPrivateMembers(instance) {
return privateMembersMap.get(instance);
},
};

View File

@@ -0,0 +1 @@
{"version":3,"names":["unreleasedLabels","exports","safari","browserNameMap","and_chr","and_ff","android","chrome","edge","firefox","ie","ie_mob","ios_saf","node","deno","op_mob","opera","samsung"],"sources":["../src/targets.ts"],"sourcesContent":["export const unreleasedLabels = {\n safari: \"tp\",\n} as const;\n\n// Map from browserslist|@mdn/browser-compat-data browser names to @kangax/compat-table browser names\nexport const browserNameMap = {\n and_chr: \"chrome\",\n and_ff: \"firefox\",\n android: \"android\",\n chrome: \"chrome\",\n edge: \"edge\",\n firefox: \"firefox\",\n ie: \"ie\",\n ie_mob: \"ie\",\n ios_saf: \"ios\",\n node: \"node\",\n deno: \"deno\",\n op_mob: \"opera_mobile\",\n opera: \"opera\",\n safari: \"safari\",\n samsung: \"samsung\",\n} as const;\n\nexport type BrowserslistBrowserName = keyof typeof browserNameMap;\n"],"mappings":";;;;;;AAAO,MAAMA,gBAAgB,GAAAC,OAAA,CAAAD,gBAAA,GAAG;EAC9BE,MAAM,EAAE;AACV,CAAU;AAGH,MAAMC,cAAc,GAAAF,OAAA,CAAAE,cAAA,GAAG;EAC5BC,OAAO,EAAE,QAAQ;EACjBC,MAAM,EAAE,SAAS;EACjBC,OAAO,EAAE,SAAS;EAClBC,MAAM,EAAE,QAAQ;EAChBC,IAAI,EAAE,MAAM;EACZC,OAAO,EAAE,SAAS;EAClBC,EAAE,EAAE,IAAI;EACRC,MAAM,EAAE,IAAI;EACZC,OAAO,EAAE,KAAK;EACdC,IAAI,EAAE,MAAM;EACZC,IAAI,EAAE,MAAM;EACZC,MAAM,EAAE,cAAc;EACtBC,KAAK,EAAE,OAAO;EACdd,MAAM,EAAE,QAAQ;EAChBe,OAAO,EAAE;AACX,CAAU","ignoreList":[]}

View File

@@ -0,0 +1,8 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
module.exports = {};

View File

@@ -0,0 +1,52 @@
{
"name": "ieee754",
"description": "Read/write IEEE754 floating point numbers from/to a Buffer or array-like object",
"version": "1.2.1",
"author": {
"name": "Feross Aboukhadijeh",
"email": "feross@feross.org",
"url": "https://feross.org"
},
"contributors": [
"Romain Beauxis <toots@rastageeks.org>"
],
"devDependencies": {
"airtap": "^3.0.0",
"standard": "*",
"tape": "^5.0.1"
},
"keywords": [
"IEEE 754",
"buffer",
"convert",
"floating point",
"ieee754"
],
"license": "BSD-3-Clause",
"main": "index.js",
"types": "index.d.ts",
"repository": {
"type": "git",
"url": "git://github.com/feross/ieee754.git"
},
"scripts": {
"test": "standard && npm run test-node && npm run test-browser",
"test-browser": "airtap -- test/*.js",
"test-browser-local": "airtap --local -- test/*.js",
"test-node": "tape test/*.js"
},
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
]
}

View File

@@ -0,0 +1 @@
{"version":3,"names":["_classCheckPrivateStaticFieldDescriptor","descriptor","action","undefined","TypeError"],"sources":["../../src/helpers/classCheckPrivateStaticFieldDescriptor.js"],"sourcesContent":["/* @minVersion 7.13.10 */\n/* @onlyBabel7 */\n\nexport default function _classCheckPrivateStaticFieldDescriptor(\n descriptor,\n action,\n) {\n if (descriptor === undefined) {\n throw new TypeError(\n \"attempted to \" + action + \" private static field before its declaration\",\n );\n }\n}\n"],"mappings":";;;;;;AAGe,SAASA,uCAAuCA,CAC7DC,UAAU,EACVC,MAAM,EACN;EACA,IAAID,UAAU,KAAKE,SAAS,EAAE;IAC5B,MAAM,IAAIC,SAAS,CACjB,eAAe,GAAGF,MAAM,GAAG,8CAC7B,CAAC;EACH;AACF","ignoreList":[]}

View File

@@ -0,0 +1 @@
{"version":3,"names":["_cloneNode","require","clone","node","cloneNode"],"sources":["../../src/clone/clone.ts"],"sourcesContent":["import cloneNode from \"./cloneNode.ts\";\nimport type * as t from \"../index.ts\";\n\n/**\n * Create a shallow clone of a `node`, including only\n * properties belonging to the node.\n * @deprecated Use t.cloneNode instead.\n */\nexport default function clone<T extends t.Node>(node: T): T {\n return cloneNode(node, /* deep */ false);\n}\n"],"mappings":";;;;;;AAAA,IAAAA,UAAA,GAAAC,OAAA;AAQe,SAASC,KAAKA,CAAmBC,IAAO,EAAK;EAC1D,OAAO,IAAAC,kBAAS,EAACD,IAAI,EAAa,KAAK,CAAC;AAC1C","ignoreList":[]}

View File

@@ -0,0 +1,125 @@
[Build]: http://img.shields.io/travis/litejs/natural-compare-lite.png
[Coverage]: http://img.shields.io/coveralls/litejs/natural-compare-lite.png
[1]: https://travis-ci.org/litejs/natural-compare-lite
[2]: https://coveralls.io/r/litejs/natural-compare-lite
[npm package]: https://npmjs.org/package/natural-compare-lite
[GitHub repo]: https://github.com/litejs/natural-compare-lite
@version 1.4.0
@date 2015-10-26
@stability 3 - Stable
Natural Compare &ndash; [![Build][]][1] [![Coverage][]][2]
===============
Compare strings containing a mix of letters and numbers
in the way a human being would in sort order.
This is described as a "natural ordering".
```text
Standard sorting: Natural order sorting:
img1.png img1.png
img10.png img2.png
img12.png img10.png
img2.png img12.png
```
String.naturalCompare returns a number indicating
whether a reference string comes before or after or is the same
as the given string in sort order.
Use it with builtin sort() function.
### Installation
- In browser
```html
<script src=min.natural-compare.js></script>
```
- In node.js: `npm install natural-compare-lite`
```javascript
require("natural-compare-lite")
```
### Usage
```javascript
// Simple case sensitive example
var a = ["z1.doc", "z10.doc", "z17.doc", "z2.doc", "z23.doc", "z3.doc"];
a.sort(String.naturalCompare);
// ["z1.doc", "z2.doc", "z3.doc", "z10.doc", "z17.doc", "z23.doc"]
// Use wrapper function for case insensitivity
a.sort(function(a, b){
return String.naturalCompare(a.toLowerCase(), b.toLowerCase());
})
// In most cases we want to sort an array of objects
var a = [ {"street":"350 5th Ave", "room":"A-1021"}
, {"street":"350 5th Ave", "room":"A-21046-b"} ];
// sort by street, then by room
a.sort(function(a, b){
return String.naturalCompare(a.street, b.street) || String.naturalCompare(a.room, b.room);
})
// When text transformation is needed (eg toLowerCase()),
// it is best for performance to keep
// transformed key in that object.
// There are no need to do text transformation
// on each comparision when sorting.
var a = [ {"make":"Audi", "model":"A6"}
, {"make":"Kia", "model":"Rio"} ];
// sort by make, then by model
a.map(function(car){
car.sort_key = (car.make + " " + car.model).toLowerCase();
})
a.sort(function(a, b){
return String.naturalCompare(a.sort_key, b.sort_key);
})
```
- Works well with dates in ISO format eg "Rev 2012-07-26.doc".
### Custom alphabet
It is possible to configure a custom alphabet
to achieve a desired order.
```javascript
// Estonian alphabet
String.alphabet = "ABDEFGHIJKLMNOPRSŠZŽTUVÕÄÖÜXYabdefghijklmnoprsšzžtuvõäöüxy"
["t", "z", "x", "õ"].sort(String.naturalCompare)
// ["z", "t", "õ", "x"]
// Russian alphabet
String.alphabet = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя"
["Ё", "А", "Б"].sort(String.naturalCompare)
// ["А", "Б", "Ё"]
```
External links
--------------
- [GitHub repo][https://github.com/litejs/natural-compare-lite]
- [jsperf test](http://jsperf.com/natural-sort-2/12)
Licence
-------
Copyright (c) 2012-2015 Lauri Rooden &lt;lauri@rooden.ee&gt;
[The MIT License](http://lauri.rooden.ee/mit-license.txt)

View File

@@ -0,0 +1,720 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.TSAnyKeyword = TSAnyKeyword;
exports.TSArrayType = TSArrayType;
exports.TSSatisfiesExpression = exports.TSAsExpression = TSTypeExpression;
exports.TSBigIntKeyword = TSBigIntKeyword;
exports.TSBooleanKeyword = TSBooleanKeyword;
exports.TSCallSignatureDeclaration = TSCallSignatureDeclaration;
exports.TSInterfaceHeritage = exports.TSClassImplements = TSClassImplements;
exports.TSConditionalType = TSConditionalType;
exports.TSConstructSignatureDeclaration = TSConstructSignatureDeclaration;
exports.TSConstructorType = TSConstructorType;
exports.TSDeclareFunction = TSDeclareFunction;
exports.TSDeclareMethod = TSDeclareMethod;
exports.TSEnumBody = TSEnumBody;
exports.TSEnumDeclaration = TSEnumDeclaration;
exports.TSEnumMember = TSEnumMember;
exports.TSExportAssignment = TSExportAssignment;
exports.TSExternalModuleReference = TSExternalModuleReference;
exports.TSFunctionType = TSFunctionType;
exports.TSImportEqualsDeclaration = TSImportEqualsDeclaration;
exports.TSImportType = TSImportType;
exports.TSIndexSignature = TSIndexSignature;
exports.TSIndexedAccessType = TSIndexedAccessType;
exports.TSInferType = TSInferType;
exports.TSInstantiationExpression = TSInstantiationExpression;
exports.TSInterfaceBody = TSInterfaceBody;
exports.TSInterfaceDeclaration = TSInterfaceDeclaration;
exports.TSIntersectionType = TSIntersectionType;
exports.TSIntrinsicKeyword = TSIntrinsicKeyword;
exports.TSLiteralType = TSLiteralType;
exports.TSMappedType = TSMappedType;
exports.TSMethodSignature = TSMethodSignature;
exports.TSModuleBlock = TSModuleBlock;
exports.TSModuleDeclaration = TSModuleDeclaration;
exports.TSNamedTupleMember = TSNamedTupleMember;
exports.TSNamespaceExportDeclaration = TSNamespaceExportDeclaration;
exports.TSNeverKeyword = TSNeverKeyword;
exports.TSNonNullExpression = TSNonNullExpression;
exports.TSNullKeyword = TSNullKeyword;
exports.TSNumberKeyword = TSNumberKeyword;
exports.TSObjectKeyword = TSObjectKeyword;
exports.TSOptionalType = TSOptionalType;
exports.TSParameterProperty = TSParameterProperty;
exports.TSParenthesizedType = TSParenthesizedType;
exports.TSPropertySignature = TSPropertySignature;
exports.TSQualifiedName = TSQualifiedName;
exports.TSRestType = TSRestType;
exports.TSStringKeyword = TSStringKeyword;
exports.TSSymbolKeyword = TSSymbolKeyword;
exports.TSTemplateLiteralType = TSTemplateLiteralType;
exports.TSThisType = TSThisType;
exports.TSTupleType = TSTupleType;
exports.TSTypeAliasDeclaration = TSTypeAliasDeclaration;
exports.TSTypeAnnotation = TSTypeAnnotation;
exports.TSTypeAssertion = TSTypeAssertion;
exports.TSTypeLiteral = TSTypeLiteral;
exports.TSTypeOperator = TSTypeOperator;
exports.TSTypeParameter = TSTypeParameter;
exports.TSTypeParameterDeclaration = exports.TSTypeParameterInstantiation = TSTypeParameterInstantiation;
exports.TSTypePredicate = TSTypePredicate;
exports.TSTypeQuery = TSTypeQuery;
exports.TSTypeReference = TSTypeReference;
exports.TSUndefinedKeyword = TSUndefinedKeyword;
exports.TSUnionType = TSUnionType;
exports.TSUnknownKeyword = TSUnknownKeyword;
exports.TSVoidKeyword = TSVoidKeyword;
exports.tsPrintClassMemberModifiers = tsPrintClassMemberModifiers;
exports.tsPrintFunctionOrConstructorType = tsPrintFunctionOrConstructorType;
exports.tsPrintPropertyOrMethodName = tsPrintPropertyOrMethodName;
exports.tsPrintSignatureDeclarationBase = tsPrintSignatureDeclarationBase;
function TSTypeAnnotation(node, parent) {
this.token((parent.type === "TSFunctionType" || parent.type === "TSConstructorType") && parent.typeAnnotation === node ? "=>" : ":");
this.space();
if (node.optional) this.tokenChar(63);
this.print(node.typeAnnotation);
}
function TSTypeParameterInstantiation(node, parent) {
this.tokenChar(60);
let printTrailingSeparator = parent.type === "ArrowFunctionExpression" && node.params.length === 1;
if (this.tokenMap && node.start != null && node.end != null) {
printTrailingSeparator && (printTrailingSeparator = !!this.tokenMap.find(node, t => this.tokenMap.matchesOriginal(t, ",")));
printTrailingSeparator || (printTrailingSeparator = this.shouldPrintTrailingComma(">"));
}
this.printList(node.params, printTrailingSeparator);
this.tokenChar(62);
}
function TSTypeParameter(node) {
if (node.in) {
this.word("in");
this.space();
}
if (node.out) {
this.word("out");
this.space();
}
this.word(node.name);
if (node.constraint) {
this.space();
this.word("extends");
this.space();
this.print(node.constraint);
}
if (node.default) {
this.space();
this.tokenChar(61);
this.space();
this.print(node.default);
}
}
function TSParameterProperty(node) {
if (node.accessibility) {
this.word(node.accessibility);
this.space();
}
if (node.readonly) {
this.word("readonly");
this.space();
}
this._param(node.parameter);
}
function TSDeclareFunction(node, parent) {
if (node.declare) {
this.word("declare");
this.space();
}
this._functionHead(node, parent);
this.semicolon();
}
function TSDeclareMethod(node) {
this._classMethodHead(node);
this.semicolon();
}
function TSQualifiedName(node) {
this.print(node.left);
this.tokenChar(46);
this.print(node.right);
}
function TSCallSignatureDeclaration(node) {
this.tsPrintSignatureDeclarationBase(node);
maybePrintTrailingCommaOrSemicolon(this, node);
}
function maybePrintTrailingCommaOrSemicolon(printer, node) {
if (!printer.tokenMap || !node.start || !node.end) {
printer.semicolon();
return;
}
if (printer.tokenMap.endMatches(node, ",")) {
printer.token(",");
} else if (printer.tokenMap.endMatches(node, ";")) {
printer.semicolon();
}
}
function TSConstructSignatureDeclaration(node) {
this.word("new");
this.space();
this.tsPrintSignatureDeclarationBase(node);
maybePrintTrailingCommaOrSemicolon(this, node);
}
function TSPropertySignature(node) {
const {
readonly
} = node;
if (readonly) {
this.word("readonly");
this.space();
}
this.tsPrintPropertyOrMethodName(node);
this.print(node.typeAnnotation);
maybePrintTrailingCommaOrSemicolon(this, node);
}
function tsPrintPropertyOrMethodName(node) {
if (node.computed) {
this.tokenChar(91);
}
this.print(node.key);
if (node.computed) {
this.tokenChar(93);
}
if (node.optional) {
this.tokenChar(63);
}
}
function TSMethodSignature(node) {
const {
kind
} = node;
if (kind === "set" || kind === "get") {
this.word(kind);
this.space();
}
this.tsPrintPropertyOrMethodName(node);
this.tsPrintSignatureDeclarationBase(node);
maybePrintTrailingCommaOrSemicolon(this, node);
}
function TSIndexSignature(node) {
const {
readonly,
static: isStatic
} = node;
if (isStatic) {
this.word("static");
this.space();
}
if (readonly) {
this.word("readonly");
this.space();
}
this.tokenChar(91);
this._parameters(node.parameters, "]");
this.print(node.typeAnnotation);
maybePrintTrailingCommaOrSemicolon(this, node);
}
function TSAnyKeyword() {
this.word("any");
}
function TSBigIntKeyword() {
this.word("bigint");
}
function TSUnknownKeyword() {
this.word("unknown");
}
function TSNumberKeyword() {
this.word("number");
}
function TSObjectKeyword() {
this.word("object");
}
function TSBooleanKeyword() {
this.word("boolean");
}
function TSStringKeyword() {
this.word("string");
}
function TSSymbolKeyword() {
this.word("symbol");
}
function TSVoidKeyword() {
this.word("void");
}
function TSUndefinedKeyword() {
this.word("undefined");
}
function TSNullKeyword() {
this.word("null");
}
function TSNeverKeyword() {
this.word("never");
}
function TSIntrinsicKeyword() {
this.word("intrinsic");
}
function TSThisType() {
this.word("this");
}
function TSFunctionType(node) {
this.tsPrintFunctionOrConstructorType(node);
}
function TSConstructorType(node) {
if (node.abstract) {
this.word("abstract");
this.space();
}
this.word("new");
this.space();
this.tsPrintFunctionOrConstructorType(node);
}
function tsPrintFunctionOrConstructorType(node) {
const {
typeParameters
} = node;
const parameters = node.parameters;
this.print(typeParameters);
this.tokenChar(40);
this._parameters(parameters, ")");
this.space();
const returnType = node.typeAnnotation;
this.print(returnType);
}
function TSTypeReference(node) {
const typeArguments = node.typeParameters;
this.print(node.typeName, !!typeArguments);
this.print(typeArguments);
}
function TSTypePredicate(node) {
if (node.asserts) {
this.word("asserts");
this.space();
}
this.print(node.parameterName);
if (node.typeAnnotation) {
this.space();
this.word("is");
this.space();
this.print(node.typeAnnotation.typeAnnotation);
}
}
function TSTypeQuery(node) {
this.word("typeof");
this.space();
this.print(node.exprName);
const typeArguments = node.typeParameters;
if (typeArguments) {
this.print(typeArguments);
}
}
function TSTypeLiteral(node) {
printBraced(this, node, () => this.printJoin(node.members, true, true));
}
function TSArrayType(node) {
this.print(node.elementType, true);
this.tokenChar(91);
this.tokenChar(93);
}
function TSTupleType(node) {
this.tokenChar(91);
this.printList(node.elementTypes, this.shouldPrintTrailingComma("]"));
this.tokenChar(93);
}
function TSOptionalType(node) {
this.print(node.typeAnnotation);
this.tokenChar(63);
}
function TSRestType(node) {
this.token("...");
this.print(node.typeAnnotation);
}
function TSNamedTupleMember(node) {
this.print(node.label);
if (node.optional) this.tokenChar(63);
this.tokenChar(58);
this.space();
this.print(node.elementType);
}
function TSUnionType(node) {
tsPrintUnionOrIntersectionType(this, node, "|");
}
function TSIntersectionType(node) {
tsPrintUnionOrIntersectionType(this, node, "&");
}
function tsPrintUnionOrIntersectionType(printer, node, sep) {
var _printer$tokenMap;
let hasLeadingToken = 0;
if ((_printer$tokenMap = printer.tokenMap) != null && _printer$tokenMap.startMatches(node, sep)) {
hasLeadingToken = 1;
printer.token(sep);
}
printer.printJoin(node.types, undefined, undefined, function (i) {
this.space();
this.token(sep, null, i + hasLeadingToken);
this.space();
});
}
function TSConditionalType(node) {
this.print(node.checkType);
this.space();
this.word("extends");
this.space();
this.print(node.extendsType);
this.space();
this.tokenChar(63);
this.space();
this.print(node.trueType);
this.space();
this.tokenChar(58);
this.space();
this.print(node.falseType);
}
function TSInferType(node) {
this.word("infer");
this.print(node.typeParameter);
}
function TSParenthesizedType(node) {
this.tokenChar(40);
this.print(node.typeAnnotation);
this.tokenChar(41);
}
function TSTypeOperator(node) {
this.word(node.operator);
this.space();
this.print(node.typeAnnotation);
}
function TSIndexedAccessType(node) {
this.print(node.objectType, true);
this.tokenChar(91);
this.print(node.indexType);
this.tokenChar(93);
}
function TSMappedType(node) {
const {
nameType,
optional,
readonly,
typeAnnotation
} = node;
this.tokenChar(123);
const exit = this.enterDelimited();
this.space();
if (readonly) {
tokenIfPlusMinus(this, readonly);
this.word("readonly");
this.space();
}
this.tokenChar(91);
{
this.word(node.typeParameter.name);
}
this.space();
this.word("in");
this.space();
{
this.print(node.typeParameter.constraint);
}
if (nameType) {
this.space();
this.word("as");
this.space();
this.print(nameType);
}
this.tokenChar(93);
if (optional) {
tokenIfPlusMinus(this, optional);
this.tokenChar(63);
}
if (typeAnnotation) {
this.tokenChar(58);
this.space();
this.print(typeAnnotation);
}
this.space();
exit();
this.tokenChar(125);
}
function tokenIfPlusMinus(self, tok) {
if (tok !== true) {
self.token(tok);
}
}
function TSTemplateLiteralType(node) {
this._printTemplate(node, node.types);
}
function TSLiteralType(node) {
this.print(node.literal);
}
function TSClassImplements(node) {
this.print(node.expression);
this.print(node.typeArguments);
}
function TSInterfaceDeclaration(node) {
const {
declare,
id,
typeParameters,
extends: extendz,
body
} = node;
if (declare) {
this.word("declare");
this.space();
}
this.word("interface");
this.space();
this.print(id);
this.print(typeParameters);
if (extendz != null && extendz.length) {
this.space();
this.word("extends");
this.space();
this.printList(extendz);
}
this.space();
this.print(body);
}
function TSInterfaceBody(node) {
printBraced(this, node, () => this.printJoin(node.body, true, true));
}
function TSTypeAliasDeclaration(node) {
const {
declare,
id,
typeParameters,
typeAnnotation
} = node;
if (declare) {
this.word("declare");
this.space();
}
this.word("type");
this.space();
this.print(id);
this.print(typeParameters);
this.space();
this.tokenChar(61);
this.space();
this.print(typeAnnotation);
this.semicolon();
}
function TSTypeExpression(node) {
const {
type,
expression,
typeAnnotation
} = node;
this.print(expression, true);
this.space();
this.word(type === "TSAsExpression" ? "as" : "satisfies");
this.space();
this.print(typeAnnotation);
}
function TSTypeAssertion(node) {
const {
typeAnnotation,
expression
} = node;
this.tokenChar(60);
this.print(typeAnnotation);
this.tokenChar(62);
this.space();
this.print(expression);
}
function TSInstantiationExpression(node) {
this.print(node.expression);
{
this.print(node.typeParameters);
}
}
function TSEnumDeclaration(node) {
const {
declare,
const: isConst,
id
} = node;
if (declare) {
this.word("declare");
this.space();
}
if (isConst) {
this.word("const");
this.space();
}
this.word("enum");
this.space();
this.print(id);
this.space();
{
TSEnumBody.call(this, node);
}
}
function TSEnumBody(node) {
printBraced(this, node, () => {
var _this$shouldPrintTrai;
return this.printList(node.members, (_this$shouldPrintTrai = this.shouldPrintTrailingComma("}")) != null ? _this$shouldPrintTrai : true, true, true);
});
}
function TSEnumMember(node) {
const {
id,
initializer
} = node;
this.print(id);
if (initializer) {
this.space();
this.tokenChar(61);
this.space();
this.print(initializer);
}
}
function TSModuleDeclaration(node) {
const {
declare,
id,
kind
} = node;
if (declare) {
this.word("declare");
this.space();
}
{
if (!node.global) {
this.word(kind != null ? kind : id.type === "Identifier" ? "namespace" : "module");
this.space();
}
this.print(id);
if (!node.body) {
this.semicolon();
return;
}
let body = node.body;
while (body.type === "TSModuleDeclaration") {
this.tokenChar(46);
this.print(body.id);
body = body.body;
}
this.space();
this.print(body);
}
}
function TSModuleBlock(node) {
printBraced(this, node, () => this.printSequence(node.body, true));
}
function TSImportType(node) {
const {
argument,
qualifier,
options
} = node;
this.word("import");
this.tokenChar(40);
this.print(argument);
if (options) {
this.tokenChar(44);
this.print(options);
}
this.tokenChar(41);
if (qualifier) {
this.tokenChar(46);
this.print(qualifier);
}
const typeArguments = node.typeParameters;
if (typeArguments) {
this.print(typeArguments);
}
}
function TSImportEqualsDeclaration(node) {
const {
id,
moduleReference
} = node;
if (node.isExport) {
this.word("export");
this.space();
}
this.word("import");
this.space();
this.print(id);
this.space();
this.tokenChar(61);
this.space();
this.print(moduleReference);
this.semicolon();
}
function TSExternalModuleReference(node) {
this.token("require(");
this.print(node.expression);
this.tokenChar(41);
}
function TSNonNullExpression(node) {
this.print(node.expression);
this.tokenChar(33);
}
function TSExportAssignment(node) {
this.word("export");
this.space();
this.tokenChar(61);
this.space();
this.print(node.expression);
this.semicolon();
}
function TSNamespaceExportDeclaration(node) {
this.word("export");
this.space();
this.word("as");
this.space();
this.word("namespace");
this.space();
this.print(node.id);
this.semicolon();
}
function tsPrintSignatureDeclarationBase(node) {
const {
typeParameters
} = node;
const parameters = node.parameters;
this.print(typeParameters);
this.tokenChar(40);
this._parameters(parameters, ")");
const returnType = node.typeAnnotation;
this.print(returnType);
}
function tsPrintClassMemberModifiers(node) {
const isPrivateField = node.type === "ClassPrivateProperty";
const isPublicField = node.type === "ClassAccessorProperty" || node.type === "ClassProperty";
printModifiersList(this, node, [isPublicField && node.declare && "declare", !isPrivateField && node.accessibility]);
if (node.static) {
this.word("static");
this.space();
}
printModifiersList(this, node, [!isPrivateField && node.abstract && "abstract", !isPrivateField && node.override && "override", (isPublicField || isPrivateField) && node.readonly && "readonly"]);
}
function printBraced(printer, node, cb) {
printer.token("{");
const exit = printer.enterDelimited();
cb();
exit();
printer.rightBrace(node);
}
function printModifiersList(printer, node, modifiers) {
var _printer$tokenMap2;
const modifiersSet = new Set();
for (const modifier of modifiers) {
if (modifier) modifiersSet.add(modifier);
}
(_printer$tokenMap2 = printer.tokenMap) == null || _printer$tokenMap2.find(node, tok => {
if (modifiersSet.has(tok.value)) {
printer.token(tok.value);
printer.space();
modifiersSet.delete(tok.value);
return modifiersSet.size === 0;
}
});
for (const modifier of modifiersSet) {
printer.word(modifier);
printer.space();
}
}
//# sourceMappingURL=typescript.js.map

View File

@@ -0,0 +1,20 @@
(The MIT License)
Copyright (c) 2014-2017 TJ Holowaychuk <tj@vision-media.ca>
Copyright (c) 2018-2021 Josh Junon
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

@@ -0,0 +1 @@
{"version":3,"names":["_objectWithoutPropertiesLoose","require","_objectWithoutProperties","source","excluded","target","objectWithoutPropertiesLoose","key","i","Object","getOwnPropertySymbols","sourceSymbolKeys","length","indexOf","prototype","propertyIsEnumerable","call"],"sources":["../../src/helpers/objectWithoutProperties.ts"],"sourcesContent":["/* @minVersion 7.0.0-beta.0 */\n\nimport objectWithoutPropertiesLoose from \"./objectWithoutPropertiesLoose.ts\";\n\nexport default function _objectWithoutProperties(\n source: null | undefined,\n excluded: PropertyKey[],\n): Record<string, never>;\nexport default function _objectWithoutProperties<\n T extends object,\n K extends PropertyKey[],\n>(\n source: T | null | undefined,\n excluded: K,\n): Pick<T, Exclude<keyof T, K[number]>>;\nexport default function _objectWithoutProperties<\n T extends object,\n K extends PropertyKey[],\n>(\n source: T | null | undefined,\n excluded: K,\n): Pick<T, Exclude<keyof T, K[number]>> | Record<string, never> {\n if (source == null) return {};\n\n var target = objectWithoutPropertiesLoose(source, excluded);\n var key, i;\n\n if (Object.getOwnPropertySymbols) {\n var sourceSymbolKeys = Object.getOwnPropertySymbols(source);\n for (i = 0; i < sourceSymbolKeys.length; i++) {\n key = sourceSymbolKeys[i] as keyof typeof source & keyof typeof target;\n if (excluded.indexOf(key) !== -1) continue;\n if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;\n target[key] = source[key];\n }\n }\n\n return target;\n}\n"],"mappings":";;;;;;AAEA,IAAAA,6BAAA,GAAAC,OAAA;AAae,SAASC,wBAAwBA,CAI9CC,MAA4B,EAC5BC,QAAW,EACmD;EAC9D,IAAID,MAAM,IAAI,IAAI,EAAE,OAAO,CAAC,CAAC;EAE7B,IAAIE,MAAM,GAAG,IAAAC,qCAA4B,EAACH,MAAM,EAAEC,QAAQ,CAAC;EAC3D,IAAIG,GAAG,EAAEC,CAAC;EAEV,IAAIC,MAAM,CAACC,qBAAqB,EAAE;IAChC,IAAIC,gBAAgB,GAAGF,MAAM,CAACC,qBAAqB,CAACP,MAAM,CAAC;IAC3D,KAAKK,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGG,gBAAgB,CAACC,MAAM,EAAEJ,CAAC,EAAE,EAAE;MAC5CD,GAAG,GAAGI,gBAAgB,CAACH,CAAC,CAA8C;MACtE,IAAIJ,QAAQ,CAACS,OAAO,CAACN,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE;MAClC,IAAI,CAACE,MAAM,CAACK,SAAS,CAACC,oBAAoB,CAACC,IAAI,CAACb,MAAM,EAAEI,GAAG,CAAC,EAAE;MAC9DF,MAAM,CAACE,GAAG,CAAC,GAAGJ,MAAM,CAACI,GAAG,CAAC;IAC3B;EACF;EAEA,OAAOF,MAAM;AACf","ignoreList":[]}

View File

@@ -0,0 +1 @@
module.exports={A:{A:{"2":"K D E F A B mC"},B:{"1":"0 9 L M G N O P Q H R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB I","132":"C"},C:{"2":"1 2 3 4 5 6 7 8 nC LC J PB K D E F A B C L M G N O P QB RB SB TB UB VB WB XB YB ZB aB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qC rC","1090":"qB rB sB tB","2052":"uB vB MC wB NC xB yB zB 0B 1B 2B 3B 4B 5B 6B 7B 8B 9B AC BC CC DC Q H R OC S T U V W X Y Z a b","4100":"0 9 c d e f g h i j k l m n o p q r s t u v w x y z AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB I PC EC QC RC oC pC"},D:{"1":"0 6 7 8 9 RB SB TB UB VB WB XB YB ZB aB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qB rB sB tB uB vB MC wB NC xB yB zB 0B 1B 2B 3B 4B 5B 6B 7B 8B 9B AC BC CC DC Q H R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB I PC EC QC RC","2":"J PB K D E F A B C L M G N O P QB","2052":"1 2 3 4 5"},E:{"2":"J PB K D E F A B C L M sC SC tC uC vC wC TC FC GC xC","4100":"G yC zC UC VC HC 0C IC WC XC YC ZC aC 1C JC bC cC dC eC fC 2C KC gC hC iC jC 3C"},F:{"1":"0 1 2 3 4 5 6 7 8 F B C G N O P QB RB SB TB UB VB WB XB YB ZB aB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qB rB sB tB uB vB wB xB yB zB 0B 1B 2B 3B 4B 5B 6B 7B 8B 9B AC BC CC DC Q H R OC S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z 4C 5C 6C 7C FC kC 8C GC"},G:{"2":"SC 9C lC","260":"E AD BD CD DD ED FD GD HD ID JD KD LD MD ND OD PD QD RD SD UC VC HC TD IC WC XC YC ZC aC UD JC bC cC dC eC fC VD KC gC","8193":"hC iC jC"},H:{"2":"WD"},I:{"1":"I bD cD","2":"LC XD YD ZD","514":"J aD lC"},J:{"1":"A","2":"D"},K:{"1":"A B C H FC kC GC"},L:{"1":"I"},M:{"4100":"EC"},N:{"2":"A B"},O:{"1":"HC"},P:{"1":"1 2 3 4 5 6 7 8 J dD eD fD gD hD TC iD jD kD lD mD IC JC KC nD"},Q:{"1":"oD"},R:{"1":"pD"},S:{"2052":"qD rD"}},B:1,C:"Date and time input types",D:true};

View File

@@ -0,0 +1,297 @@
/**
* @fileoverview Validates spacing before and after semicolon
* @author Mathias Schreck
* @deprecated in ESLint v8.53.0
*/
"use strict";
const astUtils = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../shared/types').Rule} */
module.exports = {
meta: {
deprecated: {
message: "Formatting rules are being moved out of ESLint core.",
url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/",
deprecatedSince: "8.53.0",
availableUntil: "10.0.0",
replacedBy: [
{
message:
"ESLint Stylistic now maintains deprecated stylistic core rules.",
url: "https://eslint.style/guide/migration",
plugin: {
name: "@stylistic/eslint-plugin-js",
url: "https://eslint.style/packages/js",
},
rule: {
name: "semi-spacing",
url: "https://eslint.style/rules/js/semi-spacing",
},
},
],
},
type: "layout",
docs: {
description:
"Enforce consistent spacing before and after semicolons",
recommended: false,
url: "https://eslint.org/docs/latest/rules/semi-spacing",
},
fixable: "whitespace",
schema: [
{
type: "object",
properties: {
before: {
type: "boolean",
default: false,
},
after: {
type: "boolean",
default: true,
},
},
additionalProperties: false,
},
],
messages: {
unexpectedWhitespaceBefore:
"Unexpected whitespace before semicolon.",
unexpectedWhitespaceAfter: "Unexpected whitespace after semicolon.",
missingWhitespaceBefore: "Missing whitespace before semicolon.",
missingWhitespaceAfter: "Missing whitespace after semicolon.",
},
},
create(context) {
const config = context.options[0],
sourceCode = context.sourceCode;
let requireSpaceBefore = false,
requireSpaceAfter = true;
if (typeof config === "object") {
requireSpaceBefore = config.before;
requireSpaceAfter = config.after;
}
/**
* Checks if a given token has leading whitespace.
* @param {Object} token The token to check.
* @returns {boolean} True if the given token has leading space, false if not.
*/
function hasLeadingSpace(token) {
const tokenBefore = sourceCode.getTokenBefore(token);
return (
tokenBefore &&
astUtils.isTokenOnSameLine(tokenBefore, token) &&
sourceCode.isSpaceBetweenTokens(tokenBefore, token)
);
}
/**
* Checks if a given token has trailing whitespace.
* @param {Object} token The token to check.
* @returns {boolean} True if the given token has trailing space, false if not.
*/
function hasTrailingSpace(token) {
const tokenAfter = sourceCode.getTokenAfter(token);
return (
tokenAfter &&
astUtils.isTokenOnSameLine(token, tokenAfter) &&
sourceCode.isSpaceBetweenTokens(token, tokenAfter)
);
}
/**
* Checks if the given token is the last token in its line.
* @param {Token} token The token to check.
* @returns {boolean} Whether or not the token is the last in its line.
*/
function isLastTokenInCurrentLine(token) {
const tokenAfter = sourceCode.getTokenAfter(token);
return !(
tokenAfter && astUtils.isTokenOnSameLine(token, tokenAfter)
);
}
/**
* Checks if the given token is the first token in its line
* @param {Token} token The token to check.
* @returns {boolean} Whether or not the token is the first in its line.
*/
function isFirstTokenInCurrentLine(token) {
const tokenBefore = sourceCode.getTokenBefore(token);
return !(
tokenBefore && astUtils.isTokenOnSameLine(token, tokenBefore)
);
}
/**
* Checks if the next token of a given token is a closing parenthesis.
* @param {Token} token The token to check.
* @returns {boolean} Whether or not the next token of a given token is a closing parenthesis.
*/
function isBeforeClosingParen(token) {
const nextToken = sourceCode.getTokenAfter(token);
return (
(nextToken && astUtils.isClosingBraceToken(nextToken)) ||
astUtils.isClosingParenToken(nextToken)
);
}
/**
* Report location example :
*
* for unexpected space `before`
*
* var a = 'b' ;
* ^^^
*
* for unexpected space `after`
*
* var a = 'b'; c = 10;
* ^^
*
* Reports if the given token has invalid spacing.
* @param {Token} token The semicolon token to check.
* @param {ASTNode} node The corresponding node of the token.
* @returns {void}
*/
function checkSemicolonSpacing(token, node) {
if (astUtils.isSemicolonToken(token)) {
if (hasLeadingSpace(token)) {
if (!requireSpaceBefore) {
const tokenBefore = sourceCode.getTokenBefore(token);
const loc = {
start: tokenBefore.loc.end,
end: token.loc.start,
};
context.report({
node,
loc,
messageId: "unexpectedWhitespaceBefore",
fix(fixer) {
return fixer.removeRange([
tokenBefore.range[1],
token.range[0],
]);
},
});
}
} else {
if (requireSpaceBefore) {
const loc = token.loc;
context.report({
node,
loc,
messageId: "missingWhitespaceBefore",
fix(fixer) {
return fixer.insertTextBefore(token, " ");
},
});
}
}
if (
!isFirstTokenInCurrentLine(token) &&
!isLastTokenInCurrentLine(token) &&
!isBeforeClosingParen(token)
) {
if (hasTrailingSpace(token)) {
if (!requireSpaceAfter) {
const tokenAfter = sourceCode.getTokenAfter(token);
const loc = {
start: token.loc.end,
end: tokenAfter.loc.start,
};
context.report({
node,
loc,
messageId: "unexpectedWhitespaceAfter",
fix(fixer) {
return fixer.removeRange([
token.range[1],
tokenAfter.range[0],
]);
},
});
}
} else {
if (requireSpaceAfter) {
const loc = token.loc;
context.report({
node,
loc,
messageId: "missingWhitespaceAfter",
fix(fixer) {
return fixer.insertTextAfter(token, " ");
},
});
}
}
}
}
}
/**
* Checks the spacing of the semicolon with the assumption that the last token is the semicolon.
* @param {ASTNode} node The node to check.
* @returns {void}
*/
function checkNode(node) {
const token = sourceCode.getLastToken(node);
checkSemicolonSpacing(token, node);
}
return {
VariableDeclaration: checkNode,
ExpressionStatement: checkNode,
BreakStatement: checkNode,
ContinueStatement: checkNode,
DebuggerStatement: checkNode,
DoWhileStatement: checkNode,
ReturnStatement: checkNode,
ThrowStatement: checkNode,
ImportDeclaration: checkNode,
ExportNamedDeclaration: checkNode,
ExportAllDeclaration: checkNode,
ExportDefaultDeclaration: checkNode,
ForStatement(node) {
if (node.init) {
checkSemicolonSpacing(
sourceCode.getTokenAfter(node.init),
node,
);
}
if (node.test) {
checkSemicolonSpacing(
sourceCode.getTokenAfter(node.test),
node,
);
}
},
PropertyDefinition: checkNode,
};
},
};

View File

@@ -0,0 +1,163 @@
'use strict';
const wrapAnsi16 = (fn, offset) => (...args) => {
const code = fn(...args);
return `\u001B[${code + offset}m`;
};
const wrapAnsi256 = (fn, offset) => (...args) => {
const code = fn(...args);
return `\u001B[${38 + offset};5;${code}m`;
};
const wrapAnsi16m = (fn, offset) => (...args) => {
const rgb = fn(...args);
return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
};
const ansi2ansi = n => n;
const rgb2rgb = (r, g, b) => [r, g, b];
const setLazyProperty = (object, property, get) => {
Object.defineProperty(object, property, {
get: () => {
const value = get();
Object.defineProperty(object, property, {
value,
enumerable: true,
configurable: true
});
return value;
},
enumerable: true,
configurable: true
});
};
/** @type {typeof import('color-convert')} */
let colorConvert;
const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => {
if (colorConvert === undefined) {
colorConvert = require('color-convert');
}
const offset = isBackground ? 10 : 0;
const styles = {};
for (const [sourceSpace, suite] of Object.entries(colorConvert)) {
const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace;
if (sourceSpace === targetSpace) {
styles[name] = wrap(identity, offset);
} else if (typeof suite === 'object') {
styles[name] = wrap(suite[targetSpace], offset);
}
}
return styles;
};
function assembleStyles() {
const codes = new Map();
const styles = {
modifier: {
reset: [0, 0],
// 21 isn't widely supported and 22 does the same thing
bold: [1, 22],
dim: [2, 22],
italic: [3, 23],
underline: [4, 24],
inverse: [7, 27],
hidden: [8, 28],
strikethrough: [9, 29]
},
color: {
black: [30, 39],
red: [31, 39],
green: [32, 39],
yellow: [33, 39],
blue: [34, 39],
magenta: [35, 39],
cyan: [36, 39],
white: [37, 39],
// Bright color
blackBright: [90, 39],
redBright: [91, 39],
greenBright: [92, 39],
yellowBright: [93, 39],
blueBright: [94, 39],
magentaBright: [95, 39],
cyanBright: [96, 39],
whiteBright: [97, 39]
},
bgColor: {
bgBlack: [40, 49],
bgRed: [41, 49],
bgGreen: [42, 49],
bgYellow: [43, 49],
bgBlue: [44, 49],
bgMagenta: [45, 49],
bgCyan: [46, 49],
bgWhite: [47, 49],
// Bright color
bgBlackBright: [100, 49],
bgRedBright: [101, 49],
bgGreenBright: [102, 49],
bgYellowBright: [103, 49],
bgBlueBright: [104, 49],
bgMagentaBright: [105, 49],
bgCyanBright: [106, 49],
bgWhiteBright: [107, 49]
}
};
// Alias bright black as gray (and grey)
styles.color.gray = styles.color.blackBright;
styles.bgColor.bgGray = styles.bgColor.bgBlackBright;
styles.color.grey = styles.color.blackBright;
styles.bgColor.bgGrey = styles.bgColor.bgBlackBright;
for (const [groupName, group] of Object.entries(styles)) {
for (const [styleName, style] of Object.entries(group)) {
styles[styleName] = {
open: `\u001B[${style[0]}m`,
close: `\u001B[${style[1]}m`
};
group[styleName] = styles[styleName];
codes.set(style[0], style[1]);
}
Object.defineProperty(styles, groupName, {
value: group,
enumerable: false
});
}
Object.defineProperty(styles, 'codes', {
value: codes,
enumerable: false
});
styles.color.close = '\u001B[39m';
styles.bgColor.close = '\u001B[49m';
setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false));
setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false));
setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false));
setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true));
setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true));
setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true));
return styles;
}
// Make the export immutable
Object.defineProperty(module, 'exports', {
enumerable: true,
get: assembleStyles
});

View File

@@ -0,0 +1,125 @@
"use strict";
'use client';
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Canvas;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const merge_refs_1 = __importDefault(require("merge-refs"));
const tiny_invariant_1 = __importDefault(require("tiny-invariant"));
const warning_1 = __importDefault(require("warning"));
const pdfjs = __importStar(require("pdfjs-dist"));
const StructTree_js_1 = __importDefault(require("../StructTree.js"));
const usePageContext_js_1 = __importDefault(require("../shared/hooks/usePageContext.js"));
const utils_js_1 = require("../shared/utils.js");
const ANNOTATION_MODE = pdfjs.AnnotationMode;
function Canvas(props) {
const pageContext = (0, usePageContext_js_1.default)();
(0, tiny_invariant_1.default)(pageContext, 'Unable to find Page context.');
const mergedProps = Object.assign(Object.assign({}, pageContext), props);
const { _className, canvasBackground, devicePixelRatio = (0, utils_js_1.getDevicePixelRatio)(), onRenderError: onRenderErrorProps, onRenderSuccess: onRenderSuccessProps, page, renderForms, renderTextLayer, rotate, scale, } = mergedProps;
const { canvasRef } = props;
(0, tiny_invariant_1.default)(page, 'Attempted to render page canvas, but no page was specified.');
const canvasElement = (0, react_1.useRef)(null);
/**
* Called when a page is rendered successfully.
*/
function onRenderSuccess() {
if (!page) {
// Impossible, but TypeScript doesn't know that
return;
}
if (onRenderSuccessProps) {
onRenderSuccessProps((0, utils_js_1.makePageCallback)(page, scale));
}
}
/**
* Called when a page fails to render.
*/
function onRenderError(error) {
if ((0, utils_js_1.isCancelException)(error)) {
return;
}
(0, warning_1.default)(false, error.toString());
if (onRenderErrorProps) {
onRenderErrorProps(error);
}
}
const renderViewport = (0, react_1.useMemo)(() => page.getViewport({ scale: scale * devicePixelRatio, rotation: rotate }), [devicePixelRatio, page, rotate, scale]);
const viewport = (0, react_1.useMemo)(() => page.getViewport({ scale, rotation: rotate }), [page, rotate, scale]);
// biome-ignore lint/correctness/useExhaustiveDependencies: Ommitted callbacks so they are not called every time they change
(0, react_1.useEffect)(function drawPageOnCanvas() {
if (!page) {
return;
}
// Ensures the canvas will be re-rendered from scratch. Otherwise all form data will stay.
page.cleanup();
const { current: canvas } = canvasElement;
if (!canvas) {
return;
}
canvas.width = renderViewport.width;
canvas.height = renderViewport.height;
canvas.style.width = `${Math.floor(viewport.width)}px`;
canvas.style.height = `${Math.floor(viewport.height)}px`;
canvas.style.visibility = 'hidden';
const renderContext = {
annotationMode: renderForms ? ANNOTATION_MODE.ENABLE_FORMS : ANNOTATION_MODE.ENABLE,
canvasContext: canvas.getContext('2d', { alpha: false }),
viewport: renderViewport,
};
if (canvasBackground) {
renderContext.background = canvasBackground;
}
const cancellable = page.render(renderContext);
const runningTask = cancellable;
cancellable.promise
.then(() => {
canvas.style.visibility = '';
onRenderSuccess();
})
.catch(onRenderError);
return () => (0, utils_js_1.cancelRunningTask)(runningTask);
}, [canvasBackground, page, renderForms, renderViewport, viewport]);
const cleanup = (0, react_1.useCallback)(() => {
const { current: canvas } = canvasElement;
/**
* Zeroing the width and height cause most browsers to release graphics
* resources immediately, which can greatly reduce memory consumption.
*/
if (canvas) {
canvas.width = 0;
canvas.height = 0;
}
}, []);
(0, react_1.useEffect)(() => cleanup, [cleanup]);
return ((0, jsx_runtime_1.jsx)("canvas", { className: `${_className}__canvas`, dir: "ltr", ref: (0, merge_refs_1.default)(canvasRef, canvasElement), style: {
display: 'block',
userSelect: 'none',
}, children: renderTextLayer ? (0, jsx_runtime_1.jsx)(StructTree_js_1.default, {}) : null }));
}

View File

@@ -0,0 +1 @@
{"version":3,"names":["_getPrototypeOf","require","_superPropBase","object","property","Object","prototype","hasOwnProperty","call","getPrototypeOf"],"sources":["../../src/helpers/superPropBase.ts"],"sourcesContent":["/* @minVersion 7.0.0-beta.0 */\n\nimport getPrototypeOf from \"./getPrototypeOf.ts\";\n\nexport default function _superPropBase(object: object, property: PropertyKey) {\n // Yes, this throws if object is null to being with, that's on purpose.\n while (!Object.prototype.hasOwnProperty.call(object, property)) {\n object = getPrototypeOf(object);\n if (object === null) break;\n }\n return object;\n}\n"],"mappings":";;;;;;AAEA,IAAAA,eAAA,GAAAC,OAAA;AAEe,SAASC,cAAcA,CAACC,MAAc,EAAEC,QAAqB,EAAE;EAE5E,OAAO,CAACC,MAAM,CAACC,SAAS,CAACC,cAAc,CAACC,IAAI,CAACL,MAAM,EAAEC,QAAQ,CAAC,EAAE;IAC9DD,MAAM,GAAG,IAAAM,uBAAc,EAACN,MAAM,CAAC;IAC/B,IAAIA,MAAM,KAAK,IAAI,EAAE;EACvB;EACA,OAAOA,MAAM;AACf","ignoreList":[]}