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,115 @@
/**
* @fileoverview Rule to enforce a maximum number of nested callbacks.
* @author Ian Christian Myers
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../shared/types').Rule} */
module.exports = {
meta: {
type: "suggestion",
docs: {
description: "Enforce a maximum depth that callbacks can be nested",
recommended: false,
url: "https://eslint.org/docs/latest/rules/max-nested-callbacks",
},
schema: [
{
oneOf: [
{
type: "integer",
minimum: 0,
},
{
type: "object",
properties: {
maximum: {
type: "integer",
minimum: 0,
},
max: {
type: "integer",
minimum: 0,
},
},
additionalProperties: false,
},
],
},
],
messages: {
exceed: "Too many nested callbacks ({{num}}). Maximum allowed is {{max}}.",
},
},
create(context) {
//--------------------------------------------------------------------------
// Constants
//--------------------------------------------------------------------------
const option = context.options[0];
let THRESHOLD = 10;
if (
typeof option === "object" &&
(Object.hasOwn(option, "maximum") || Object.hasOwn(option, "max"))
) {
THRESHOLD = option.maximum || option.max;
} else if (typeof option === "number") {
THRESHOLD = option;
}
//--------------------------------------------------------------------------
// Helpers
//--------------------------------------------------------------------------
const callbackStack = [];
/**
* Checks a given function node for too many callbacks.
* @param {ASTNode} node The node to check.
* @returns {void}
* @private
*/
function checkFunction(node) {
const parent = node.parent;
if (parent.type === "CallExpression") {
callbackStack.push(node);
}
if (callbackStack.length > THRESHOLD) {
const opts = { num: callbackStack.length, max: THRESHOLD };
context.report({ node, messageId: "exceed", data: opts });
}
}
/**
* Pops the call stack.
* @returns {void}
* @private
*/
function popStack() {
callbackStack.pop();
}
//--------------------------------------------------------------------------
// Public API
//--------------------------------------------------------------------------
return {
ArrowFunctionExpression: checkFunction,
"ArrowFunctionExpression:exit": popStack,
FunctionExpression: checkFunction,
"FunctionExpression:exit": popStack,
};
},
};

View File

@@ -0,0 +1,79 @@
import * as React from 'react'
import { Matches } from './Matches'
import { getRouterContext } from './routerContext'
import type {
AnyRouter,
RegisteredRouter,
RouterOptions,
} from '@tanstack/router-core'
export function RouterContextProvider<
TRouter extends AnyRouter = RegisteredRouter,
TDehydrated extends Record<string, any> = Record<string, any>,
>({
router,
children,
...rest
}: RouterProps<TRouter, TDehydrated> & {
children: React.ReactNode
}) {
// Allow the router to update options on the router instance
router.update({
...router.options,
...rest,
context: {
...router.options.context,
...rest.context,
},
} as any)
const routerContext = getRouterContext()
const provider = (
<routerContext.Provider value={router as AnyRouter}>
{children}
</routerContext.Provider>
)
if (router.options.Wrap) {
return <router.options.Wrap>{provider}</router.options.Wrap>
}
return provider
}
export function RouterProvider<
TRouter extends AnyRouter = RegisteredRouter,
TDehydrated extends Record<string, any> = Record<string, any>,
>({ router, ...rest }: RouterProps<TRouter, TDehydrated>) {
return (
<RouterContextProvider router={router} {...rest}>
<Matches />
</RouterContextProvider>
)
}
export type RouterProps<
TRouter extends AnyRouter = RegisteredRouter,
TDehydrated extends Record<string, any> = Record<string, any>,
> = Omit<
RouterOptions<
TRouter['routeTree'],
NonNullable<TRouter['options']['trailingSlash']>,
NonNullable<TRouter['options']['defaultStructuralSharing']>,
TRouter['history'],
TDehydrated
>,
'context'
> & {
router: TRouter
context?: Partial<
RouterOptions<
TRouter['routeTree'],
NonNullable<TRouter['options']['trailingSlash']>,
NonNullable<TRouter['options']['defaultStructuralSharing']>,
TRouter['history'],
TDehydrated
>['context']
>
}

View File

@@ -0,0 +1,66 @@
{
"name": "csstype",
"version": "3.1.3",
"main": "",
"types": "index.d.ts",
"description": "Strict TypeScript and Flow types for style based on MDN data",
"repository": "https://github.com/frenic/csstype",
"author": "Fredrik Nicol <fredrik.nicol@gmail.com>",
"license": "MIT",
"devDependencies": {
"@types/chokidar": "^2.1.3",
"@types/css-tree": "^2.3.1",
"@types/jest": "^29.5.0",
"@types/jsdom": "^21.1.1",
"@types/node": "^16.18.23",
"@types/prettier": "^2.7.2",
"@types/request": "^2.48.8",
"@types/turndown": "^5.0.1",
"@typescript-eslint/eslint-plugin": "^5.57.0",
"@typescript-eslint/parser": "^5.57.0",
"chalk": "^4.1.2",
"chokidar": "^3.5.3",
"eslint": "^8.37.0",
"css-tree": "^2.3.1",
"eslint-config-prettier": "^8.8.0",
"eslint-plugin-prettier": "^4.2.1",
"fast-glob": "^3.2.12",
"flow-bin": "^0.203.1",
"jest": "^29.5.0",
"jsdom": "^21.1.1",
"mdn-browser-compat-data": "git+https://github.com/mdn/browser-compat-data.git#1bf44517bd08de735e9ec20dbfe8e86c96341054",
"mdn-data": "git+https://github.com/mdn/data.git#7f0c865a3c4b5d891285c93308ee5c25cb5cfee8",
"prettier": "^2.8.7",
"request": "^2.88.2",
"ts-jest": "^29.0.5",
"ts-node": "^10.9.1",
"turndown": "^7.1.2",
"typescript": "~5.0.3"
},
"scripts": {
"prepublish": "npm install --prefix __tests__ && npm install --prefix __tests__/__fixtures__",
"prepublishOnly": "tsc && npm run test:src && npm run build && ts-node --files prepublish.ts",
"update": "ts-node --files update.ts",
"build": "ts-node --files build.ts --start",
"watch": "ts-node --files build.ts --watch",
"lint": "eslint . --ext .js,.jsx,.ts,.tsx --fix",
"pretty": "prettier --write build.ts **/*.{ts,js,json,md}",
"lazy": "tsc && npm run lint",
"test": "jest --runInBand",
"test:src": "jest src.*.ts",
"test:dist": "jest dist.*.ts --runInBand"
},
"files": [
"index.d.ts",
"index.js.flow"
],
"keywords": [
"css",
"style",
"typescript",
"flow",
"typings",
"types",
"definitions"
]
}

View File

@@ -0,0 +1 @@
module.exports={A:{A:{"2":"K D E F A B mC"},B:{"2":"C L M G N O P","132":"0 9 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"},C:{"2":"0 1 2 3 4 5 6 7 8 9 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 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 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 AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB I PC EC QC RC oC pC qC rC"},D:{"16":"J PB K D E F A B C L M G","132":"0 1 2 3 4 5 6 7 8 9 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 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"},E:{"1":"J PB K D E F A B C L M G sC SC tC uC vC wC TC FC GC xC 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:{"2":"F B C 4C 5C 6C 7C FC kC 8C GC","132":"0 1 2 3 4 5 6 7 8 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"},G:{"2":"E SC 9C lC 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 hC iC jC"},H:{"2":"WD"},I:{"2":"LC J I XD YD ZD aD lC bD cD"},J:{"2":"D A"},K:{"2":"A B C FC kC GC","132":"H"},L:{"2":"I"},M:{"2":"EC"},N:{"2":"A B"},O:{"2":"HC"},P:{"2":"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:{"2":"oD"},R:{"2":"pD"},S:{"2":"qD rD"}},B:7,C:"CSS -webkit-user-drag property",D:true};

View File

@@ -0,0 +1,5 @@
import { Colors } from "./types"
declare const picocolors: Colors & { createColors: (enabled?: boolean) => Colors }
export = picocolors

View File

@@ -0,0 +1,219 @@
/**
* @fileoverview Rule to count multiple spaces in regular expressions
* @author Matt DuVall <http://www.mattduvall.com/>
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const astUtils = require("./utils/ast-utils");
const regexpp = require("@eslint-community/regexpp");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
const regExpParser = new regexpp.RegExpParser();
const DOUBLE_SPACE = / {2}/u;
/**
* Check if node is a string
* @param {ASTNode} node node to evaluate
* @returns {boolean} True if its a string
* @private
*/
function isString(node) {
return node && node.type === "Literal" && typeof node.value === "string";
}
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../shared/types').Rule} */
module.exports = {
meta: {
type: "suggestion",
docs: {
description: "Disallow multiple spaces in regular expressions",
recommended: true,
url: "https://eslint.org/docs/latest/rules/no-regex-spaces",
},
schema: [],
fixable: "code",
messages: {
multipleSpaces: "Spaces are hard to count. Use {{{length}}}.",
},
},
create(context) {
const sourceCode = context.sourceCode;
/**
* Validate regular expression
* @param {ASTNode} nodeToReport Node to report.
* @param {string} pattern Regular expression pattern to validate.
* @param {string} rawPattern Raw representation of the pattern in the source code.
* @param {number} rawPatternStartRange Start range of the pattern in the source code.
* @param {string} flags Regular expression flags.
* @returns {void}
* @private
*/
function checkRegex(
nodeToReport,
pattern,
rawPattern,
rawPatternStartRange,
flags,
) {
// Skip if there are no consecutive spaces in the source code, to avoid reporting e.g., RegExp(' \ ').
if (!DOUBLE_SPACE.test(rawPattern)) {
return;
}
const characterClassNodes = [];
let regExpAST;
try {
regExpAST = regExpParser.parsePattern(
pattern,
0,
pattern.length,
{
unicode: flags.includes("u"),
unicodeSets: flags.includes("v"),
},
);
} catch {
// Ignore regular expressions with syntax errors
return;
}
regexpp.visitRegExpAST(regExpAST, {
onCharacterClassEnter(ccNode) {
characterClassNodes.push(ccNode);
},
});
const spacesPattern = /( {2,})(?: [+*{?]|[^+*{?]|$)/gu;
let match;
while ((match = spacesPattern.exec(pattern))) {
const {
1: { length },
index,
} = match;
// Report only consecutive spaces that are not in character classes.
if (
characterClassNodes.every(
({ start, end }) => index < start || end <= index,
)
) {
context.report({
node: nodeToReport,
messageId: "multipleSpaces",
data: { length },
fix(fixer) {
if (pattern !== rawPattern) {
return null;
}
return fixer.replaceTextRange(
[
rawPatternStartRange + index,
rawPatternStartRange + index + length,
],
` {${length}}`,
);
},
});
// Report only the first occurrence of consecutive spaces
return;
}
}
}
/**
* Validate regular expression literals
* @param {ASTNode} node node to validate
* @returns {void}
* @private
*/
function checkLiteral(node) {
if (node.regex) {
const pattern = node.regex.pattern;
const rawPattern = node.raw.slice(1, node.raw.lastIndexOf("/"));
const rawPatternStartRange = node.range[0] + 1;
const flags = node.regex.flags;
checkRegex(
node,
pattern,
rawPattern,
rawPatternStartRange,
flags,
);
}
}
/**
* Validate strings passed to the RegExp constructor
* @param {ASTNode} node node to validate
* @returns {void}
* @private
*/
function checkFunction(node) {
const scope = sourceCode.getScope(node);
const regExpVar = astUtils.getVariableByName(scope, "RegExp");
const shadowed = regExpVar && regExpVar.defs.length > 0;
const patternNode = node.arguments[0];
if (
node.callee.type === "Identifier" &&
node.callee.name === "RegExp" &&
isString(patternNode) &&
!shadowed
) {
const pattern = patternNode.value;
const rawPattern = patternNode.raw.slice(1, -1);
const rawPatternStartRange = patternNode.range[0] + 1;
let flags;
if (node.arguments.length < 2) {
// It has no flags.
flags = "";
} else {
const flagsNode = node.arguments[1];
if (isString(flagsNode)) {
flags = flagsNode.value;
} else {
// The flags cannot be determined.
return;
}
}
checkRegex(
node,
pattern,
rawPattern,
rawPatternStartRange,
flags,
);
}
}
return {
Literal: checkLiteral,
CallExpression: checkFunction,
NewExpression: checkFunction,
};
},
};

View File

@@ -0,0 +1,476 @@
/**
* @fileoverview Rule to flag missing semicolons.
* @author Nicholas C. Zakas
* @deprecated in ESLint v8.53.0
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const FixTracker = require("./utils/fix-tracker");
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",
url: "https://eslint.style/rules/js/semi",
},
},
],
},
type: "layout",
docs: {
description: "Require or disallow semicolons instead of ASI",
recommended: false,
url: "https://eslint.org/docs/latest/rules/semi",
},
fixable: "code",
schema: {
anyOf: [
{
type: "array",
items: [
{
enum: ["never"],
},
{
type: "object",
properties: {
beforeStatementContinuationChars: {
enum: ["always", "any", "never"],
},
},
additionalProperties: false,
},
],
minItems: 0,
maxItems: 2,
},
{
type: "array",
items: [
{
enum: ["always"],
},
{
type: "object",
properties: {
omitLastInOneLineBlock: { type: "boolean" },
omitLastInOneLineClassBody: { type: "boolean" },
},
additionalProperties: false,
},
],
minItems: 0,
maxItems: 2,
},
],
},
messages: {
missingSemi: "Missing semicolon.",
extraSemi: "Extra semicolon.",
},
},
create(context) {
const OPT_OUT_PATTERN = /^[-[(/+`]/u; // One of [(/+-`
const unsafeClassFieldNames = new Set(["get", "set", "static"]);
const unsafeClassFieldFollowers = new Set(["*", "in", "instanceof"]);
const options = context.options[1];
const never = context.options[0] === "never";
const exceptOneLine = Boolean(
options && options.omitLastInOneLineBlock,
);
const exceptOneLineClassBody = Boolean(
options && options.omitLastInOneLineClassBody,
);
const beforeStatementContinuationChars =
(options && options.beforeStatementContinuationChars) || "any";
const sourceCode = context.sourceCode;
//--------------------------------------------------------------------------
// Helpers
//--------------------------------------------------------------------------
/**
* Reports a semicolon error with appropriate location and message.
* @param {ASTNode} node The node with an extra or missing semicolon.
* @param {boolean} missing True if the semicolon is missing.
* @returns {void}
*/
function report(node, missing) {
const lastToken = sourceCode.getLastToken(node);
let messageId, fix, loc;
if (!missing) {
messageId = "missingSemi";
loc = {
start: lastToken.loc.end,
end: astUtils.getNextLocation(
sourceCode,
lastToken.loc.end,
),
};
fix = function (fixer) {
return fixer.insertTextAfter(lastToken, ";");
};
} else {
messageId = "extraSemi";
loc = lastToken.loc;
fix = function (fixer) {
/*
* Expand the replacement range to include the surrounding
* tokens to avoid conflicting with no-extra-semi.
* https://github.com/eslint/eslint/issues/7928
*/
return new FixTracker(fixer, sourceCode)
.retainSurroundingTokens(lastToken)
.remove(lastToken);
};
}
context.report({
node,
loc,
messageId,
fix,
});
}
/**
* Check whether a given semicolon token is redundant.
* @param {Token} semiToken A semicolon token to check.
* @returns {boolean} `true` if the next token is `;` or `}`.
*/
function isRedundantSemi(semiToken) {
const nextToken = sourceCode.getTokenAfter(semiToken);
return (
!nextToken ||
astUtils.isClosingBraceToken(nextToken) ||
astUtils.isSemicolonToken(nextToken)
);
}
/**
* Check whether a given token is the closing brace of an arrow function.
* @param {Token} lastToken A token to check.
* @returns {boolean} `true` if the token is the closing brace of an arrow function.
*/
function isEndOfArrowBlock(lastToken) {
if (!astUtils.isClosingBraceToken(lastToken)) {
return false;
}
const node = sourceCode.getNodeByRangeIndex(lastToken.range[0]);
return (
node.type === "BlockStatement" &&
node.parent.type === "ArrowFunctionExpression"
);
}
/**
* Checks if a given PropertyDefinition node followed by a semicolon
* can safely remove that semicolon. It is not to safe to remove if
* the class field name is "get", "set", or "static", or if
* followed by a generator method.
* @param {ASTNode} node The node to check.
* @returns {boolean} `true` if the node cannot have the semicolon
* removed.
*/
function maybeClassFieldAsiHazard(node) {
if (node.type !== "PropertyDefinition") {
return false;
}
/*
* Computed property names and non-identifiers are always safe
* as they can be distinguished from keywords easily.
*/
const needsNameCheck =
!node.computed && node.key.type === "Identifier";
/*
* Certain names are problematic unless they also have a
* a way to distinguish between keywords and property
* names.
*/
if (needsNameCheck && unsafeClassFieldNames.has(node.key.name)) {
/*
* Special case: If the field name is `static`,
* it is only valid if the field is marked as static,
* so "static static" is okay but "static" is not.
*/
const isStaticStatic =
node.static && node.key.name === "static";
/*
* For other unsafe names, we only care if there is no
* initializer. No initializer = hazard.
*/
if (!isStaticStatic && !node.value) {
return true;
}
}
const followingToken = sourceCode.getTokenAfter(node);
return unsafeClassFieldFollowers.has(followingToken.value);
}
/**
* Check whether a given node is on the same line with the next token.
* @param {Node} node A statement node to check.
* @returns {boolean} `true` if the node is on the same line with the next token.
*/
function isOnSameLineWithNextToken(node) {
const prevToken = sourceCode.getLastToken(node, 1);
const nextToken = sourceCode.getTokenAfter(node);
return (
!!nextToken && astUtils.isTokenOnSameLine(prevToken, nextToken)
);
}
/**
* Check whether a given node can connect the next line if the next line is unreliable.
* @param {Node} node A statement node to check.
* @returns {boolean} `true` if the node can connect the next line.
*/
function maybeAsiHazardAfter(node) {
const t = node.type;
if (
t === "DoWhileStatement" ||
t === "BreakStatement" ||
t === "ContinueStatement" ||
t === "DebuggerStatement" ||
t === "ImportDeclaration" ||
t === "ExportAllDeclaration"
) {
return false;
}
if (t === "ReturnStatement") {
return Boolean(node.argument);
}
if (t === "ExportNamedDeclaration") {
return Boolean(node.declaration);
}
if (isEndOfArrowBlock(sourceCode.getLastToken(node, 1))) {
return false;
}
return true;
}
/**
* Check whether a given token can connect the previous statement.
* @param {Token} token A token to check.
* @returns {boolean} `true` if the token is one of `[`, `(`, `/`, `+`, `-`, ```, `++`, and `--`.
*/
function maybeAsiHazardBefore(token) {
return (
Boolean(token) &&
OPT_OUT_PATTERN.test(token.value) &&
token.value !== "++" &&
token.value !== "--"
);
}
/**
* Check if the semicolon of a given node is unnecessary, only true if:
* - next token is a valid statement divider (`;` or `}`).
* - next token is on a new line and the node is not connectable to the new line.
* @param {Node} node A statement node to check.
* @returns {boolean} whether the semicolon is unnecessary.
*/
function canRemoveSemicolon(node) {
if (isRedundantSemi(sourceCode.getLastToken(node))) {
return true; // `;;` or `;}`
}
if (maybeClassFieldAsiHazard(node)) {
return false;
}
if (isOnSameLineWithNextToken(node)) {
return false; // One liner.
}
// continuation characters should not apply to class fields
if (
node.type !== "PropertyDefinition" &&
beforeStatementContinuationChars === "never" &&
!maybeAsiHazardAfter(node)
) {
return true; // ASI works. This statement doesn't connect to the next.
}
if (!maybeAsiHazardBefore(sourceCode.getTokenAfter(node))) {
return true; // ASI works. The next token doesn't connect to this statement.
}
return false;
}
/**
* Checks a node to see if it's the last item in a one-liner block.
* Block is any `BlockStatement` or `StaticBlock` node. Block is a one-liner if its
* braces (and consequently everything between them) are on the same line.
* @param {ASTNode} node The node to check.
* @returns {boolean} whether the node is the last item in a one-liner block.
*/
function isLastInOneLinerBlock(node) {
const parent = node.parent;
const nextToken = sourceCode.getTokenAfter(node);
if (!nextToken || nextToken.value !== "}") {
return false;
}
if (parent.type === "BlockStatement") {
return parent.loc.start.line === parent.loc.end.line;
}
if (parent.type === "StaticBlock") {
const openingBrace = sourceCode.getFirstToken(parent, {
skip: 1,
}); // skip the `static` token
return openingBrace.loc.start.line === parent.loc.end.line;
}
return false;
}
/**
* Checks a node to see if it's the last item in a one-liner `ClassBody` node.
* ClassBody is a one-liner if its braces (and consequently everything between them) are on the same line.
* @param {ASTNode} node The node to check.
* @returns {boolean} whether the node is the last item in a one-liner ClassBody.
*/
function isLastInOneLinerClassBody(node) {
const parent = node.parent;
const nextToken = sourceCode.getTokenAfter(node);
if (!nextToken || nextToken.value !== "}") {
return false;
}
if (parent.type === "ClassBody") {
return parent.loc.start.line === parent.loc.end.line;
}
return false;
}
/**
* Checks a node to see if it's followed by a semicolon.
* @param {ASTNode} node The node to check.
* @returns {void}
*/
function checkForSemicolon(node) {
const isSemi = astUtils.isSemicolonToken(
sourceCode.getLastToken(node),
);
if (never) {
if (isSemi && canRemoveSemicolon(node)) {
report(node, true);
} else if (
!isSemi &&
beforeStatementContinuationChars === "always" &&
node.type !== "PropertyDefinition" &&
maybeAsiHazardBefore(sourceCode.getTokenAfter(node))
) {
report(node);
}
} else {
const oneLinerBlock =
exceptOneLine && isLastInOneLinerBlock(node);
const oneLinerClassBody =
exceptOneLineClassBody && isLastInOneLinerClassBody(node);
const oneLinerBlockOrClassBody =
oneLinerBlock || oneLinerClassBody;
if (isSemi && oneLinerBlockOrClassBody) {
report(node, true);
} else if (!isSemi && !oneLinerBlockOrClassBody) {
report(node);
}
}
}
/**
* Checks to see if there's a semicolon after a variable declaration.
* @param {ASTNode} node The node to check.
* @returns {void}
*/
function checkForSemicolonForVariableDeclaration(node) {
const parent = node.parent;
if (
(parent.type !== "ForStatement" || parent.init !== node) &&
(!/^For(?:In|Of)Statement/u.test(parent.type) ||
parent.left !== node)
) {
checkForSemicolon(node);
}
}
//--------------------------------------------------------------------------
// Public API
//--------------------------------------------------------------------------
return {
VariableDeclaration: checkForSemicolonForVariableDeclaration,
ExpressionStatement: checkForSemicolon,
ReturnStatement: checkForSemicolon,
ThrowStatement: checkForSemicolon,
DoWhileStatement: checkForSemicolon,
DebuggerStatement: checkForSemicolon,
BreakStatement: checkForSemicolon,
ContinueStatement: checkForSemicolon,
ImportDeclaration: checkForSemicolon,
ExportAllDeclaration: checkForSemicolon,
ExportNamedDeclaration(node) {
if (!node.declaration) {
checkForSemicolon(node);
}
},
ExportDefaultDeclaration(node) {
if (
!/(?:Class|Function)Declaration/u.test(
node.declaration.type,
)
) {
checkForSemicolon(node);
}
},
PropertyDefinition: checkForSemicolon,
};
},
};

View File

@@ -0,0 +1,19 @@
# @babel/helper-module-imports
> Babel helper functions for inserting module loads
See our website [@babel/helper-module-imports](https://babeljs.io/docs/babel-helper-module-imports) for more information.
## Install
Using npm:
```sh
npm install --save @babel/helper-module-imports
```
or using yarn:
```sh
yarn add @babel/helper-module-imports
```

View File

@@ -0,0 +1,212 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
function helpers() {
const data = require("@babel/helpers");
helpers = function () {
return data;
};
return data;
}
function _traverse() {
const data = require("@babel/traverse");
_traverse = function () {
return data;
};
return data;
}
function _codeFrame() {
const data = require("@babel/code-frame");
_codeFrame = function () {
return data;
};
return data;
}
function _t() {
const data = require("@babel/types");
_t = function () {
return data;
};
return data;
}
function _semver() {
const data = require("semver");
_semver = function () {
return data;
};
return data;
}
var _babel7Helpers = require("./babel-7-helpers.cjs");
const {
cloneNode,
interpreterDirective
} = _t();
const errorVisitor = {
enter(path, state) {
const loc = path.node.loc;
if (loc) {
state.loc = loc;
path.stop();
}
}
};
class File {
constructor(options, {
code,
ast,
inputMap
}) {
this._map = new Map();
this.opts = void 0;
this.declarations = {};
this.path = void 0;
this.ast = void 0;
this.scope = void 0;
this.metadata = {};
this.code = "";
this.inputMap = void 0;
this.hub = {
file: this,
getCode: () => this.code,
getScope: () => this.scope,
addHelper: this.addHelper.bind(this),
buildError: this.buildCodeFrameError.bind(this)
};
this.opts = options;
this.code = code;
this.ast = ast;
this.inputMap = inputMap;
this.path = _traverse().NodePath.get({
hub: this.hub,
parentPath: null,
parent: this.ast,
container: this.ast,
key: "program"
}).setContext();
this.scope = this.path.scope;
}
get shebang() {
const {
interpreter
} = this.path.node;
return interpreter ? interpreter.value : "";
}
set shebang(value) {
if (value) {
this.path.get("interpreter").replaceWith(interpreterDirective(value));
} else {
this.path.get("interpreter").remove();
}
}
set(key, val) {
{
if (key === "helpersNamespace") {
throw new Error("Babel 7.0.0-beta.56 has dropped support for the 'helpersNamespace' utility." + "If you are using @babel/plugin-external-helpers you will need to use a newer " + "version than the one you currently have installed. " + "If you have your own implementation, you'll want to explore using 'helperGenerator' " + "alongside 'file.availableHelper()'.");
}
}
this._map.set(key, val);
}
get(key) {
return this._map.get(key);
}
has(key) {
return this._map.has(key);
}
availableHelper(name, versionRange) {
let minVersion;
try {
minVersion = helpers().minVersion(name);
} catch (err) {
if (err.code !== "BABEL_HELPER_UNKNOWN") throw err;
return false;
}
if (typeof versionRange !== "string") return true;
if (_semver().valid(versionRange)) versionRange = `^${versionRange}`;
{
return !_semver().intersects(`<${minVersion}`, versionRange) && !_semver().intersects(`>=8.0.0`, versionRange);
}
}
addHelper(name) {
const declar = this.declarations[name];
if (declar) return cloneNode(declar);
const generator = this.get("helperGenerator");
if (generator) {
const res = generator(name);
if (res) return res;
}
helpers().minVersion(name);
const uid = this.declarations[name] = this.scope.generateUidIdentifier(name);
const dependencies = {};
for (const dep of helpers().getDependencies(name)) {
dependencies[dep] = this.addHelper(dep);
}
const {
nodes,
globals
} = helpers().get(name, dep => dependencies[dep], uid.name, Object.keys(this.scope.getAllBindings()));
globals.forEach(name => {
if (this.path.scope.hasBinding(name, true)) {
this.path.scope.rename(name);
}
});
nodes.forEach(node => {
node._compact = true;
});
const added = this.path.unshiftContainer("body", nodes);
for (const path of added) {
if (path.isVariableDeclaration()) this.scope.registerDeclaration(path);
}
return uid;
}
buildCodeFrameError(node, msg, _Error = SyntaxError) {
let loc = node == null ? void 0 : node.loc;
if (!loc && node) {
const state = {
loc: null
};
(0, _traverse().default)(node, errorVisitor, this.scope, state);
loc = state.loc;
let txt = "This is an error on an internal node. Probably an internal error.";
if (loc) txt += " Location has been estimated.";
msg += ` (${txt})`;
}
if (loc) {
const {
highlightCode = true
} = this.opts;
msg += "\n" + (0, _codeFrame().codeFrameColumns)(this.code, {
start: {
line: loc.start.line,
column: loc.start.column + 1
},
end: loc.end && loc.start.line === loc.end.line ? {
line: loc.end.line,
column: loc.end.column + 1
} : undefined
}, {
highlightCode
});
}
return new _Error(msg);
}
}
exports.default = File;
{
File.prototype.addImport = function addImport() {
throw new Error("This API has been removed. If you're looking for this " + "functionality in Babel 7, you should import the " + "'@babel/helper-module-imports' module and use the functions exposed " + " from that module, such as 'addNamed' or 'addDefault'.");
};
File.prototype.addTemplateObject = function addTemplateObject() {
throw new Error("This function has been moved into the template literal transform itself.");
};
{
File.prototype.getModuleName = function getModuleName() {
return _babel7Helpers.getModuleName()(this.opts, this.opts);
};
}
}
0 && 0;
//# sourceMappingURL=file.js.map

View File

@@ -0,0 +1,247 @@
# bl *(BufferList)*
[![Build Status](https://api.travis-ci.com/rvagg/bl.svg?branch=master)](https://travis-ci.com/rvagg/bl/)
**A Node.js Buffer list collector, reader and streamer thingy.**
[![NPM](https://nodei.co/npm/bl.svg)](https://nodei.co/npm/bl/)
**bl** is a storage object for collections of Node Buffers, exposing them with the main Buffer readable API. Also works as a duplex stream so you can collect buffers from a stream that emits them and emit buffers to a stream that consumes them!
The original buffers are kept intact and copies are only done as necessary. Any reads that require the use of a single original buffer will return a slice of that buffer only (which references the same memory as the original buffer). Reads that span buffers perform concatenation as required and return the results transparently.
```js
const { BufferList } = require('bl')
const bl = new BufferList()
bl.append(Buffer.from('abcd'))
bl.append(Buffer.from('efg'))
bl.append('hi') // bl will also accept & convert Strings
bl.append(Buffer.from('j'))
bl.append(Buffer.from([ 0x3, 0x4 ]))
console.log(bl.length) // 12
console.log(bl.slice(0, 10).toString('ascii')) // 'abcdefghij'
console.log(bl.slice(3, 10).toString('ascii')) // 'defghij'
console.log(bl.slice(3, 6).toString('ascii')) // 'def'
console.log(bl.slice(3, 8).toString('ascii')) // 'defgh'
console.log(bl.slice(5, 10).toString('ascii')) // 'fghij'
console.log(bl.indexOf('def')) // 3
console.log(bl.indexOf('asdf')) // -1
// or just use toString!
console.log(bl.toString()) // 'abcdefghij\u0003\u0004'
console.log(bl.toString('ascii', 3, 8)) // 'defgh'
console.log(bl.toString('ascii', 5, 10)) // 'fghij'
// other standard Buffer readables
console.log(bl.readUInt16BE(10)) // 0x0304
console.log(bl.readUInt16LE(10)) // 0x0403
```
Give it a callback in the constructor and use it just like **[concat-stream](https://github.com/maxogden/node-concat-stream)**:
```js
const { BufferListStream } = require('bl')
const fs = require('fs')
fs.createReadStream('README.md')
.pipe(BufferListStream((err, data) => { // note 'new' isn't strictly required
// `data` is a complete Buffer object containing the full data
console.log(data.toString())
}))
```
Note that when you use the *callback* method like this, the resulting `data` parameter is a concatenation of all `Buffer` objects in the list. If you want to avoid the overhead of this concatenation (in cases of extreme performance consciousness), then avoid the *callback* method and just listen to `'end'` instead, like a standard Stream.
Or to fetch a URL using [hyperquest](https://github.com/substack/hyperquest) (should work with [request](http://github.com/mikeal/request) and even plain Node http too!):
```js
const hyperquest = require('hyperquest')
const { BufferListStream } = require('bl')
const url = 'https://raw.github.com/rvagg/bl/master/README.md'
hyperquest(url).pipe(BufferListStream((err, data) => {
console.log(data.toString())
}))
```
Or, use it as a readable stream to recompose a list of Buffers to an output source:
```js
const { BufferListStream } = require('bl')
const fs = require('fs')
var bl = new BufferListStream()
bl.append(Buffer.from('abcd'))
bl.append(Buffer.from('efg'))
bl.append(Buffer.from('hi'))
bl.append(Buffer.from('j'))
bl.pipe(fs.createWriteStream('gibberish.txt'))
```
## API
* <a href="#ctor"><code><b>new BufferList([ buf ])</b></code></a>
* <a href="#isBufferList"><code><b>BufferList.isBufferList(obj)</b></code></a>
* <a href="#length"><code>bl.<b>length</b></code></a>
* <a href="#append"><code>bl.<b>append(buffer)</b></code></a>
* <a href="#get"><code>bl.<b>get(index)</b></code></a>
* <a href="#indexOf"><code>bl.<b>indexOf(value[, byteOffset][, encoding])</b></code></a>
* <a href="#slice"><code>bl.<b>slice([ start[, end ] ])</b></code></a>
* <a href="#shallowSlice"><code>bl.<b>shallowSlice([ start[, end ] ])</b></code></a>
* <a href="#copy"><code>bl.<b>copy(dest, [ destStart, [ srcStart [, srcEnd ] ] ])</b></code></a>
* <a href="#duplicate"><code>bl.<b>duplicate()</b></code></a>
* <a href="#consume"><code>bl.<b>consume(bytes)</b></code></a>
* <a href="#toString"><code>bl.<b>toString([encoding, [ start, [ end ]]])</b></code></a>
* <a href="#readXX"><code>bl.<b>readDoubleBE()</b></code>, <code>bl.<b>readDoubleLE()</b></code>, <code>bl.<b>readFloatBE()</b></code>, <code>bl.<b>readFloatLE()</b></code>, <code>bl.<b>readInt32BE()</b></code>, <code>bl.<b>readInt32LE()</b></code>, <code>bl.<b>readUInt32BE()</b></code>, <code>bl.<b>readUInt32LE()</b></code>, <code>bl.<b>readInt16BE()</b></code>, <code>bl.<b>readInt16LE()</b></code>, <code>bl.<b>readUInt16BE()</b></code>, <code>bl.<b>readUInt16LE()</b></code>, <code>bl.<b>readInt8()</b></code>, <code>bl.<b>readUInt8()</b></code></a>
* <a href="#ctorStream"><code><b>new BufferListStream([ callback ])</b></code></a>
--------------------------------------------------------
<a name="ctor"></a>
### new BufferList([ Buffer | Buffer array | BufferList | BufferList array | String ])
No arguments are _required_ for the constructor, but you can initialise the list by passing in a single `Buffer` object or an array of `Buffer` objects.
`new` is not strictly required, if you don't instantiate a new object, it will be done automatically for you so you can create a new instance simply with:
```js
const { BufferList } = require('bl')
const bl = BufferList()
// equivalent to:
const { BufferList } = require('bl')
const bl = new BufferList()
```
--------------------------------------------------------
<a name="isBufferList"></a>
### BufferList.isBufferList(obj)
Determines if the passed object is a `BufferList`. It will return `true` if the passed object is an instance of `BufferList` **or** `BufferListStream` and `false` otherwise.
N.B. this won't return `true` for `BufferList` or `BufferListStream` instances created by versions of this library before this static method was added.
--------------------------------------------------------
<a name="length"></a>
### bl.length
Get the length of the list in bytes. This is the sum of the lengths of all of the buffers contained in the list, minus any initial offset for a semi-consumed buffer at the beginning. Should accurately represent the total number of bytes that can be read from the list.
--------------------------------------------------------
<a name="append"></a>
### bl.append(Buffer | Buffer array | BufferList | BufferList array | String)
`append(buffer)` adds an additional buffer or BufferList to the internal list. `this` is returned so it can be chained.
--------------------------------------------------------
<a name="get"></a>
### bl.get(index)
`get()` will return the byte at the specified index.
--------------------------------------------------------
<a name="indexOf"></a>
### bl.indexOf(value[, byteOffset][, encoding])
`get()` will return the byte at the specified index.
`indexOf()` method returns the first index at which a given element can be found in the BufferList, or -1 if it is not present.
--------------------------------------------------------
<a name="slice"></a>
### bl.slice([ start, [ end ] ])
`slice()` returns a new `Buffer` object containing the bytes within the range specified. Both `start` and `end` are optional and will default to the beginning and end of the list respectively.
If the requested range spans a single internal buffer then a slice of that buffer will be returned which shares the original memory range of that Buffer. If the range spans multiple buffers then copy operations will likely occur to give you a uniform Buffer.
--------------------------------------------------------
<a name="shallowSlice"></a>
### bl.shallowSlice([ start, [ end ] ])
`shallowSlice()` returns a new `BufferList` object containing the bytes within the range specified. Both `start` and `end` are optional and will default to the beginning and end of the list respectively.
No copies will be performed. All buffers in the result share memory with the original list.
--------------------------------------------------------
<a name="copy"></a>
### bl.copy(dest, [ destStart, [ srcStart [, srcEnd ] ] ])
`copy()` copies the content of the list in the `dest` buffer, starting from `destStart` and containing the bytes within the range specified with `srcStart` to `srcEnd`. `destStart`, `start` and `end` are optional and will default to the beginning of the `dest` buffer, and the beginning and end of the list respectively.
--------------------------------------------------------
<a name="duplicate"></a>
### bl.duplicate()
`duplicate()` performs a **shallow-copy** of the list. The internal Buffers remains the same, so if you change the underlying Buffers, the change will be reflected in both the original and the duplicate. This method is needed if you want to call `consume()` or `pipe()` and still keep the original list.Example:
```js
var bl = new BufferListStream()
bl.append('hello')
bl.append(' world')
bl.append('\n')
bl.duplicate().pipe(process.stdout, { end: false })
console.log(bl.toString())
```
--------------------------------------------------------
<a name="consume"></a>
### bl.consume(bytes)
`consume()` will shift bytes *off the start of the list*. The number of bytes consumed don't need to line up with the sizes of the internal Buffers&mdash;initial offsets will be calculated accordingly in order to give you a consistent view of the data.
--------------------------------------------------------
<a name="toString"></a>
### bl.toString([encoding, [ start, [ end ]]])
`toString()` will return a string representation of the buffer. The optional `start` and `end` arguments are passed on to `slice()`, while the `encoding` is passed on to `toString()` of the resulting Buffer. See the [Buffer#toString()](http://nodejs.org/docs/latest/api/buffer.html#buffer_buf_tostring_encoding_start_end) documentation for more information.
--------------------------------------------------------
<a name="readXX"></a>
### bl.readDoubleBE(), bl.readDoubleLE(), bl.readFloatBE(), bl.readFloatLE(), bl.readInt32BE(), bl.readInt32LE(), bl.readUInt32BE(), bl.readUInt32LE(), bl.readInt16BE(), bl.readInt16LE(), bl.readUInt16BE(), bl.readUInt16LE(), bl.readInt8(), bl.readUInt8()
All of the standard byte-reading methods of the `Buffer` interface are implemented and will operate across internal Buffer boundaries transparently.
See the <b><code>[Buffer](http://nodejs.org/docs/latest/api/buffer.html)</code></b> documentation for how these work.
--------------------------------------------------------
<a name="ctorStream"></a>
### new BufferListStream([ callback | Buffer | Buffer array | BufferList | BufferList array | String ])
**BufferListStream** is a Node **[Duplex Stream](http://nodejs.org/docs/latest/api/stream.html#stream_class_stream_duplex)**, so it can be read from and written to like a standard Node stream. You can also `pipe()` to and from a **BufferListStream** instance.
The constructor takes an optional callback, if supplied, the callback will be called with an error argument followed by a reference to the **bl** instance, when `bl.end()` is called (i.e. from a piped stream). This is a convenient method of collecting the entire contents of a stream, particularly when the stream is *chunky*, such as a network stream.
Normally, no arguments are required for the constructor, but you can initialise the list by passing in a single `Buffer` object or an array of `Buffer` object.
`new` is not strictly required, if you don't instantiate a new object, it will be done automatically for you so you can create a new instance simply with:
```js
const { BufferListStream } = require('bl')
const bl = BufferListStream()
// equivalent to:
const { BufferListStream } = require('bl')
const bl = new BufferListStream()
```
N.B. For backwards compatibility reasons, `BufferListStream` is the **default** export when you `require('bl')`:
```js
const { BufferListStream } = require('bl')
// equivalent to:
const BufferListStream = require('bl')
```
--------------------------------------------------------
## Contributors
**bl** is brought to you by the following hackers:
* [Rod Vagg](https://github.com/rvagg)
* [Matteo Collina](https://github.com/mcollina)
* [Jarett Cruger](https://github.com/jcrugzz)
<a name="license"></a>
## License &amp; copyright
Copyright (c) 2013-2019 bl contributors (listed above).
bl is licensed under the MIT license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE.md file for more details.

View File

@@ -0,0 +1 @@
module.exports={A:{A:{"2":"K D E F A B mC"},B:{"1":"BB CB DB EB FB GB HB IB JB KB LB MB NB OB I","2":"C L M G N","164":"0 9 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","3138":"O","12292":"P"},C:{"1":"0 9 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 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 AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB I PC EC QC RC oC pC","2":"nC LC","260":"1 2 3 4 5 6 7 8 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"},D:{"1":"BB CB DB EB FB GB HB IB JB KB LB MB NB OB I PC EC QC RC","164":"0 1 2 3 4 5 6 7 8 9 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 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"},E:{"1":"VC HC 0C IC WC XC YC ZC aC 1C JC bC cC dC eC fC 2C KC gC hC iC jC 3C","2":"sC SC","164":"J PB K D E F A B C L M G tC uC vC wC TC FC GC xC yC zC UC"},F:{"1":"0 p q r s t u v w x y z","2":"F B C 4C 5C 6C 7C FC kC 8C GC","164":"1 2 3 4 5 6 7 8 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"},G:{"1":"VC HC TD IC WC XC YC ZC aC UD JC bC cC dC eC fC VD KC gC hC iC jC","164":"E SC 9C lC AD BD CD DD ED FD GD HD ID JD KD LD MD ND OD PD QD RD SD UC"},H:{"2":"WD"},I:{"1":"I","164":"bD cD","676":"LC J XD YD ZD aD lC"},J:{"164":"D A"},K:{"1":"H","2":"A B C FC kC GC"},L:{"1":"I"},M:{"1":"EC"},N:{"2":"A B"},O:{"164":"HC"},P:{"1":"6 7 8","164":"1 2 3 4 5 J dD eD fD gD hD TC iD jD kD lD mD IC JC KC nD"},Q:{"164":"oD"},R:{"164":"pD"},S:{"1":"rD","260":"qD"}},B:4,C:"CSS Masks",D:true};

View File

@@ -0,0 +1 @@
module.exports={A:{A:{"1":"F A B","2":"K D E mC"},B:{"1":"0 9 C 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"},C:{"1":"0 1 2 3 4 5 6 7 8 9 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 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 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 AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB I PC EC QC RC oC pC qC rC"},D:{"1":"0 1 2 3 4 5 6 7 8 9 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 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"},E:{"1":"J PB K D E F A B C L M G tC uC vC wC TC FC GC xC 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","16":"sC SC"},F:{"1":"0 1 2 3 4 5 6 7 8 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 7C FC kC 8C GC","16":"F 4C 5C 6C"},G:{"1":"E 9C lC 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 hC iC jC","16":"SC"},H:{"2":"WD"},I:{"1":"LC J I XD YD ZD aD lC bD cD"},J:{"1":"D A"},K:{"1":"A B C H FC kC GC"},L:{"1":"I"},M:{"1":"EC"},N:{"1":"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:{"1":"qD rD"}},B:1,C:"Selection controls for input & textarea",D:true};

View File

@@ -0,0 +1,177 @@
/**
* @fileoverview Rule to flag use constant conditions
* @author Christian Schulz <http://rndm.de>
*/
"use strict";
const { isConstant } = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../shared/types').Rule} */
module.exports = {
meta: {
type: "problem",
defaultOptions: [{ checkLoops: "allExceptWhileTrue" }],
docs: {
description: "Disallow constant expressions in conditions",
recommended: true,
url: "https://eslint.org/docs/latest/rules/no-constant-condition",
},
schema: [
{
type: "object",
properties: {
checkLoops: {
enum: [
"all",
"allExceptWhileTrue",
"none",
true,
false,
],
},
},
additionalProperties: false,
},
],
messages: {
unexpected: "Unexpected constant condition.",
},
},
create(context) {
const loopSetStack = [];
const sourceCode = context.sourceCode;
let [{ checkLoops }] = context.options;
if (checkLoops === true) {
checkLoops = "all";
} else if (checkLoops === false) {
checkLoops = "none";
}
let loopsInCurrentScope = new Set();
//--------------------------------------------------------------------------
// Helpers
//--------------------------------------------------------------------------
/**
* Tracks when the given node contains a constant condition.
* @param {ASTNode} node The AST node to check.
* @returns {void}
* @private
*/
function trackConstantConditionLoop(node) {
if (
node.test &&
isConstant(sourceCode.getScope(node), node.test, true)
) {
loopsInCurrentScope.add(node);
}
}
/**
* Reports when the set contains the given constant condition node
* @param {ASTNode} node The AST node to check.
* @returns {void}
* @private
*/
function checkConstantConditionLoopInSet(node) {
if (loopsInCurrentScope.has(node)) {
loopsInCurrentScope.delete(node);
context.report({ node: node.test, messageId: "unexpected" });
}
}
/**
* Reports when the given node contains a constant condition.
* @param {ASTNode} node The AST node to check.
* @returns {void}
* @private
*/
function reportIfConstant(node) {
if (
node.test &&
isConstant(sourceCode.getScope(node), node.test, true)
) {
context.report({ node: node.test, messageId: "unexpected" });
}
}
/**
* Stores current set of constant loops in loopSetStack temporarily
* and uses a new set to track constant loops
* @returns {void}
* @private
*/
function enterFunction() {
loopSetStack.push(loopsInCurrentScope);
loopsInCurrentScope = new Set();
}
/**
* Reports when the set still contains stored constant conditions
* @returns {void}
* @private
*/
function exitFunction() {
loopsInCurrentScope = loopSetStack.pop();
}
/**
* Checks node when checkLoops option is enabled
* @param {ASTNode} node The AST node to check.
* @returns {void}
* @private
*/
function checkLoop(node) {
if (checkLoops === "all" || checkLoops === "allExceptWhileTrue") {
trackConstantConditionLoop(node);
}
}
//--------------------------------------------------------------------------
// Public
//--------------------------------------------------------------------------
return {
ConditionalExpression: reportIfConstant,
IfStatement: reportIfConstant,
WhileStatement(node) {
if (
node.test.type === "Literal" &&
node.test.value === true &&
checkLoops === "allExceptWhileTrue"
) {
return;
}
checkLoop(node);
},
"WhileStatement:exit": checkConstantConditionLoopInSet,
DoWhileStatement: checkLoop,
"DoWhileStatement:exit": checkConstantConditionLoopInSet,
ForStatement: checkLoop,
"ForStatement > .test": node => checkLoop(node.parent),
"ForStatement:exit": checkConstantConditionLoopInSet,
FunctionDeclaration: enterFunction,
"FunctionDeclaration:exit": exitFunction,
FunctionExpression: enterFunction,
"FunctionExpression:exit": exitFunction,
YieldExpression: () => loopsInCurrentScope.clear(),
};
},
};