This commit is contained in:
2026-11-02 12:42:04 +00:00
commit e4e28174bf
5498 changed files with 1735888 additions and 0 deletions

View File

@@ -0,0 +1,141 @@
import type { ASTNode, RuleContext, SourceCode } from '../types.js';
import type { TSESTree } from '@typescript-eslint/types';
import type { Scope, Variable } from '@typescript-eslint/scope-manager';
import type { AST as SvAST } from 'svelte-eslint-parser';
/**
* Checks whether or not the tokens of two given nodes are same.
* @param left A node 1 to compare.
* @param right A node 2 to compare.
* @param sourceCode The ESLint source code object.
* @returns the source code for the given node.
*/
export declare function equalTokens(left: ASTNode, right: ASTNode, sourceCode: SourceCode): boolean;
/**
* Get the value of a given node if it's a literal or a template literal.
*/
export declare function getStringIfConstant(node: TSESTree.Expression | TSESTree.PrivateIdentifier): string | null;
/**
* Check if it need parentheses.
*/
export declare function needParentheses(node: TSESTree.Expression, kind: 'not' | 'logical'): boolean;
/** Checks whether the given node is the html element node or <svelte:element> node. */
export declare function isHTMLElementLike(node: SvAST.SvelteElement | SvAST.SvelteScriptElement | SvAST.SvelteStyleElement): node is SvAST.SvelteHTMLElement | (SvAST.SvelteSpecialElement & {
name: SvAST.SvelteName & {
name: 'svelte:element';
};
});
/**
* Find the attribute from the given element node
*/
export declare function findAttribute<N extends string>(node: SvAST.SvelteElement | SvAST.SvelteScriptElement | SvAST.SvelteStyleElement | SvAST.SvelteStartTag, name: N): (SvAST.SvelteAttribute & {
key: SvAST.SvelteAttribute['key'] & {
name: N;
};
}) | null;
/**
* Find the shorthand attribute from the given element node
*/
export declare function findShorthandAttribute<N extends string>(node: SvAST.SvelteElement | SvAST.SvelteScriptElement | SvAST.SvelteStyleElement | SvAST.SvelteStartTag, name: N): (SvAST.SvelteShorthandAttribute & {
key: SvAST.SvelteShorthandAttribute['key'] & {
name: N;
};
}) | null;
/**
* Find the bind directive from the given element node
*/
export declare function findBindDirective<N extends string>(node: SvAST.SvelteElement | SvAST.SvelteScriptElement | SvAST.SvelteStyleElement | SvAST.SvelteStartTag, name: N): (SvAST.SvelteBindingDirective & {
key: SvAST.SvelteDirectiveKey & {
name: SvAST.SvelteDirectiveKey['name'] & {
name: N;
};
};
}) | null;
/**
* Get the static attribute value from given attribute
*/
export declare function getStaticAttributeValue(node: SvAST.SvelteAttribute): string | null;
/**
* Get the static attribute value from given attribute
*/
export declare function getLangValue(node: SvAST.SvelteScriptElement | SvAST.SvelteStyleElement): string | null;
/**
* Find the variable of a given name.
*/
export declare function findVariable(context: RuleContext, node: TSESTree.Identifier): Variable | null;
/**
* Context for safely finding variables, avoiding infinite recursion.
* This should be used when the caller function may be called recursively, instead of `findVariable()`.
*
* Create an instance of this class at the top of the call stack where you want to start searching for identifiers,
* and then use it within the recursion.
*/
export declare class FindVariableContext {
readonly findVariable: (node: TSESTree.Identifier) => Variable | null;
constructor(context: RuleContext);
}
/**
* Iterate the identifiers of a given pattern node.
*/
export declare function iterateIdentifiers(node: TSESTree.DestructuringPattern): Iterable<TSESTree.Identifier>;
/**
* Gets the scope for the current node
*/
export declare function getScope(context: RuleContext, currentNode: TSESTree.Node): Scope;
/** Get the parent node from the given node */
export declare function getParent(node: TSESTree.Node): TSESTree.Node | null;
export type QuoteAndRange = {
quote: 'unquoted' | 'double' | 'single';
range: [number, number];
firstToken: SvAST.Token | SvAST.Comment;
lastToken: SvAST.Token | SvAST.Comment;
};
/** Get the quote and range from given attribute values */
export declare function getAttributeValueQuoteAndRange(attr: SvAST.SvelteAttribute | SvAST.SvelteDirective | SvAST.SvelteStyleDirective | SvAST.SvelteSpecialDirective, sourceCode: SourceCode): QuoteAndRange | null;
export declare function getMustacheTokens(node: SvAST.SvelteMustacheTag | SvAST.SvelteShorthandAttribute | SvAST.SvelteSpreadAttribute | SvAST.SvelteDebugTag | SvAST.SvelteDeclarationTag | SvAST.SvelteRenderTag, sourceCode: SourceCode): {
openToken: SvAST.Token;
closeToken: SvAST.Token;
};
export declare function getMustacheTokens(node: SvAST.SvelteDirective | SvAST.SvelteSpecialDirective | SvAST.SvelteMustacheTag | SvAST.SvelteShorthandAttribute | SvAST.SvelteSpreadAttribute | SvAST.SvelteDebugTag | SvAST.SvelteDeclarationTag | SvAST.SvelteRenderTag, sourceCode: SourceCode): {
openToken: SvAST.Token;
closeToken: SvAST.Token;
} | null;
/** Get attribute key text */
export declare function getAttributeKeyText(node: SvAST.SvelteAttribute | SvAST.SvelteShorthandAttribute | SvAST.SvelteStyleDirective | SvAST.SvelteDirective | SvAST.SvelteSpecialDirective | SvAST.SvelteGenericsDirective | SvAST.SvelteAttachTag, context: RuleContext): string;
/** Get directive name */
export declare function getDirectiveName(node: SvAST.SvelteDirective): string;
/**
* Extract all class names used in a HTML element attribute.
*/
export declare function findClassesInAttribute(attribute: SvAST.SvelteAttribute | SvAST.SvelteShorthandAttribute | SvAST.SvelteSpreadAttribute | SvAST.SvelteDirective | SvAST.SvelteStyleDirective | SvAST.SvelteSpecialDirective | SvAST.SvelteGenericsDirective | SvAST.SvelteAttachTag): string[];
/**
* Returns name of SvelteElement
*/
export declare function getNodeName(node: SvAST.SvelteElement): string;
/**
* Returns true if element is known void element
* {@link https://developer.mozilla.org/en-US/docs/Glossary/Empty_element}
*/
export declare function isVoidHtmlElement(node: SvAST.SvelteElement): boolean;
/**
* Returns true if element is known foreign (SVG or MathML) element
*/
export declare function isForeignElement(node: SvAST.SvelteElement): boolean;
export declare function isSvgElement(node: SvAST.SvelteElement): boolean;
export declare function isMathMLElement(node: SvAST.SvelteElement): boolean;
/** Checks whether the given identifier node is used as an expression. */
export declare function isExpressionIdentifier(node: TSESTree.Identifier): boolean;
/**
* Finds the variable for a given name in the specified node's scope.
* Also determines if the replacement name is already in use.
*
* If the `name` is set to null, this assumes you're adding a new variable
* and reports if it is already in use.
*/
export declare function findVariableForReplacement(context: RuleContext, node: TSESTree.Node, name: string | null, replacementName: string): {
hasConflict: boolean;
variable: Variable | null;
};
/**
* Check if one node is contained withing the subtree of another node.
*/
export declare function isIn(needle: TSESTree.Node, haystack: TSESTree.Node): boolean;

View File

@@ -0,0 +1,531 @@
import * as eslintUtils from '@eslint-community/eslint-utils';
import { voidElements, svgElements, mathmlElements } from './element-types.js';
/**
* Checks whether or not the tokens of two given nodes are same.
* @param left A node 1 to compare.
* @param right A node 2 to compare.
* @param sourceCode The ESLint source code object.
* @returns the source code for the given node.
*/
export function equalTokens(left, right, sourceCode) {
const tokensL = sourceCode.getTokens(left);
const tokensR = sourceCode.getTokens(right);
if (tokensL.length !== tokensR.length) {
return false;
}
for (let i = 0; i < tokensL.length; ++i) {
if (tokensL[i].type !== tokensR[i].type || tokensL[i].value !== tokensR[i].value) {
return false;
}
}
return true;
}
/**
* Get the value of a given node if it's a literal or a template literal.
*/
export function getStringIfConstant(node) {
if (node.type === 'Literal') {
if (typeof node.value === 'string')
return node.value;
}
else if (node.type === 'TemplateLiteral') {
let str = '';
const quasis = [...node.quasis];
const expressions = [...node.expressions];
let quasi, expr;
while ((quasi = quasis.shift())) {
str += quasi.value.cooked;
expr = expressions.shift();
if (expr) {
const exprStr = getStringIfConstant(expr);
if (exprStr == null) {
return null;
}
str += exprStr;
}
}
return str;
}
else if (node.type === 'BinaryExpression') {
if (node.operator === '+') {
const left = getStringIfConstant(node.left);
if (left == null) {
return null;
}
const right = getStringIfConstant(node.right);
if (right == null) {
return null;
}
return left + right;
}
}
return null;
}
/**
* Check if it need parentheses.
*/
export function needParentheses(node, kind) {
if (node.type === 'ArrowFunctionExpression' ||
node.type === 'AssignmentExpression' ||
node.type === 'BinaryExpression' ||
node.type === 'ConditionalExpression' ||
node.type === 'LogicalExpression' ||
node.type === 'SequenceExpression' ||
node.type === 'UnaryExpression' ||
node.type === 'UpdateExpression')
return true;
if (kind === 'logical') {
return node.type === 'FunctionExpression';
}
return false;
}
/** Checks whether the given node is the html element node or <svelte:element> node. */
export function isHTMLElementLike(node) {
if (node.type !== 'SvelteElement') {
return false;
}
switch (node.kind) {
case 'html':
return true;
case 'special':
return node.name.name === 'svelte:element';
default:
return false;
}
}
/**
* Find the attribute from the given element node
*/
export function findAttribute(node, name) {
const startTag = node.type === 'SvelteStartTag' ? node : node.startTag;
for (const attr of startTag.attributes) {
if (attr.type === 'SvelteAttribute') {
if (attr.key.name === name) {
return attr;
}
}
}
return null;
}
/**
* Find the shorthand attribute from the given element node
*/
export function findShorthandAttribute(node, name) {
const startTag = node.type === 'SvelteStartTag' ? node : node.startTag;
for (const attr of startTag.attributes) {
if (attr.type === 'SvelteShorthandAttribute') {
if (attr.key.name === name) {
return attr;
}
}
}
return null;
}
/**
* Find the bind directive from the given element node
*/
export function findBindDirective(node, name) {
const startTag = node.type === 'SvelteStartTag' ? node : node.startTag;
for (const attr of startTag.attributes) {
if (attr.type === 'SvelteDirective') {
if (attr.kind === 'Binding' && attr.key.name.name === name) {
return attr;
}
}
}
return null;
}
/**
* Get the static attribute value from given attribute
*/
export function getStaticAttributeValue(node) {
let str = '';
for (const value of node.value) {
if (value.type === 'SvelteLiteral') {
str += value.value;
}
else {
return null;
}
}
return str;
}
/**
* Get the static attribute value from given attribute
*/
export function getLangValue(node) {
const langAttr = findAttribute(node, 'lang');
return langAttr && getStaticAttributeValue(langAttr);
}
/**
* Find the variable of a given name.
*/
export function findVariable(context, node) {
const initialScope = eslintUtils.getInnermostScope(getScope(context, node), node);
const variable = eslintUtils.findVariable(initialScope, node);
if (variable) {
return variable;
}
if (!node.name.startsWith('$')) {
return variable;
}
// Remove the $ and search for the variable again, as it may be a store access variable.
return eslintUtils.findVariable(initialScope, node.name.slice(1));
}
/**
* Context for safely finding variables, avoiding infinite recursion.
* This should be used when the caller function may be called recursively, instead of `findVariable()`.
*
* Create an instance of this class at the top of the call stack where you want to start searching for identifiers,
* and then use it within the recursion.
*/
export class FindVariableContext {
constructor(context) {
const visited = new Set();
this.findVariable = (node) => {
if (visited.has(node)) {
return null;
}
visited.add(node);
return findVariable(context, node);
};
}
}
/**
* Iterate the identifiers of a given pattern node.
*/
export function* iterateIdentifiers(node) {
const buffer = [node];
let pattern;
while ((pattern = buffer.shift())) {
if (pattern.type === 'Identifier') {
yield pattern;
}
else if (pattern.type === 'ArrayPattern') {
for (const element of pattern.elements) {
if (element) {
buffer.push(element);
}
}
}
else if (pattern.type === 'ObjectPattern') {
for (const property of pattern.properties) {
if (property.type === 'Property') {
buffer.push(property.value);
}
else if (property.type === 'RestElement') {
buffer.push(property);
}
}
}
else if (pattern.type === 'AssignmentPattern') {
buffer.push(pattern.left);
}
else if (pattern.type === 'RestElement') {
buffer.push(pattern.argument);
}
else if (pattern.type === 'MemberExpression') {
// noop
}
}
}
/**
* Gets the scope for the current node
*/
export function getScope(context, currentNode) {
const scopeManager = context.sourceCode.scopeManager;
let node = currentNode;
for (; node; node = node.parent || null) {
const scope = scopeManager.acquire(node, false);
if (scope) {
if (scope.type === 'function-expression-name') {
return scope.childScopes[0];
}
return scope;
}
}
return scopeManager.scopes[0];
}
/** Get the parent node from the given node */
export function getParent(node) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- ignore
return node.parent || null;
}
/** Get the quote and range from given attribute values */
export function getAttributeValueQuoteAndRange(attr, sourceCode) {
const valueTokens = getAttributeValueRangeTokens(attr, sourceCode);
if (valueTokens == null) {
return null;
}
const { firstToken: valueFirstToken, lastToken: valueLastToken } = valueTokens;
const eqToken = sourceCode.getTokenAfter(attr.key);
if (!eqToken || eqToken.value !== '=' || valueFirstToken.range[0] < eqToken.range[1]) {
// invalid
return null;
}
const beforeTokens = sourceCode.getTokensBetween(eqToken, valueFirstToken);
if (beforeTokens.length === 0) {
return {
quote: 'unquoted',
range: [valueFirstToken.range[0], valueLastToken.range[1]],
firstToken: valueFirstToken,
lastToken: valueLastToken
};
}
else if (beforeTokens.length > 1 ||
(beforeTokens[0].value !== '"' && beforeTokens[0].value !== "'")) {
// invalid
return null;
}
const beforeToken = beforeTokens[0];
const afterToken = sourceCode.getTokenAfter(valueLastToken);
if (!afterToken || afterToken.value !== beforeToken.value) {
// invalid
return null;
}
return {
quote: beforeToken.value === '"' ? 'double' : 'single',
range: [beforeToken.range[0], afterToken.range[1]],
firstToken: beforeToken,
lastToken: afterToken
};
}
/** Get the mustache tokens from given node */
export function getMustacheTokens(node, sourceCode) {
if (isWrappedInBraces(node)) {
const openToken = sourceCode.getFirstToken(node);
const closeToken = sourceCode.getLastToken(node);
return {
openToken,
closeToken
};
}
if (node.expression == null) {
return null;
}
if (node.key.range[0] <= node.expression.range[0] &&
node.expression.range[1] <= node.key.range[1]) {
// shorthand
return null;
}
let openToken = sourceCode.getTokenBefore(node.expression);
let closeToken = sourceCode.getTokenAfter(node.expression);
while (openToken &&
closeToken &&
eslintUtils.isOpeningParenToken(openToken) &&
eslintUtils.isClosingParenToken(closeToken)) {
openToken = sourceCode.getTokenBefore(openToken);
closeToken = sourceCode.getTokenAfter(closeToken);
}
if (!openToken ||
!closeToken ||
eslintUtils.isNotOpeningBraceToken(openToken) ||
eslintUtils.isNotClosingBraceToken(closeToken)) {
return null;
}
return {
openToken,
closeToken
};
}
function isWrappedInBraces(node) {
return (node.type === 'SvelteMustacheTag' ||
node.type === 'SvelteShorthandAttribute' ||
node.type === 'SvelteSpreadAttribute' ||
node.type === 'SvelteDebugTag' ||
node.type === 'SvelteDeclarationTag' ||
node.type === 'SvelteRenderTag');
}
/** Get attribute key text */
export function getAttributeKeyText(node, context) {
switch (node.type) {
case 'SvelteAttribute':
case 'SvelteShorthandAttribute':
case 'SvelteGenericsDirective':
return node.key.name;
case 'SvelteStyleDirective':
return `style:${node.key.name.name}`;
case 'SvelteSpecialDirective':
return node.kind;
case 'SvelteDirective': {
const dir = getDirectiveName(node);
return `${dir}:${getSimpleNameFromNode(node.key.name, context)}${node.key.modifiers.length ? `|${node.key.modifiers.join('|')}` : ''}`;
}
case 'SvelteAttachTag':
return '@attach';
default:
throw new Error(`Unknown node type: ${
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- error
node.type}`);
}
}
/** Get directive name */
export function getDirectiveName(node) {
switch (node.kind) {
case 'Action':
return 'use';
case 'Animation':
return 'animate';
case 'Binding':
return 'bind';
case 'Class':
return 'class';
case 'EventHandler':
return 'on';
case 'Let':
return 'let';
case 'Transition':
return node.intro && node.outro ? 'transition' : node.intro ? 'in' : 'out';
case 'Ref':
return 'ref';
default:
throw new Error('Unknown directive kind');
}
}
/** Get the value tokens from given attribute */
function getAttributeValueRangeTokens(attr, sourceCode) {
if (attr.type === 'SvelteAttribute' || attr.type === 'SvelteStyleDirective') {
if (!attr.value.length) {
return null;
}
const first = attr.value[0];
const last = attr.value[attr.value.length - 1];
return {
firstToken: sourceCode.getFirstToken(first),
lastToken: sourceCode.getLastToken(last)
};
}
const tokens = getMustacheTokens(attr, sourceCode);
if (!tokens) {
return null;
}
return {
firstToken: tokens.openToken,
lastToken: tokens.closeToken
};
}
/**
* Extract all class names used in a HTML element attribute.
*/
export function findClassesInAttribute(attribute) {
if (attribute.type === 'SvelteAttribute' && attribute.key.name === 'class') {
return attribute.value.flatMap((value) => value.type === 'SvelteLiteral' ? value.value.trim().split(/\s+/u) : []);
}
if (attribute.type === 'SvelteDirective' && attribute.kind === 'Class') {
return [attribute.key.name.name];
}
return [];
}
/**
* Returns name of SvelteElement
*/
export function getNodeName(node) {
return getSimpleNameFromNode(node.name);
}
/**
* Returns true if element is known void element
* {@link https://developer.mozilla.org/en-US/docs/Glossary/Empty_element}
*/
export function isVoidHtmlElement(node) {
return voidElements.includes(getNodeName(node));
}
/**
* Returns true if element is known foreign (SVG or MathML) element
*/
export function isForeignElement(node) {
return svgElements.includes(getNodeName(node)) || mathmlElements.includes(getNodeName(node));
}
export function isSvgElement(node) {
return svgElements.includes(getNodeName(node));
}
export function isMathMLElement(node) {
return mathmlElements.includes(getNodeName(node));
}
/** Checks whether the given identifier node is used as an expression. */
export function isExpressionIdentifier(node) {
const parent = node.parent;
if (!parent) {
return true;
}
if (parent.type === 'MemberExpression') {
return !parent.computed || parent.property !== node;
}
if (parent.type === 'Property' ||
parent.type === 'MethodDefinition' ||
parent.type === 'PropertyDefinition') {
return !parent.computed || parent.key !== node;
}
if (parent.type === 'FunctionDeclaration' ||
parent.type === 'FunctionExpression' ||
parent.type === 'ClassDeclaration' ||
parent.type === 'ClassExpression') {
return parent.id !== node;
}
if (parent.type === 'LabeledStatement' ||
parent.type === 'BreakStatement' ||
parent.type === 'ContinueStatement') {
return parent.label !== node;
}
if (parent.type === 'MetaProperty') {
return parent.property !== node;
}
if (parent.type === 'ImportSpecifier') {
return parent.imported !== node;
}
if (parent.type === 'ExportSpecifier') {
return parent.exported !== node;
}
return true;
}
/** Get simple name from give node */
function getSimpleNameFromNode(node, context) {
if (node.type === 'Identifier' || node.type === 'SvelteName') {
return node.name;
}
if (node.type === 'SvelteMemberExpressionName' ||
(node.type === 'MemberExpression' && !node.computed)) {
return `${getSimpleNameFromNode(node.object, context)}.${getSimpleNameFromNode(node.property, context)}`;
}
// No nodes other than those listed above are currently expected to be used in names.
if (!context) {
throw new Error('Rule context is required');
}
return context.sourceCode.getText(node);
}
/**
* Finds the variable for a given name in the specified node's scope.
* Also determines if the replacement name is already in use.
*
* If the `name` is set to null, this assumes you're adding a new variable
* and reports if it is already in use.
*/
export function findVariableForReplacement(context, node, name, replacementName) {
const scope = getScope(context, node);
let variable = null;
for (const ref of scope.references) {
if (ref.identifier.name === replacementName) {
return { hasConflict: true, variable: null };
}
}
for (const v of scope.variables) {
if (v.name === replacementName) {
return { hasConflict: true, variable: null };
}
if (v.name === name) {
variable = v;
}
}
return { hasConflict: false, variable };
}
/**
* Check if one node is contained withing the subtree of another node.
*/
export function isIn(needle, haystack) {
if (needle === haystack) {
return true;
}
if (needle.parent == null) {
return false;
}
return isIn(needle.parent, haystack);
}

14
node_modules/eslint-plugin-svelte/lib/utils/cache.d.ts generated vendored Normal file
View File

@@ -0,0 +1,14 @@
/**
* Simple cache manager.
*
* refer: https://github.com/mysticatea/eslint-plugin-node/blob/f45c6149be7235c0f7422d1179c25726afeecd83/lib/util/cache.js
*/
/**
* The cache will dispose of each value if the value has not been accessed
* during 5 seconds.
* @returns getter and setter ofr the cache.
*/
export declare function createCache<T>(): {
get: (key: string) => T | null;
set: (key: string, value: T) => void;
};

49
node_modules/eslint-plugin-svelte/lib/utils/cache.js generated vendored Normal file
View File

@@ -0,0 +1,49 @@
/**
* Simple cache manager.
*
* refer: https://github.com/mysticatea/eslint-plugin-node/blob/f45c6149be7235c0f7422d1179c25726afeecd83/lib/util/cache.js
*/
const SKIP_TIME = 5000;
/**
* The cache will dispose of each value if the value has not been accessed
* during 5 seconds.
* @returns getter and setter ofr the cache.
*/
export function createCache() {
const map = new Map();
/**
* Get the cached value of the given key.
* @param key The key to get.
* @returns The cached value or null.
*/
function get(key) {
const entry = map.get(key);
const now = Date.now();
if (entry) {
if (entry.expire > now) {
entry.expire = now + SKIP_TIME;
return entry.value;
}
map.delete(key);
}
return null;
}
/**
* Set the value of the given key.
* @param key The key to set.
* @param value The value to set.
* @returns
*/
function set(key, value) {
const entry = map.get(key);
const expire = Date.now() + SKIP_TIME;
if (entry) {
entry.value = value;
entry.expire = expire;
}
else {
map.set(key, { value, expire });
}
}
return { get, set };
}

View File

@@ -0,0 +1,3 @@
export * from './style-attribute.js';
export * from './resource.js';
export * from './utils.js';

View File

@@ -0,0 +1,3 @@
export * from './style-attribute.js';
export * from './resource.js';
export * from './utils.js';

View File

@@ -0,0 +1 @@
export declare const SHORTHAND_PROPERTIES: Map<string, string[]>;

View File

@@ -0,0 +1,153 @@
export const SHORTHAND_PROPERTIES = new Map([
['margin', ['margin-top', 'margin-bottom', 'margin-left', 'margin-right']],
['padding', ['padding-top', 'padding-bottom', 'padding-left', 'padding-right']],
[
'background',
[
'background-image',
'background-size',
'background-position',
'background-repeat',
'background-origin',
'background-clip',
'background-attachment',
'background-color'
]
],
[
'font',
[
'font-style',
'font-variant',
'font-weight',
'font-stretch',
'font-size',
'font-family',
'line-height'
]
],
[
'border',
[
'border-top-width',
'border-bottom-width',
'border-left-width',
'border-right-width',
'border-top-style',
'border-bottom-style',
'border-left-style',
'border-right-style',
'border-top-color',
'border-bottom-color',
'border-left-color',
'border-right-color'
]
],
['border-top', ['border-top-width', 'border-top-style', 'border-top-color']],
['border-bottom', ['border-bottom-width', 'border-bottom-style', 'border-bottom-color']],
['border-left', ['border-left-width', 'border-left-style', 'border-left-color']],
['border-right', ['border-right-width', 'border-right-style', 'border-right-color']],
[
'border-width',
['border-top-width', 'border-bottom-width', 'border-left-width', 'border-right-width']
],
[
'border-style',
['border-top-style', 'border-bottom-style', 'border-left-style', 'border-right-style']
],
[
'border-color',
['border-top-color', 'border-bottom-color', 'border-left-color', 'border-right-color']
],
['list-style', ['list-style-type', 'list-style-position', 'list-style-image']],
[
'border-radius',
[
'border-top-right-radius',
'border-top-left-radius',
'border-bottom-right-radius',
'border-bottom-left-radius'
]
],
[
'transition',
['transition-delay', 'transition-duration', 'transition-property', 'transition-timing-function']
],
[
'animation',
[
'animation-name',
'animation-duration',
'animation-timing-function',
'animation-delay',
'animation-iteration-count',
'animation-direction',
'animation-fill-mode',
'animation-play-state'
]
],
[
'border-block-end',
['border-block-end-width', 'border-block-end-style', 'border-block-end-color']
],
[
'border-block-start',
['border-block-start-width', 'border-block-start-style', 'border-block-start-color']
],
[
'border-image',
[
'border-image-source',
'border-image-slice',
'border-image-width',
'border-image-outset',
'border-image-repeat'
]
],
[
'border-inline-end',
['border-inline-end-width', 'border-inline-end-style', 'border-inline-end-color']
],
[
'border-inline-start',
['border-inline-start-width', 'border-inline-start-style', 'border-inline-start-color']
],
['column-rule', ['column-rule-width', 'column-rule-style', 'column-rule-color']],
['columns', ['column-width', 'column-count']],
['flex', ['flex-grow', 'flex-shrink', 'flex-basis']],
['flex-flow', ['flex-direction', 'flex-wrap']],
[
'grid',
[
'grid-template-rows',
'grid-template-columns',
'grid-template-areas',
'grid-auto-rows',
'grid-auto-columns',
'grid-auto-flow',
'grid-column-gap',
'grid-row-gap'
]
],
['grid-area', ['grid-row-start', 'grid-column-start', 'grid-row-end', 'grid-column-end']],
['grid-column', ['grid-column-start', 'grid-column-end']],
['grid-gap', ['grid-row-gap', 'grid-column-gap']],
['grid-row', ['grid-row-start', 'grid-row-end']],
['grid-template', ['grid-template-columns', 'grid-template-rows', 'grid-template-areas']],
['outline', ['outline-color', 'outline-style', 'outline-width']],
['text-decoration', ['text-decoration-color', 'text-decoration-style', 'text-decoration-line']],
['text-emphasis', ['text-emphasis-style', 'text-emphasis-color']],
[
'mask',
[
'mask-image',
'mask-mode',
'mask-position',
'mask-size',
'mask-repeat',
'mask-origin',
'mask-clip',
'mask-composite'
]
]
]);

View File

@@ -0,0 +1,46 @@
import type { AST } from 'svelte-eslint-parser';
import type { RuleContext } from '../../types.js';
import type { TSESTree } from '@typescript-eslint/types';
/**
* Parse style attribute value
*/
export declare function parseStyleAttributeValue(node: AST.SvelteAttribute, context: RuleContext): SvelteStyleRoot<AST.SvelteMustacheTagText> | null;
export type SvelteStyleInterpolation = AST.SvelteMustacheTagText | TSESTree.Expression;
export interface SvelteStyleNode<E extends SvelteStyleInterpolation> {
nodes?: SvelteStyleChildNode<E>[];
range: AST.Range;
loc: AST.SourceLocation;
}
export interface SvelteStyleRoot<E extends SvelteStyleInterpolation = SvelteStyleInterpolation> {
type: 'root';
nodes: (SvelteStyleChildNode<E> | SvelteStyleInline<E>)[];
}
export interface SvelteStyleInline<E extends SvelteStyleInterpolation = SvelteStyleInterpolation> extends SvelteStyleNode<E> {
type: 'inline';
node: E;
getInlineStyle(node: TSESTree.Expression): SvelteStyleRoot<TSESTree.Expression> | null;
getAllInlineStyles(): Map<TSESTree.Expression, SvelteStyleRoot<TSESTree.Expression>>;
}
export interface SvelteStyleDeclaration<E extends SvelteStyleInterpolation = SvelteStyleInterpolation> extends SvelteStyleNode<E> {
type: 'decl';
prop: {
name: string;
range: AST.Range;
loc: AST.SourceLocation;
interpolations: E[];
};
value: {
value: string;
range: AST.Range;
loc: AST.SourceLocation;
interpolations: E[];
};
important: boolean;
addInterpolation: (tagOrExpr: E) => void;
unknownInterpolations: E[];
}
export interface SvelteStyleComment extends SvelteStyleNode<never> {
type: 'comment';
addInterpolation: (tagOrExpr: SvelteStyleInterpolation) => void;
}
export type SvelteStyleChildNode<E extends SvelteStyleInterpolation = SvelteStyleInterpolation> = SvelteStyleDeclaration<E> | SvelteStyleComment;

View File

@@ -0,0 +1,266 @@
import Parser from './template-safe-parser.js';
import { Input } from 'postcss';
/** Parse for CSS */
function safeParseCss(css) {
try {
const input = new Input(css);
const parser = new Parser(input);
parser.parse();
return parser.root;
}
catch {
return null;
}
}
const cache = new WeakMap();
/**
* Parse style attribute value
*/
export function parseStyleAttributeValue(node, context) {
if (cache.has(node)) {
return cache.get(node) || null;
}
cache.set(node, null);
if (!node.value?.length) {
return null;
}
const startOffset = node.value[0].range[0];
const sourceCode = context.sourceCode;
const cssCode = node.value.map((value) => sourceCode.getText(value)).join('');
const root = safeParseCss(cssCode);
if (!root) {
return root;
}
const ctx = {
startOffset,
value: node.value,
context
};
const mustacheTags = node.value.filter((v) => v.type === 'SvelteMustacheTag');
const converted = convertRoot(root, mustacheTags, (e) => e.range, ctx);
cache.set(node, converted);
return converted;
}
class IgnoreError extends Error {
}
/** Checks wether the given node is string literal or not */
function isStringLiteral(node) {
return node.type === 'Literal' && typeof node.value === 'string';
}
/** convert root node */
function convertRoot(root, interpolations, getRange, ctx) {
const nodes = [];
for (const child of root.nodes) {
const converted = convertChild(child, ctx);
if (!converted) {
return null;
}
while (interpolations[0]) {
const tagOrExpr = interpolations[0];
if (tagOrExpr.range[1] <= converted.range[0]) {
nodes.push(buildSvelteStyleInline(tagOrExpr));
interpolations.shift();
continue;
}
if (tagOrExpr.range[0] < converted.range[1]) {
try {
converted.addInterpolation(tagOrExpr);
}
catch (e) {
if (e instanceof IgnoreError)
return null;
throw e;
}
interpolations.shift();
continue;
}
break;
}
nodes.push(converted);
}
nodes.push(...interpolations.map(buildSvelteStyleInline));
return {
type: 'root',
nodes
};
/** Build SvelteStyleInline */
function buildSvelteStyleInline(tagOrExpr) {
const inlineStyles = new Map();
let range = null;
/** Get range */
function getRangeForInline() {
if (range) {
return range;
}
return range ?? (range = getRange(tagOrExpr));
}
return {
type: 'inline',
node: tagOrExpr,
get range() {
return getRangeForInline();
},
get loc() {
return toLoc(getRangeForInline(), ctx);
},
getInlineStyle(node) {
return getInlineStyle(node);
},
getAllInlineStyles() {
const allInlineStyles = new Map();
for (const node of extractExpressions(tagOrExpr)) {
const style = getInlineStyle(node);
if (style) {
allInlineStyles.set(node, style);
}
}
return allInlineStyles;
}
};
/** Get inline style node */
function getInlineStyle(node) {
if (node.type === 'SvelteMustacheTag') {
return getInlineStyle(node.expression);
}
if (inlineStyles.has(node)) {
return inlineStyles.get(node) || null;
}
const sourceCode = ctx.context.sourceCode;
inlineStyles.set(node, null);
let converted;
if (isStringLiteral(node)) {
const root = safeParseCss(sourceCode.getText(node).slice(1, -1));
if (!root) {
return null;
}
converted = convertRoot(root, [], () => [0, 0], {
...ctx,
startOffset: node.range[0] + 1
});
}
else if (node.type === 'TemplateLiteral') {
const root = safeParseCss(sourceCode.getText(node).slice(1, -1));
if (!root) {
return null;
}
converted = convertRoot(root, [...node.expressions], (e) => {
const index = node.expressions.indexOf(e);
return [node.quasis[index].range[1] - 2, node.quasis[index + 1].range[0] + 1];
}, {
...ctx,
startOffset: node.range[0] + 1
});
}
else {
return null;
}
inlineStyles.set(node, converted);
return converted;
}
/** Extract all expressions */
function* extractExpressions(node) {
if (node.type === 'SvelteMustacheTag') {
yield* extractExpressions(node.expression);
}
else if (isStringLiteral(node)) {
yield node;
}
else if (node.type === 'TemplateLiteral') {
yield node;
}
else if (node.type === 'ConditionalExpression') {
yield* extractExpressions(node.consequent);
yield* extractExpressions(node.alternate);
}
else if (node.type === 'LogicalExpression') {
yield* extractExpressions(node.left);
yield* extractExpressions(node.right);
}
}
}
}
/** convert child node */
function convertChild(node, ctx) {
const range = convertRange(node, ctx);
if (node.type === 'decl') {
const propRange = [range[0], range[0] + node.prop.length];
const declValueStartIndex = propRange[1] + (node.raws.between || '').length;
const valueRange = [
declValueStartIndex,
declValueStartIndex + (node.raws.value?.value || node.value).length
];
const prop = {
name: node.prop,
range: propRange,
get loc() {
return toLoc(propRange, ctx);
},
interpolations: []
};
const value = {
value: node.value,
range: valueRange,
get loc() {
return toLoc(valueRange, ctx);
},
interpolations: []
};
const unknownInterpolations = [];
return {
type: 'decl',
prop,
value,
important: node.important,
range,
get loc() {
return toLoc(range, ctx);
},
addInterpolation(tagOrExpr) {
const index = tagOrExpr.range[0];
if (prop.range[0] <= index && index < prop.range[1]) {
prop.interpolations.push(tagOrExpr);
return;
}
if (value.range[0] <= index && index < value.range[1]) {
value.interpolations.push(tagOrExpr);
return;
}
unknownInterpolations.push(tagOrExpr);
},
unknownInterpolations
};
}
if (node.type === 'comment') {
return {
type: 'comment',
range,
get loc() {
return toLoc(range, ctx);
},
addInterpolation: () => {
throw new IgnoreError();
}
};
}
if (node.type === 'atrule') {
// unexpected node
return null;
}
if (node.type === 'rule') {
// unexpected node
return null;
}
// unknown node
return null;
}
/** convert range */
function convertRange(node, ctx) {
return [ctx.startOffset + node.source.start.offset, ctx.startOffset + node.source.end.offset];
}
/** convert range */
function toLoc(range, ctx) {
return {
start: ctx.context.sourceCode.getLocFromIndex(range[0]),
end: ctx.context.sourceCode.getLocFromIndex(range[1])
};
}

View File

@@ -0,0 +1,5 @@
import SafeParser from 'postcss-safe-parser/lib/safe-parser.js';
declare class TemplateSafeParser extends SafeParser {
protected createTokenizer(): void;
}
export default TemplateSafeParser;

View File

@@ -0,0 +1,8 @@
import SafeParser from 'postcss-safe-parser/lib/safe-parser.js';
import templateTokenize from './template-tokenize.js';
class TemplateSafeParser extends SafeParser {
createTokenizer() {
this.tokenizer = templateTokenize(this.input, { ignoreErrors: true });
}
}
export default TemplateSafeParser;

View File

@@ -0,0 +1,6 @@
import type { Tokenizer } from 'postcss/lib/tokenize';
import tokenize from 'postcss/lib/tokenize';
type Tokenize = typeof tokenize;
/** Tokenize */
declare function templateTokenize(...args: Parameters<Tokenize>): Tokenizer;
export default templateTokenize;

View File

@@ -0,0 +1,36 @@
import tokenize from 'postcss/lib/tokenize';
/** Tokenize */
function templateTokenize(...args) {
const tokenizer = tokenize(...args);
/** nextToken */
function nextToken(...args) {
const returned = [];
let token, lastPos;
let depth = 0;
while ((token = tokenizer.nextToken(...args))) {
if (token[0] !== 'word') {
if (token[0] === '{') {
++depth;
}
else if (token[0] === '}') {
--depth;
}
}
if (depth || returned.length) {
lastPos = token[3] || token[2] || lastPos;
returned.push(token);
}
if (!depth) {
break;
}
}
if (returned.length) {
token = ['word', returned.map((token) => token[1]).join(''), returned[0][2], lastPos];
}
return token;
}
return Object.assign({}, tokenizer, {
nextToken
});
}
export default templateTokenize;

View File

@@ -0,0 +1,12 @@
/**
* Checks whether given property name has vender prefix
*/
export declare function hasVendorPrefix(prop: string): boolean;
/**
* Get the vender prefix from given property name
*/
export declare function getVendorPrefix(prop: string): string;
/**
* Strip the vender prefix
*/
export declare function stripVendorPrefix(prop: string): string;

View File

@@ -0,0 +1,18 @@
/**
* Checks whether given property name has vender prefix
*/
export function hasVendorPrefix(prop) {
return Boolean(getVendorPrefix(prop));
}
/**
* Get the vender prefix from given property name
*/
export function getVendorPrefix(prop) {
return /^-\w+-/u.exec(prop)?.[0] || '';
}
/**
* Strip the vender prefix
*/
export function stripVendorPrefix(prop) {
return prop.slice(getVendorPrefix(prop).length);
}

View File

@@ -0,0 +1,7 @@
import type { AST } from 'svelte-eslint-parser';
export declare enum ElementOccurenceCount {
ZeroOrOne = 0,
One = 1,
ZeroToInf = 2
}
export declare function elementOccurrenceCount(element: AST.SvelteHTMLNode): ElementOccurenceCount;

View File

@@ -0,0 +1,43 @@
export var ElementOccurenceCount;
(function (ElementOccurenceCount) {
ElementOccurenceCount[ElementOccurenceCount["ZeroOrOne"] = 0] = "ZeroOrOne";
ElementOccurenceCount[ElementOccurenceCount["One"] = 1] = "One";
ElementOccurenceCount[ElementOccurenceCount["ZeroToInf"] = 2] = "ZeroToInf";
})(ElementOccurenceCount || (ElementOccurenceCount = {}));
function multiplyCounts(left, right) {
if (left === ElementOccurenceCount.One) {
return right;
}
if (right === ElementOccurenceCount.One) {
return left;
}
if (left === right) {
return left;
}
return ElementOccurenceCount.ZeroToInf;
}
function childElementOccurenceCount(parent) {
if (parent === null) {
return ElementOccurenceCount.One;
}
if ([
'SvelteIfBlock',
'SvelteElseBlock',
'SvelteAwaitBlock',
'SvelteAwaitPendingBlock',
'SvelteAwaitThenBlock',
'SvelteAwaitCatchBlock'
].includes(parent.type)) {
return ElementOccurenceCount.ZeroOrOne;
}
if (['SvelteEachBlock', 'SvelteSnippetBlock'].includes(parent.type) ||
(parent.type === 'SvelteElement' && parent.kind === 'component')) {
return ElementOccurenceCount.ZeroToInf;
}
return ElementOccurenceCount.One;
}
export function elementOccurrenceCount(element) {
const parentCount = element.parent !== null ? elementOccurrenceCount(element.parent) : ElementOccurenceCount.One;
const parentChildCount = childElementOccurenceCount(element.parent);
return multiplyCounts(parentCount, parentChildCount);
}

View File

@@ -0,0 +1,3 @@
export declare const voidElements: string[];
export declare const svgElements: string[];
export declare const mathmlElements: string[];

View File

@@ -0,0 +1,138 @@
export const voidElements = [
'area',
'base',
'br',
'col',
'embed',
'hr',
'img',
'input',
'keygen',
'link',
'menuitem',
'meta',
'param',
'source',
'track',
'wbr'
];
export const svgElements = [
'altGlyph',
'altGlyphDef',
'altGlyphItem',
'animate',
'animateColor',
'animateMotion',
'animateTransform',
'circle',
'clipPath',
'color-profile',
'cursor',
'defs',
'desc',
'discard',
'ellipse',
'feBlend',
'feColorMatrix',
'feComponentTransfer',
'feComposite',
'feConvolveMatrix',
'feDiffuseLighting',
'feDisplacementMap',
'feDistantLight',
'feDropShadow',
'feFlood',
'feFuncA',
'feFuncB',
'feFuncG',
'feFuncR',
'feGaussianBlur',
'feImage',
'feMerge',
'feMergeNode',
'feMorphology',
'feOffset',
'fePointLight',
'feSpecularLighting',
'feSpotLight',
'feTile',
'feTurbulence',
'filter',
'font',
'font-face',
'font-face-format',
'font-face-name',
'font-face-src',
'font-face-uri',
'foreignObject',
'g',
'glyph',
'glyphRef',
'hatch',
'hatchpath',
'hkern',
'image',
'line',
'linearGradient',
'marker',
'mask',
'mesh',
'meshgradient',
'meshpatch',
'meshrow',
'metadata',
'missing-glyph',
'mpath',
'path',
'pattern',
'polygon',
'polyline',
'radialGradient',
'rect',
'set',
'solidcolor',
'stop',
'svg',
'switch',
'symbol',
'text',
'textPath',
'tref',
'tspan',
'unknown',
'use',
'view',
'vkern'
];
export const mathmlElements = [
'annotation',
'annotation-xml',
'maction',
'math',
'merror',
'mfrac',
'mi',
'mmultiscripts',
'mn',
'mo',
'mover',
'mpadded',
'mphantom',
'mprescripts',
'mroot',
'mrow',
'ms',
'mspace',
'msqrt',
'mstyle',
'msub',
'msubsup',
'msup',
'mtable',
'mtd',
'mtext',
'mtr',
'munder',
'munderover',
'semantics'
];

View File

@@ -0,0 +1,25 @@
import type { RuleListener, RuleContext, RuleModule } from '../types.js';
import type { TSESTree } from '@typescript-eslint/types';
import type { AST as SvAST } from 'svelte-eslint-parser';
/**
* Define the wrapped core rule.
*/
export declare function defineWrapperListener(coreRule: RuleModule, context: RuleContext, proxyOptions: {
createListenerProxy?: (listener: RuleListener) => RuleListener;
}): RuleListener;
/**
* Get the proxy node
*/
export declare function getProxyNode(node: {
type: string;
}, properties: any): any;
/**
* Build the proxy rule listener
*/
export declare function buildProxyListener(base: RuleListener, convertNode: (node: SvAST.SvelteNode | (TSESTree.Node & {
parent: SvAST.SvelteNode | TSESTree.Node | null;
})) => any): RuleListener;
/**
* Get the core rule implementation from the rule name
*/
export declare function getCoreRule(ruleName: string): RuleModule;

View File

@@ -0,0 +1,66 @@
import { Linter } from 'eslint';
import Module from 'module';
const require = Module.createRequire(import.meta.url);
/**
* Define the wrapped core rule.
*/
export function defineWrapperListener(coreRule, context, proxyOptions) {
const listener = coreRule.create(context);
const svelteListener = proxyOptions.createListenerProxy?.(listener) ?? listener;
return svelteListener;
}
/**
* Get the proxy node
*/
export function getProxyNode(node, properties) {
const cache = {};
return new Proxy(node, {
get(_t, key) {
if (key in cache) {
return cache[key];
}
if (key in properties) {
return (cache[key] = properties[key]);
}
return node[key];
}
});
}
/**
* Build the proxy rule listener
*/
export function buildProxyListener(base, convertNode) {
const listeners = {};
for (const [key, listener] of Object.entries(base)) {
listeners[key] = function (...args) {
listener.call(this, ...args.map((arg) => {
if (typeof arg === 'object' &&
'type' in arg &&
typeof arg.type === 'string' &&
'range' in arg) {
return convertNode(arg);
}
return arg;
}));
};
}
return listeners;
}
let ruleMap = null;
/**
* Get the core rule implementation from the rule name
*/
export function getCoreRule(ruleName) {
try {
const map = ruleMap
? ruleMap
: (ruleMap = new Linter().getRules());
return map.get(ruleName);
}
catch {
// getRules() is no longer available in flat config.
}
const { builtinRules } = require('eslint/use-at-your-own-risk');
ruleMap = builtinRules;
return builtinRules.get(ruleName) || null;
}

View File

@@ -0,0 +1 @@
export declare const EVENT_NAMES: string[];

349
node_modules/eslint-plugin-svelte/lib/utils/events.js generated vendored Normal file
View File

@@ -0,0 +1,349 @@
// see: https://github.com/sveltejs/svelte/blob/a129592e5b248a734a68da6e9028941803a3d063/packages/svelte/elements.d.ts#L83
export const EVENT_NAMES = [
// Clipboard Events
'on:copy',
'oncopy',
'oncopycapture',
'on:cut',
'oncut',
'oncutcapture',
'on:paste',
'onpaste',
'onpastecapture',
// Composition Events
'on:compositionend',
'oncompositionend',
'oncompositionendcapture',
'on:compositionstart',
'oncompositionstart',
'oncompositionstartcapture',
'on:compositionupdate',
'oncompositionupdate',
'oncompositionupdatecapture',
// Focus Events
'on:focus',
'onfocus',
'onfocuscapture',
'on:focusin',
'onfocusin',
'onfocusincapture',
'on:focusout',
'onfocusout',
'onfocusoutcapture',
'on:blur',
'onblur',
'onblurcapture',
// Form Events
'on:change',
'onchange',
'onchangecapture',
'on:beforeinput',
'onbeforeinput',
'onbeforeinputcapture',
// oninput can be either an InputEvent or an Event, depending on the target element (input, textarea etc).
'on:input',
'oninput',
'oninputcapture',
'on:reset',
'onreset',
'onresetcapture',
'on:submit',
'onsubmit',
'onsubmitcapture',
'on:invalid',
'oninvalid',
'oninvalidcapture',
'on:formdata',
'onformdata',
'onformdatacapture',
// Image Events
'on:load',
'onload',
'onloadcapture',
'on:error',
'onerror',
'onerrorcapture',
// Popover Events
'on:beforetoggle',
'onbeforetoggle',
'onbeforetogglecapture',
'on:toggle',
'ontoggle',
'ontogglecapture',
// Content visibility Events
'on:contentvisibilityautostatechange',
'oncontentvisibilityautostatechange',
'oncontentvisibilityautostatechangecapture',
// Keyboard Events
'on:keydown',
'onkeydown',
'onkeydowncapture',
'on:keypress',
'onkeypress',
'onkeypresscapture',
'on:keyup',
'onkeyup',
'onkeyupcapture',
// Media Events
'on:abort',
'onabort',
'onabortcapture',
'on:canplay',
'oncanplay',
'oncanplaycapture',
'on:canplaythrough',
'oncanplaythrough',
'oncanplaythroughcapture',
'on:cuechange',
'oncuechange',
'oncuechangecapture',
'on:durationchange',
'ondurationchange',
'ondurationchangecapture',
'on:emptied',
'onemptied',
'onemptiedcapture',
'on:encrypted',
'onencrypted',
'onencryptedcapture',
'on:ended',
'onended',
'onendedcapture',
'on:loadeddata',
'onloadeddata',
'onloadeddatacapture',
'on:loadedmetadata',
'onloadedmetadata',
'onloadedmetadatacapture',
'on:loadstart',
'onloadstart',
'onloadstartcapture',
'on:pause',
'onpause',
'onpausecapture',
'on:play',
'onplay',
'onplaycapture',
'on:playing',
'onplaying',
'onplayingcapture',
'on:progress',
'onprogress',
'onprogresscapture',
'on:ratechange',
'onratechange',
'onratechangecapture',
'on:seeked',
'onseeked',
'onseekedcapture',
'on:seeking',
'onseeking',
'onseekingcapture',
'on:stalled',
'onstalled',
'onstalledcapture',
'on:suspend',
'onsuspend',
'onsuspendcapture',
'on:timeupdate',
'ontimeupdate',
'ontimeupdatecapture',
'on:volumechange',
'onvolumechange',
'onvolumechangecapture',
'on:waiting',
'onwaiting',
'onwaitingcapture',
// MouseEvents
'on:auxclick',
'onauxclick',
'onauxclickcapture',
'on:click',
'onclick',
'onclickcapture',
'on:contextmenu',
'oncontextmenu',
'oncontextmenucapture',
'on:dblclick',
'ondblclick',
'ondblclickcapture',
'on:drag',
'ondrag',
'ondragcapture',
'on:dragend',
'ondragend',
'ondragendcapture',
'on:dragenter',
'ondragenter',
'ondragentercapture',
'on:dragexit',
'ondragexit',
'ondragexitcapture',
'on:dragleave',
'ondragleave',
'ondragleavecapture',
'on:dragover',
'ondragover',
'ondragovercapture',
'on:dragstart',
'ondragstart',
'ondragstartcapture',
'on:drop',
'ondrop',
'ondropcapture',
'on:mousedown',
'onmousedown',
'onmousedowncapture',
'on:mouseenter',
'onmouseenter',
'on:mouseleave',
'onmouseleave',
'on:mousemove',
'onmousemove',
'onmousemovecapture',
'on:mouseout',
'onmouseout',
'onmouseoutcapture',
'on:mouseover',
'onmouseover',
'onmouseovercapture',
'on:mouseup',
'onmouseup',
'onmouseupcapture',
// Selection Events
'on:select',
'onselect',
'onselectcapture',
'on:selectionchange',
'onselectionchange',
'onselectionchangecapture',
'on:selectstart',
'onselectstart',
'onselectstartcapture',
// Touch Events
'on:touchcancel',
'ontouchcancel',
'ontouchcancelcapture',
'on:touchend',
'ontouchend',
'ontouchendcapture',
'on:touchmove',
'ontouchmove',
'ontouchmovecapture',
'on:touchstart',
'ontouchstart',
'ontouchstartcapture',
// Pointer Events
'on:gotpointercapture',
'ongotpointercapture',
'ongotpointercapturecapture',
'on:pointercancel',
'onpointercancel',
'onpointercancelcapture',
'on:pointerdown',
'onpointerdown',
'onpointerdowncapture',
'on:pointerenter',
'onpointerenter',
'onpointerentercapture',
'on:pointerleave',
'onpointerleave',
'onpointerleavecapture',
'on:pointermove',
'onpointermove',
'onpointermovecapture',
'on:pointerout',
'onpointerout',
'onpointeroutcapture',
'on:pointerover',
'onpointerover',
'onpointerovercapture',
'on:pointerup',
'onpointerup',
'onpointerupcapture',
'on:lostpointercapture',
'onlostpointercapture',
'onlostpointercapturecapture',
// Gamepad Events
'on:gamepadconnected',
'ongamepadconnected',
'on:gamepaddisconnected',
'ongamepaddisconnected',
// UI Events
'on:scroll',
'onscroll',
'onscrollcapture',
'on:scrollend',
'onscrollend',
'onscrollendcapture',
'on:resize',
'onresize',
'onresizecapture',
// Wheel Events
'on:wheel',
'onwheel',
'onwheelcapture',
// Animation Events
'on:animationstart',
'onanimationstart',
'onanimationstartcapture',
'on:animationend',
'onanimationend',
'onanimationendcapture',
'on:animationiteration',
'onanimationiteration',
'onanimationiterationcapture',
// Transition Events
'on:transitionstart',
'ontransitionstart',
'ontransitionstartcapture',
'on:transitionrun',
'ontransitionrun',
'ontransitionruncapture',
'on:transitionend',
'ontransitionend',
'ontransitionendcapture',
'on:transitioncancel',
'ontransitioncancel',
'ontransitioncancelcapture',
// Svelte Transition Events
'on:outrostart',
'onoutrostart',
'onoutrostartcapture',
'on:outroend',
'onoutroend',
'onoutroendcapture',
'on:introstart',
'onintrostart',
'onintrostartcapture',
'on:introend',
'onintroend',
'onintroendcapture',
// Message Events
'on:message',
'onmessage',
'onmessagecapture',
'on:messageerror',
'onmessageerror',
'onmessageerrorcapture',
// Document Events
'on:visibilitychange',
'onvisibilitychange',
'onvisibilitychangecapture',
// Global Events
'on:beforematch',
'onbeforematch',
'onbeforematchcapture',
'on:cancel',
'oncancel',
'oncancelcapture',
'on:close',
'onclose',
'onclosecapture',
'on:fullscreenchange',
'onfullscreenchange',
'onfullscreenchangecapture',
'on:fullscreenerror',
'onfullscreenerror',
'onfullscreenerrorcapture'
];

View File

@@ -0,0 +1,6 @@
import type { TSESTree } from '@typescript-eslint/types';
import type { RuleContext } from '../types.js';
import type { AST } from 'svelte-eslint-parser';
export declare function extractExpressionPrefixVariable(context: RuleContext, expression: TSESTree.Expression): TSESTree.Identifier | null;
export declare function extractExpressionPrefixLiteral(context: RuleContext, expression: AST.SvelteLiteral | TSESTree.Node): string | null;
export declare function extractExpressionSuffixLiteral(context: RuleContext, expression: AST.SvelteLiteral | TSESTree.Node): string | null;

View File

@@ -0,0 +1,148 @@
import { FindVariableContext } from './ast-utils.js';
export function extractExpressionPrefixVariable(context, expression) {
return extractExpressionPrefixVariableInternal(new FindVariableContext(context), expression);
}
export function extractExpressionPrefixLiteral(context, expression) {
return extractExpressionPrefixLiteralInternal(new FindVariableContext(context), expression);
}
export function extractExpressionSuffixLiteral(context, expression) {
return extractExpressionSuffixLiteralInternal(new FindVariableContext(context), expression);
}
// Variable prefix extraction
function extractExpressionPrefixVariableInternal(context, expression) {
switch (expression.type) {
case 'BinaryExpression':
return extractBinaryExpressionPrefixVariable(context, expression);
case 'Identifier':
return extractVariablePrefixVariable(context, expression);
case 'MemberExpression':
return extractMemberExpressionPrefixVariable(expression);
case 'TemplateLiteral':
return extractTemplateLiteralPrefixVariable(context, expression);
default:
return null;
}
}
function extractBinaryExpressionPrefixVariable(context, expression) {
return expression.left.type !== 'PrivateIdentifier'
? extractExpressionPrefixVariableInternal(context, expression.left)
: null;
}
function extractVariablePrefixVariable(context, expression) {
const variable = context.findVariable(expression);
if (variable === null ||
variable.identifiers.length !== 1 ||
variable.identifiers[0].parent.type !== 'VariableDeclarator' ||
variable.identifiers[0].parent.init === null) {
return expression;
}
return (extractExpressionPrefixVariableInternal(context, variable.identifiers[0].parent.init) ??
expression);
}
function extractMemberExpressionPrefixVariable(expression) {
return expression.property.type === 'Identifier' ? expression.property : null;
}
function extractTemplateLiteralPrefixVariable(context, expression) {
const literalParts = [...expression.expressions, ...expression.quasis].sort((a, b) => a.range[0] < b.range[0] ? -1 : 1);
for (const part of literalParts) {
if (part.type === 'TemplateElement' && part.value.raw === '') {
// Skip empty quasi in the begining
continue;
}
if (part.type !== 'TemplateElement') {
return extractExpressionPrefixVariableInternal(context, part);
}
return null;
}
return null;
}
// Literal prefix extraction
function extractExpressionPrefixLiteralInternal(context, expression) {
switch (expression.type) {
case 'BinaryExpression':
return extractBinaryExpressionPrefixLiteral(context, expression);
case 'Identifier':
return extractVariablePrefixLiteral(context, expression);
case 'Literal':
return typeof expression.value === 'string' ? expression.value : null;
case 'SvelteLiteral':
return expression.value;
case 'TemplateLiteral':
return extractTemplateLiteralPrefixLiteral(context, expression);
default:
return null;
}
}
function extractBinaryExpressionPrefixLiteral(context, expression) {
return expression.left.type !== 'PrivateIdentifier'
? extractExpressionPrefixLiteralInternal(context, expression.left)
: null;
}
function extractVariablePrefixLiteral(context, expression) {
const variable = context.findVariable(expression);
if (variable === null ||
variable.identifiers.length !== 1 ||
variable.identifiers[0].parent.type !== 'VariableDeclarator' ||
variable.identifiers[0].parent.init === null) {
return null;
}
return extractExpressionPrefixLiteralInternal(context, variable.identifiers[0].parent.init);
}
function extractTemplateLiteralPrefixLiteral(context, expression) {
const literalParts = [...expression.expressions, ...expression.quasis].sort((a, b) => a.range[0] < b.range[0] ? -1 : 1);
for (const part of literalParts) {
if (part.type === 'TemplateElement') {
if (part.value.raw === '') {
// Skip empty quasi
continue;
}
return part.value.raw;
}
return extractExpressionPrefixLiteralInternal(context, part);
}
return null;
}
// Literal suffix extraction
function extractExpressionSuffixLiteralInternal(context, expression) {
switch (expression.type) {
case 'BinaryExpression':
return extractBinaryExpressionSuffixLiteral(context, expression);
case 'Identifier':
return extractVariableSuffixLiteral(context, expression);
case 'Literal':
return typeof expression.value === 'string' ? expression.value : null;
case 'SvelteLiteral':
return expression.value;
case 'TemplateLiteral':
return extractTemplateLiteralSuffixLiteral(context, expression);
default:
return null;
}
}
function extractBinaryExpressionSuffixLiteral(context, expression) {
return extractExpressionSuffixLiteralInternal(context, expression.right);
}
function extractVariableSuffixLiteral(context, expression) {
const variable = context.findVariable(expression);
if (variable === null ||
variable.identifiers.length !== 1 ||
variable.identifiers[0].parent.type !== 'VariableDeclarator' ||
variable.identifiers[0].parent.init === null) {
return null;
}
return extractExpressionSuffixLiteralInternal(context, variable.identifiers[0].parent.init);
}
function extractTemplateLiteralSuffixLiteral(context, expression) {
const literalParts = [...expression.expressions, ...expression.quasis].sort((a, b) => a.range[0] < b.range[0] ? -1 : 1);
for (const part of literalParts.reverse()) {
if (part.type === 'TemplateElement') {
if (part.value.raw === '') {
// Skip empty quasi
continue;
}
return part.value.raw;
}
return extractExpressionSuffixLiteralInternal(context, part);
}
return null;
}

View File

@@ -0,0 +1,4 @@
/**
* Get first found package path from node_modules
*/
export declare function getNodeModule(packageName: string, startPath?: string): string | null;

View File

@@ -0,0 +1,64 @@
import fs from 'fs';
import path from 'path';
import { createCache } from './cache.js';
const isRunOnBrowser = !fs.readFileSync;
const nodeModuleCache = createCache();
const nodeModulesCache = createCache();
/**
* Find package directory in node_modules
*/
function findPackageInNodeModules(dir, packageName) {
if (isRunOnBrowser)
return null;
const nodeModulesPath = path.join(dir, 'node_modules');
const packagePath = path.join(nodeModulesPath, packageName);
try {
const stats = fs.statSync(packagePath);
if (stats.isDirectory()) {
return packagePath;
}
}
catch {
// ignore if directory not found
}
return null;
}
/**
* Get first found package path from node_modules
*/
export function getNodeModule(packageName, startPath = 'a.js') {
if (isRunOnBrowser)
return null;
const cacheKey = `${startPath}:${packageName}`;
const cached = nodeModulesCache.get(cacheKey);
if (cached) {
return cached[0] ?? null;
}
const startDir = path.dirname(path.resolve(startPath));
let dir = startDir;
let prevDir = '';
do {
// check cache
const cachePath = nodeModuleCache.get(`${dir}:${packageName}`);
if (cachePath) {
if (cachePath !== null) {
nodeModulesCache.set(cacheKey, [cachePath]);
return cachePath;
}
}
else {
// search new
const packagePath = findPackageInNodeModules(dir, packageName);
nodeModuleCache.set(`${dir}:${packageName}`, packagePath);
if (packagePath) {
nodeModulesCache.set(cacheKey, [packagePath]);
return packagePath;
}
}
// go to parent
prevDir = dir;
dir = path.resolve(dir, '..');
} while (dir !== prevDir);
nodeModulesCache.set(cacheKey, []);
return null;
}

View File

@@ -0,0 +1,22 @@
/**
* refer: https://github.com/mysticatea/eslint-plugin-node/blob/f45c6149be7235c0f7422d1179c25726afeecd83/lib/util/get-package-json.js
*/
type PackageJson = {
name?: unknown;
dependencies?: {
[key in string]?: unknown;
};
devDependencies?: {
[key in string]?: unknown;
};
filePath: string;
};
/**
* Gets a `package.json` data.
* The data is cached if found, then it's used after.
* @param startPath A file path to lookup.
* @returns A found `package.json` data or `null`.
* This object have additional property `filePath`.
*/
export declare function getPackageJsons(startPath?: string): PackageJson[];
export {};

View File

@@ -0,0 +1,70 @@
/**
* refer: https://github.com/mysticatea/eslint-plugin-node/blob/f45c6149be7235c0f7422d1179c25726afeecd83/lib/util/get-package-json.js
*/
import fs from 'fs';
import path from 'path';
import { createCache } from './cache.js';
const isRunOnBrowser = !fs.readFileSync;
const packageJsonCache = createCache();
const packageJsonsCache = createCache();
/**
* Reads the `package.json` data in a given path.
*
* Don't cache the data.
*
* @param dir The path to a directory to read.
* @returns The read `package.json` data, or null.
*/
function readPackageJson(dir) {
if (isRunOnBrowser)
return null;
const filePath = path.join(dir, 'package.json');
try {
const text = fs.readFileSync(filePath, 'utf8');
const data = JSON.parse(text);
if (typeof data === 'object' && data !== null) {
data.filePath = filePath;
return data;
}
}
catch {
// do nothing.
}
return null;
}
/**
* Gets a `package.json` data.
* The data is cached if found, then it's used after.
* @param startPath A file path to lookup.
* @returns A found `package.json` data or `null`.
* This object have additional property `filePath`.
*/
export function getPackageJsons(startPath = 'a.js') {
if (isRunOnBrowser)
return [];
const cached = packageJsonsCache.get(startPath);
if (cached) {
return cached;
}
const packageJsons = [];
const startDir = path.dirname(path.resolve(startPath));
let dir = startDir;
let prevDir = '';
let data = null;
do {
data = packageJsonCache.get(dir);
if (data) {
packageJsons.push(data);
}
data = readPackageJson(dir);
if (data) {
packageJsonCache.set(dir, data);
packageJsons.push(data);
}
// Go to next.
prevDir = dir;
dir = path.resolve(dir, '..');
} while (dir !== prevDir);
packageJsonsCache.set(startDir, packageJsons);
return packageJsons;
}

View File

@@ -0,0 +1,9 @@
import type { RuleModule, PartialRuleModule, PartialRuleMetaData } from '../types.js';
import { type SvelteContext } from '../utils/svelte-context.js';
export declare function shouldRun(svelteContext: SvelteContext | null, conditions: PartialRuleMetaData['conditions']): boolean;
/**
* Define the rule.
* @param ruleName ruleName
* @param rule rule module
*/
export declare function createRule(ruleName: string, rule: PartialRuleModule): RuleModule;

57
node_modules/eslint-plugin-svelte/lib/utils/index.js generated vendored Normal file
View File

@@ -0,0 +1,57 @@
import { getSvelteContext } from '../utils/svelte-context.js';
function doesNotSatisfy(actual, expected) {
if (expected == null || expected.length === 0) {
return false;
}
return !expected.includes(actual);
}
function satisfiesCondition(condition, svelteContext) {
if (doesNotSatisfy(svelteContext.svelteVersion, condition.svelteVersions) ||
doesNotSatisfy(svelteContext.svelteFileType, condition.svelteFileTypes) ||
doesNotSatisfy(svelteContext.runes, condition.runes) ||
doesNotSatisfy(svelteContext.svelteKitVersion, condition.svelteKitVersions) ||
doesNotSatisfy(svelteContext.svelteKitFileType, condition.svelteKitFileTypes)) {
return false;
}
return true;
}
// export for testing
export function shouldRun(svelteContext, conditions) {
// If svelteContext is null, it means the rule might be executed based on the analysis result of a different parser.
// In this case, always execute the rule.
if (svelteContext == null || conditions == null || conditions.length === 0) {
return true;
}
for (const condition of conditions) {
if (satisfiesCondition(condition, svelteContext)) {
return true;
}
}
return false;
}
/**
* Define the rule.
* @param ruleName ruleName
* @param rule rule module
*/
export function createRule(ruleName, rule) {
return {
meta: {
...rule.meta,
docs: {
...rule.meta.docs,
url: `https://sveltejs.github.io/eslint-plugin-svelte/rules/${ruleName}/`,
ruleId: `svelte/${ruleName}`,
ruleName
}
},
create(context) {
const { conditions } = rule.meta;
const svelteContext = getSvelteContext(context);
if (!shouldRun(svelteContext, conditions)) {
return {};
}
return rule.create(context);
}
};
}

View File

@@ -0,0 +1,12 @@
export declare class LinesAndColumns {
private readonly lineStartIndices;
constructor(code: string);
getLocFromIndex(index: number): {
line: number;
column: number;
};
getIndexFromLoc(loc: {
line: number;
column: number;
}): number;
}

View File

@@ -0,0 +1,53 @@
export class LinesAndColumns {
constructor(code) {
const len = code.length;
const lineStartIndices = [0];
for (let index = 0; index < len; index++) {
const c = code[index];
if (c === '\r') {
const next = code[index + 1] || '';
if (next === '\n') {
index++;
}
lineStartIndices.push(index + 1);
}
else if (c === '\n') {
lineStartIndices.push(index + 1);
}
}
this.lineStartIndices = lineStartIndices;
}
getLocFromIndex(index) {
const lineNumber = sortedLastIndex(this.lineStartIndices, index);
return {
line: lineNumber,
column: index - this.lineStartIndices[lineNumber - 1]
};
}
getIndexFromLoc(loc) {
const lineStartIndex = this.lineStartIndices[loc.line - 1];
const positionIndex = lineStartIndex + loc.column;
return positionIndex;
}
}
/**
* Uses a binary search to determine the highest index at which value should be inserted into array in order to maintain its sort order.
*/
function sortedLastIndex(array, value) {
let lower = 0;
let upper = array.length;
while (lower < upper) {
const mid = Math.floor(lower + (upper - lower) / 2);
const target = array[mid];
if (target < value) {
lower = mid + 1;
}
else if (target > value) {
upper = mid;
}
else {
return mid + 1;
}
}
return upper;
}

View File

@@ -0,0 +1,5 @@
import type { RuleContext } from '../types.js';
/**
* Load module
*/
export declare function loadModule<R>(context: RuleContext, name: string): R | null;

View File

@@ -0,0 +1,45 @@
import Module from 'module';
import path from 'path';
const cache = new WeakMap();
const cache4b = new Map();
/**
* Load module
*/
export function loadModule(context, name) {
const key = context.sourceCode.ast;
let modules = cache.get(key);
if (!modules) {
modules = {};
cache.set(key, modules);
}
const mod = modules[name] || cache4b.get(name);
if (mod)
return mod;
try {
// load from cwd
const cwd = context.cwd ?? process.cwd();
const relativeTo = path.join(cwd, '__placeholder__.js');
return (modules[name] = Module.createRequire(relativeTo)(name));
}
catch {
// ignore
}
for (const relativeTo of [
// load from lint file name
context.filename,
// load from lint file name (physical)
context.physicalFilename,
// load from this plugin module
typeof __filename !== 'undefined' ? __filename : ''
]) {
if (relativeTo) {
try {
return (modules[name] = Module.createRequire(relativeTo)(name));
}
catch {
// ignore
}
}
}
return null;
}

View File

@@ -0,0 +1,17 @@
/**
* Convert a string to the `RegExp`.
* Normal strings (e.g. `"foo"`) is converted to `/^foo$/` of `RegExp`.
* Strings like `"/^foo/i"` are converted to `/^foo/i` of `RegExp`.
*
* @param {string} string The string to convert.
* @returns {RegExp} Returns the `RegExp`.
*/
export declare function toRegExp(string: string): {
test(s: string): boolean;
};
/**
* Checks whether given string is regexp string
* @param {string} string
* @returns {boolean}
*/
export declare function isRegExp(string: string): boolean;

24
node_modules/eslint-plugin-svelte/lib/utils/regexp.js generated vendored Normal file
View File

@@ -0,0 +1,24 @@
const RE_REGEXP_STR = /^\/(.+)\/([A-Za-z]*)$/u;
/**
* Convert a string to the `RegExp`.
* Normal strings (e.g. `"foo"`) is converted to `/^foo$/` of `RegExp`.
* Strings like `"/^foo/i"` are converted to `/^foo/i` of `RegExp`.
*
* @param {string} string The string to convert.
* @returns {RegExp} Returns the `RegExp`.
*/
export function toRegExp(string) {
const parts = RE_REGEXP_STR.exec(string);
if (parts) {
return new RegExp(parts[1], parts[2]);
}
return { test: (s) => s === string };
}
/**
* Checks whether given string is regexp string
* @param {string} string
* @returns {boolean}
*/
export function isRegExp(string) {
return Boolean(RE_REGEXP_STR.test(string));
}

View File

@@ -0,0 +1,2 @@
import type { RuleModule } from '../types.js';
export declare const rules: RuleModule[];

174
node_modules/eslint-plugin-svelte/lib/utils/rules.js generated vendored Normal file
View File

@@ -0,0 +1,174 @@
import typescriptEslintNoUnnecessaryCondition from '../rules/@typescript-eslint/no-unnecessary-condition.js';
import blockLang from '../rules/block-lang.js';
import buttonHasType from '../rules/button-has-type.js';
import commentDirective from '../rules/comment-directive.js';
import consistentSelectorStyle from '../rules/consistent-selector-style.js';
import derivedHasSameInputsOutputs from '../rules/derived-has-same-inputs-outputs.js';
import experimentalRequireSlotTypes from '../rules/experimental-require-slot-types.js';
import experimentalRequireStrictEvents from '../rules/experimental-require-strict-events.js';
import firstAttributeLinebreak from '../rules/first-attribute-linebreak.js';
import htmlClosingBracketNewLine from '../rules/html-closing-bracket-new-line.js';
import htmlClosingBracketSpacing from '../rules/html-closing-bracket-spacing.js';
import htmlQuotes from '../rules/html-quotes.js';
import htmlSelfClosing from '../rules/html-self-closing.js';
import indent from '../rules/indent.js';
import infiniteReactiveLoop from '../rules/infinite-reactive-loop.js';
import maxAttributesPerLine from '../rules/max-attributes-per-line.js';
import maxLinesPerBlock from '../rules/max-lines-per-block.js';
import mustacheSpacing from '../rules/mustache-spacing.js';
import noAddEventListener from '../rules/no-add-event-listener.js';
import noAtConstTags from '../rules/no-at-const-tags.js';
import noAtDebugTags from '../rules/no-at-debug-tags.js';
import noAtHtmlTags from '../rules/no-at-html-tags.js';
import noBindValueOnCheckableInputs from '../rules/no-bind-value-on-checkable-inputs.js';
import noConflictingModuleNames from '../rules/no-conflicting-module-names.js';
import noDomManipulating from '../rules/no-dom-manipulating.js';
import noDupeElseIfBlocks from '../rules/no-dupe-else-if-blocks.js';
import noDupeOnDirectives from '../rules/no-dupe-on-directives.js';
import noDupeStyleProperties from '../rules/no-dupe-style-properties.js';
import noDupeUseDirectives from '../rules/no-dupe-use-directives.js';
import noDynamicSlotName from '../rules/no-dynamic-slot-name.js';
import noExportLoadInSvelteModuleInKitPages from '../rules/no-export-load-in-svelte-module-in-kit-pages.js';
import noExtraReactiveCurlies from '../rules/no-extra-reactive-curlies.js';
import noGotoWithoutBase from '../rules/no-goto-without-base.js';
import noIgnoredUnsubscribe from '../rules/no-ignored-unsubscribe.js';
import noImmutableReactiveStatements from '../rules/no-immutable-reactive-statements.js';
import noInlineStyles from '../rules/no-inline-styles.js';
import noInnerDeclarations from '../rules/no-inner-declarations.js';
import noInspect from '../rules/no-inspect.js';
import noNavigationWithoutBase from '../rules/no-navigation-without-base.js';
import noNavigationWithoutResolve from '../rules/no-navigation-without-resolve.js';
import noNestedStyleTag from '../rules/no-nested-style-tag.js';
import noNotFunctionHandler from '../rules/no-not-function-handler.js';
import noObjectInTextMustaches from '../rules/no-object-in-text-mustaches.js';
import noRawSpecialElements from '../rules/no-raw-special-elements.js';
import noReactiveFunctions from '../rules/no-reactive-functions.js';
import noReactiveLiterals from '../rules/no-reactive-literals.js';
import noReactiveReassign from '../rules/no-reactive-reassign.js';
import noRestrictedHtmlElements from '../rules/no-restricted-html-elements.js';
import noShorthandStylePropertyOverrides from '../rules/no-shorthand-style-property-overrides.js';
import noSpacesAroundEqualSignsInAttribute from '../rules/no-spaces-around-equal-signs-in-attribute.js';
import noStoreAsync from '../rules/no-store-async.js';
import noSvelteInternal from '../rules/no-svelte-internal.js';
import noTargetBlank from '../rules/no-target-blank.js';
import noTopLevelBrowserGlobals from '../rules/no-top-level-browser-globals.js';
import noTrailingSpaces from '../rules/no-trailing-spaces.js';
import noUnknownStyleDirectiveProperty from '../rules/no-unknown-style-directive-property.js';
import noUnnecessaryStateWrap from '../rules/no-unnecessary-state-wrap.js';
import noUnusedClassName from '../rules/no-unused-class-name.js';
import noUnusedProps from '../rules/no-unused-props.js';
import noUnusedSvelteIgnore from '../rules/no-unused-svelte-ignore.js';
import noUselessChildrenSnippet from '../rules/no-useless-children-snippet.js';
import noUselessMustaches from '../rules/no-useless-mustaches.js';
import preferAttributeInterpolation from '../rules/prefer-attribute-interpolation.js';
import preferClassDirective from '../rules/prefer-class-directive.js';
import preferConst from '../rules/prefer-const.js';
import preferDerivedOverDerivedBy from '../rules/prefer-derived-over-derived-by.js';
import preferDestructuredStoreProps from '../rules/prefer-destructured-store-props.js';
import preferStyleDirective from '../rules/prefer-style-directive.js';
import preferSvelteReactivity from '../rules/prefer-svelte-reactivity.js';
import preferWritableDerived from '../rules/prefer-writable-derived.js';
import requireEachKey from '../rules/require-each-key.js';
import requireEventDispatcherTypes from '../rules/require-event-dispatcher-types.js';
import requireEventPrefix from '../rules/require-event-prefix.js';
import requireOptimizedStyleAttribute from '../rules/require-optimized-style-attribute.js';
import requireStoreCallbacksUseSetParam from '../rules/require-store-callbacks-use-set-param.js';
import requireStoreReactiveAccess from '../rules/require-store-reactive-access.js';
import requireStoresInit from '../rules/require-stores-init.js';
import shorthandAttribute from '../rules/shorthand-attribute.js';
import shorthandDirective from '../rules/shorthand-directive.js';
import sortAttributes from '../rules/sort-attributes.js';
import spacedHtmlComment from '../rules/spaced-html-comment.js';
import system from '../rules/system.js';
import validCompile from '../rules/valid-compile.js';
import validEachKey from '../rules/valid-each-key.js';
import validPropNamesInKitPages from '../rules/valid-prop-names-in-kit-pages.js';
import validStyleParse from '../rules/valid-style-parse.js';
export const rules = [
typescriptEslintNoUnnecessaryCondition,
blockLang,
buttonHasType,
commentDirective,
consistentSelectorStyle,
derivedHasSameInputsOutputs,
experimentalRequireSlotTypes,
experimentalRequireStrictEvents,
firstAttributeLinebreak,
htmlClosingBracketNewLine,
htmlClosingBracketSpacing,
htmlQuotes,
htmlSelfClosing,
indent,
infiniteReactiveLoop,
maxAttributesPerLine,
maxLinesPerBlock,
mustacheSpacing,
noAddEventListener,
noAtConstTags,
noAtDebugTags,
noAtHtmlTags,
noBindValueOnCheckableInputs,
noConflictingModuleNames,
noDomManipulating,
noDupeElseIfBlocks,
noDupeOnDirectives,
noDupeStyleProperties,
noDupeUseDirectives,
noDynamicSlotName,
noExportLoadInSvelteModuleInKitPages,
noExtraReactiveCurlies,
noGotoWithoutBase,
noIgnoredUnsubscribe,
noImmutableReactiveStatements,
noInlineStyles,
noInnerDeclarations,
noInspect,
noNavigationWithoutBase,
noNavigationWithoutResolve,
noNestedStyleTag,
noNotFunctionHandler,
noObjectInTextMustaches,
noRawSpecialElements,
noReactiveFunctions,
noReactiveLiterals,
noReactiveReassign,
noRestrictedHtmlElements,
noShorthandStylePropertyOverrides,
noSpacesAroundEqualSignsInAttribute,
noStoreAsync,
noSvelteInternal,
noTargetBlank,
noTopLevelBrowserGlobals,
noTrailingSpaces,
noUnknownStyleDirectiveProperty,
noUnnecessaryStateWrap,
noUnusedClassName,
noUnusedProps,
noUnusedSvelteIgnore,
noUselessChildrenSnippet,
noUselessMustaches,
preferAttributeInterpolation,
preferClassDirective,
preferConst,
preferDerivedOverDerivedBy,
preferDestructuredStoreProps,
preferStyleDirective,
preferSvelteReactivity,
preferWritableDerived,
requireEachKey,
requireEventDispatcherTypes,
requireEventPrefix,
requireOptimizedStyleAttribute,
requireStoreCallbacksUseSetParam,
requireStoreReactiveAccess,
requireStoresInit,
shorthandAttribute,
shorthandDirective,
sortAttributes,
spacedHtmlComment,
system,
validCompile,
validEachKey,
validPropNamesInKitPages,
validStyleParse
];

View File

@@ -0,0 +1,26 @@
import type { RuleContext } from '../types.js';
export type SvelteContext = ({
svelteVersion: '3/4';
svelteFileType: '.svelte' | null;
runes: null;
} | ({
svelteVersion: '5';
} & ({
svelteFileType: '.svelte' | '.svelte.[js|ts]';
/** If a user uses a parser other than `svelte-eslint-parser`, `undetermined` will be set. */
runes: boolean | 'undetermined';
} | {
/** e.g. `foo.js` / `package.json` */
svelteFileType: null;
runes: null;
})) | {
/** For projects that do not use Svelte. */
svelteVersion: null;
svelteFileType: null;
runes: null;
}) & {
svelteKitVersion: '1.0.0-next' | '1' | '2' | '3' | null;
svelteKitFileType: '+page.svelte' | '+page.[js|ts]' | '+page.server.[js|ts]' | '+error.svelte' | '+layout.svelte' | '+layout.[js|ts]' | '+layout.server.[js|ts]' | '+server.[js|ts]' | null;
};
export declare function getSvelteVersion(): SvelteContext['svelteVersion'];
export declare function getSvelteContext(context: RuleContext): SvelteContext | null;

View File

@@ -0,0 +1,263 @@
import fs from 'fs';
import path from 'path';
import { getPackageJsons } from './get-package-json.js';
import { getNodeModule } from './get-node-module.js';
import { createCache } from './cache.js';
import { VERSION as SVELTE_VERSION } from 'svelte/compiler';
const isRunInBrowser = !fs.readFileSync;
function getSvelteFileType(filePath) {
if (filePath.endsWith('.svelte')) {
return '.svelte';
}
if (filePath.endsWith('.svelte.js') || filePath.endsWith('.svelte.ts')) {
return '.svelte.[js|ts]';
}
return null;
}
function getSvelteKitFileTypeFromFilePath(filePath) {
const fileName = filePath.split(/[/\\]/).pop();
switch (fileName) {
case '+page.svelte': {
return '+page.svelte';
}
case '+page.js':
case '+page.ts': {
return '+page.[js|ts]';
}
case '+page.server.js':
case '+page.server.ts': {
return '+page.server.[js|ts]';
}
case '+error.svelte': {
return '+error.svelte';
}
case '+layout.svelte': {
return '+layout.svelte';
}
case '+layout.js':
case '+layout.ts': {
return '+layout.[js|ts]';
}
case '+layout.server.js':
case '+layout.server.ts': {
return '+layout.server.[js|ts]';
}
case '+server.js':
case '+server.ts': {
return '+server.[js|ts]';
}
default: {
return null;
}
}
}
function extractMajorVersion(version, recognizePrereleaseVersion) {
if (recognizePrereleaseVersion) {
const match = /^(?:\^|~)?(\d+\.0\.0-next)/.exec(version);
if (match && match[1]) {
return match[1];
}
}
const match = /^(?:\^|~)?(\d+)\./.exec(version);
if (match && match[1]) {
return match[1];
}
return null;
}
const svelteKitContextCache = createCache();
function getSvelteKitContext(context) {
const filePath = context.filename;
const cached = svelteKitContextCache.get(filePath);
if (cached)
return cached;
const svelteKitVersion = getSvelteKitVersion(filePath);
if (svelteKitVersion == null) {
const result = {
svelteKitFileType: null,
svelteKitVersion: null
};
svelteKitContextCache.set(filePath, result);
return result;
}
if (isRunInBrowser) {
const result = {
svelteKitVersion,
// Judge by only file path if it runs in browser.
svelteKitFileType: getSvelteKitFileTypeFromFilePath(filePath)
};
svelteKitContextCache.set(filePath, result);
return result;
}
const routes = (context.settings?.svelte?.kit?.files?.routes ??
context.sourceCode.parserServices.svelteParseContext?.svelteConfig?.kit?.files?.routes)?.replace(/^\//, '') ?? 'src/routes';
const projectRootDir = getProjectRootDir(context.filename) ?? '';
if (!filePath.startsWith(path.join(projectRootDir, routes))) {
const result = {
svelteKitVersion,
svelteKitFileType: null
};
svelteKitContextCache.set(filePath, result);
return result;
}
const result = {
svelteKitVersion,
svelteKitFileType: getSvelteKitFileTypeFromFilePath(filePath)
};
svelteKitContextCache.set(filePath, result);
return result;
}
function checkAndSetSvelteVersion(version) {
const major = extractMajorVersion(version, false);
if (major == null) {
return null;
}
if (major === '3' || major === '4') {
return '3/4';
}
return major;
}
export function getSvelteVersion() {
// Hack: if it runs in browser, it regards as Svelte project.
if (isRunInBrowser) {
return '5';
}
return checkAndSetSvelteVersion(SVELTE_VERSION);
}
const svelteKitVersionCache = createCache();
function checkAndSetSvelteKitVersion(version, filePath) {
// Preserve Kit 1's distinct prerelease version; use the major for later prereleases.
const major = (extractMajorVersion(version, true) === '1.0.0-next'
? '1.0.0-next'
: extractMajorVersion(version, false));
svelteKitVersionCache.set(filePath, major);
return major;
}
function getSvelteKitVersion(filePath) {
const cached = svelteKitVersionCache.get(filePath);
if (cached)
return cached;
// Hack: if it runs in browser, it regards as SvelteKit project.
if (isRunInBrowser) {
svelteKitVersionCache.set(filePath, '2');
return '2';
}
const nodeModule = getNodeModule('@sveltejs/kit', filePath);
if (nodeModule) {
try {
const packageJson = JSON.parse(fs.readFileSync(path.join(nodeModule, 'package.json'), 'utf8'));
const result = checkAndSetSvelteKitVersion(packageJson.version, filePath);
if (result != null) {
return result;
}
}
catch {
/** do nothing */
}
}
try {
const packageJsons = getPackageJsons(filePath);
if (packageJsons.length > 0) {
if (packageJsons[0].name === 'eslint-plugin-svelte') {
// Hack: CI removes `@sveltejs/kit` and it returns false and test failed.
// So always it returns 2 if it runs on the package.
svelteKitVersionCache.set(filePath, '2');
return '2';
}
for (const packageJson of packageJsons) {
const version = packageJson.dependencies?.['@sveltejs/kit'] ??
packageJson.devDependencies?.['@sveltejs/kit'];
if (typeof version === 'string') {
const result = checkAndSetSvelteKitVersion(version, filePath);
if (result != null) {
return result;
}
}
}
}
}
catch {
/** do nothing */
}
svelteKitVersionCache.set(filePath, null);
return null;
}
const projectRootDirCache = createCache();
/**
* Gets a project root folder path.
* @param filePath A file path to lookup.
* @returns A found project root folder path or null.
*/
function getProjectRootDir(filePath) {
if (isRunInBrowser)
return null;
const cached = projectRootDirCache.get(filePath);
if (cached)
return cached;
const packageJsons = getPackageJsons(filePath);
if (packageJsons.length === 0) {
projectRootDirCache.set(filePath, null);
return null;
}
const packageJsonFilePath = packageJsons[0].filePath;
if (!packageJsonFilePath) {
projectRootDirCache.set(filePath, null);
return null;
}
const projectRootDir = path.dirname(path.resolve(packageJsonFilePath));
projectRootDirCache.set(filePath, projectRootDir);
return projectRootDir;
}
const svelteContextCache = createCache();
export function getSvelteContext(context) {
const { parserServices } = context.sourceCode;
const { svelteParseContext } = parserServices;
const filePath = context.filename;
const cached = svelteContextCache.get(filePath);
if (cached)
return cached;
const svelteKitContext = getSvelteKitContext(context);
const svelteVersion = getSvelteVersion();
const svelteFileType = getSvelteFileType(filePath);
if (svelteVersion == null) {
const result = {
svelteVersion: null,
svelteFileType: null,
runes: null,
svelteKitVersion: svelteKitContext.svelteKitVersion,
svelteKitFileType: svelteKitContext.svelteKitFileType
};
svelteContextCache.set(filePath, result);
return result;
}
if (svelteVersion === '3/4') {
const result = {
svelteVersion,
svelteFileType: svelteFileType === '.svelte' ? '.svelte' : null,
runes: null,
svelteKitVersion: svelteKitContext.svelteKitVersion,
svelteKitFileType: svelteKitContext.svelteKitFileType
};
svelteContextCache.set(filePath, result);
return result;
}
if (svelteFileType == null) {
const result = {
svelteVersion,
svelteFileType: null,
runes: null,
svelteKitVersion: svelteKitContext.svelteKitVersion,
svelteKitFileType: svelteKitContext.svelteKitFileType
};
svelteContextCache.set(filePath, result);
return result;
}
const result = {
svelteVersion,
runes: svelteParseContext?.runes ?? 'undetermined',
svelteFileType,
svelteKitVersion: svelteKitContext.svelteKitVersion,
svelteKitFileType: svelteKitContext.svelteKitFileType
};
svelteContextCache.set(filePath, result);
return result;
}

View File

@@ -0,0 +1,138 @@
import type { RuleContext, ASTNode } from '../../types.js';
import type * as TS from 'typescript';
export type TypeScript = typeof TS;
export type { TS };
export type TSTools = {
service: {
esTreeNodeToTSNodeMap: ReadonlyMap<unknown, TS.Node>;
tsNodeToESTreeNodeMap: ReadonlyMap<TS.Node, ASTNode>;
program: TS.Program;
hasFullTypeInformation: boolean;
};
ts: TypeScript;
};
/**
* Get TypeScript tools
*/
export declare function getTypeScriptTools(context: RuleContext): TSTools | null;
/**
* Get TypeScript tools
*/
export declare function getTypeScript(context: RuleContext): TypeScript | null;
/**
* Check whether the given type is a truthy literal type or not.
*/
export declare function isTruthyLiteral(type: TS.Type, tsTools: TSTools): boolean;
/**
* Check whether the given type is a falsy type or not.
*/
export declare function isFalsyType(type: TS.Type, tsTools: TSTools): boolean;
/**
* Check whether the given type is a nullish type or not.
*/
export declare function isNullishType(type: TS.Type, ts: TypeScript): boolean;
/**
* Checks whether the given type is nullable or not.
*/
export declare function isNullableType(type: TS.Type, ts: TypeScript): boolean;
/**
* Check whether the given type is a boolean literal type or not.
*/
export declare function isBooleanLiteralType(type: TS.Type, ts: TypeScript): boolean;
/**
* Check whether the given type is an object type or not.
*/
export declare function isObjectType(type: TS.Type, ts: TypeScript): type is TS.ObjectType;
/**
* Check whether the given type is a reference type or not.
*/
export declare function isReferenceObjectType(type: TS.Type, ts: TypeScript): type is TS.TypeReference;
/**
* Check whether the given type is a tuple type or not.
*/
export declare function isTupleObjectType(type: TS.Type, ts: TypeScript): type is TS.TupleType;
/**
* Check whether the given type is a tuple type or not.
* Unlike isTupleObjectType, it also refers to reference types.
*/
export declare function isTupleType(type: TS.Type, ts: TypeScript): boolean;
/**
* Check whether the given type is an any type or not.
*/
export declare function isAnyType(type: TS.Type, ts: TypeScript): boolean;
/**
* Check whether the given type is an unknown type or not.
*/
export declare function isUnknownType(type: TS.Type, ts: TypeScript): boolean;
/**
* Check whether the given type is a never type or not.
*/
export declare function isNeverType(type: TS.Type, ts: TypeScript): boolean;
/**
* Check whether the given type is an undefined type or not.
*/
export declare function isUndefinedType(type: TS.Type, ts: TypeScript): boolean;
/**
* Check whether the given type is a void type or not.
*/
export declare function isVoidType(type: TS.Type, ts: TypeScript): boolean;
/**
* Check whether the given type is a null type or not.
*/
export declare function isNullType(type: TS.Type, ts: TypeScript): boolean;
/**
* Check whether the given type is a possibly falsy type or not.
*/
export declare function isPossiblyFalsyType(type: TS.Type, ts: TypeScript): boolean;
/**
* Get the call signatures from the given type.
* This method is heavily inspired by tsutils. https://github.com/ajafff/tsutils
* The MIT License (MIT) Copyright (c) 2017 Klaus Meinhardt
* https://github.com/ajafff/tsutils/blob/master/LICENSE
*/
export declare function getCallSignaturesOfType(type: TS.Type): readonly TS.Signature[];
/**
* Resolves the given node's type. Will resolve to the type's generic constraint, if it has one.
* Copied this method from @typescript-eslint/type-utils. https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/type-utils
* The MIT License (MIT) Copyright (c) 2021 TypeScript ESLint and other contributors
* https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/type-utils/LICENSE
*/
export declare function getConstrainedTypeAtLocation(checker: TS.TypeChecker, node: TS.Node): TS.Type;
/**
* Get the type name of a given type.
*
* Copied this method from @typescript-eslint/type-utils. https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/type-utils
* The MIT License (MIT) Copyright (c) 2021 TypeScript ESLint and other contributors
* https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/type-utils/LICENSE
*
* @param type The type to get the name of.
*/
export declare function getTypeName(type: TS.Type, tsTools: TSTools): string;
/**
* Return the type of the given property in the given type, or undefined if no such property exists
*/
export declare function getTypeOfPropertyOfType(type: TS.Type, name: string, checker: TS.TypeChecker): TS.Type | undefined;
/**
* Check whether the given symbol is a method type or not.
*/
export declare function isMethodSymbol(type: TS.Symbol, ts: TypeScript): boolean;
/**
* Check whether the given node is a property signature kind or not.
*/
export declare function isPropertySignatureKind(node: TS.Node, ts: TypeScript): node is TS.PropertySignature;
/**
* Check whether the given node is a function type kind or not.
*/
export declare function isFunctionTypeKind(node: TS.Node, ts: TypeScript): node is TS.FunctionTypeNode;
/**
* Check whether the given node is a method signature kind or not.
*/
export declare function isMethodSignatureKind(node: TS.Node, ts: TypeScript): node is TS.MethodSignature;
/**
* Check whether the given node is a type reference kind or not.
*/
export declare function isTypeReferenceKind(node: TS.Node, ts: TypeScript): node is TS.TypeReferenceNode;
/**
* Check whether the given node is an identifier kind or not.
*/
export declare function isIdentifierKind(node: TS.Node, ts: TypeScript): node is TS.Identifier;

View File

@@ -0,0 +1,298 @@
import { loadModule } from '../load-module.js';
/**
* Get TypeScript tools
*/
export function getTypeScriptTools(context) {
const ts = getTypeScript(context);
if (!ts) {
return null;
}
const sourceCode = context.sourceCode;
const { program, esTreeNodeToTSNodeMap, tsNodeToESTreeNodeMap } = sourceCode.parserServices;
if (!program || !esTreeNodeToTSNodeMap || !tsNodeToESTreeNodeMap) {
return null;
}
const hasFullTypeInformation = sourceCode.parserServices.hasFullTypeInformation ?? true;
if (!hasFullTypeInformation) {
// Full type information is required. User must specify parserOptions.project.
return null;
}
return {
service: {
esTreeNodeToTSNodeMap,
tsNodeToESTreeNodeMap,
hasFullTypeInformation,
program
},
ts
};
}
let cacheTypeScript = null;
/**
* Get TypeScript tools
*/
export function getTypeScript(context) {
if (cacheTypeScript) {
return cacheTypeScript;
}
cacheTypeScript = loadModule(context, 'typescript');
if (cacheTypeScript) {
return cacheTypeScript;
}
try {
// eslint-disable-next-line @typescript-eslint/no-require-imports -- ignore
cacheTypeScript ?? (cacheTypeScript = require('typescript'));
}
catch {
// ignore
}
return cacheTypeScript;
}
/**
* Check whether the given type is a truthy literal type or not.
*/
export function isTruthyLiteral(type, tsTools) {
if (type.isUnion()) {
return type.types.every((t) => isTruthyLiteral(t, tsTools));
}
return ((isBooleanLiteralType(type, tsTools.ts) &&
tsTools.service.program.getTypeChecker().typeToString(type) === 'true') ||
(type.isLiteral() && Boolean(type.value)));
}
/**
* Check whether the given type is a falsy type or not.
*/
export function isFalsyType(type, tsTools) {
if (type.isUnion()) {
return type.types.every((t) => isFalsyType(t, tsTools));
}
if (isUndefinedType(type, tsTools.ts) ||
isNullType(type, tsTools.ts) ||
isVoidType(type, tsTools.ts))
return true;
if (type.isLiteral())
return !type.value;
return (isBooleanLiteralType(type, tsTools.ts) &&
tsTools.service.program.getTypeChecker().typeToString(type) === 'false');
}
/**
* Check whether the given type is a nullish type or not.
*/
export function isNullishType(type, ts) {
if (type.isUnion()) {
return type.types.every((t) => isNullishType(t, ts));
}
return isNullType(type, ts) || isUndefinedType(type, ts);
}
/**
* Checks whether the given type is nullable or not.
*/
export function isNullableType(type, ts) {
if (type.isUnion()) {
return type.types.some((t) => isNullableType(t, ts));
}
return isNullType(type, ts) || isUndefinedType(type, ts);
}
/**
* Check whether the given type is a boolean literal type or not.
*/
export function isBooleanLiteralType(type, ts) {
return (type.flags & ts.TypeFlags.BooleanLiteral) !== 0;
}
/**
* Check whether the given type is an object type or not.
*/
export function isObjectType(type, ts) {
return (type.flags & ts.TypeFlags.Object) !== 0;
}
/**
* Check whether the given type is a reference type or not.
*/
export function isReferenceObjectType(type, ts) {
return isObjectType(type, ts) && (type.objectFlags & ts.ObjectFlags.Reference) !== 0;
}
/**
* Check whether the given type is a tuple type or not.
*/
export function isTupleObjectType(type, ts) {
return isObjectType(type, ts) && (type.objectFlags & ts.ObjectFlags.Tuple) !== 0;
}
/**
* Check whether the given type is a tuple type or not.
* Unlike isTupleObjectType, it also refers to reference types.
*/
export function isTupleType(type, ts) {
return (isTupleObjectType(type, ts) ||
(isReferenceObjectType(type, ts) && isTupleObjectType(type.target, ts)));
}
/**
* Check whether the given type is an any type or not.
*/
export function isAnyType(type, ts) {
return (type.flags & ts.TypeFlags.Any) !== 0;
}
/**
* Check whether the given type is an unknown type or not.
*/
export function isUnknownType(type, ts) {
return (type.flags & ts.TypeFlags.Unknown) !== 0;
}
/**
* Check whether the given type is a never type or not.
*/
export function isNeverType(type, ts) {
return (type.flags & ts.TypeFlags.Never) !== 0;
}
/**
* Check whether the given type is an undefined type or not.
*/
export function isUndefinedType(type, ts) {
return (type.flags & ts.TypeFlags.Undefined) !== 0;
}
/**
* Check whether the given type is a void type or not.
*/
export function isVoidType(type, ts) {
return (type.flags & ts.TypeFlags.Void) !== 0;
}
/**
* Check whether the given type is a null type or not.
*/
export function isNullType(type, ts) {
return (type.flags & ts.TypeFlags.Null) !== 0;
}
/**
* Check whether the given type is a possibly falsy type or not.
*/
export function isPossiblyFalsyType(type, ts) {
if (type.isUnion()) {
return type.types.some((t) => isPossiblyFalsyType(t, ts));
}
return (type.flags & ts.TypeFlags.PossiblyFalsy) !== 0;
}
/**
* Get the call signatures from the given type.
* This method is heavily inspired by tsutils. https://github.com/ajafff/tsutils
* The MIT License (MIT) Copyright (c) 2017 Klaus Meinhardt
* https://github.com/ajafff/tsutils/blob/master/LICENSE
*/
export function getCallSignaturesOfType(type) {
if (type.isUnion()) {
return type.types.flatMap((t) => getCallSignaturesOfType(t));
}
if (type.isIntersection()) {
let signatures = [];
for (const t of type.types) {
const sig = getCallSignaturesOfType(t);
if (sig.length !== 0) {
if (signatures.length) {
// if more than one type of the intersection has call signatures, none of them is useful for inference
return [];
}
signatures = sig;
}
}
return signatures;
}
return type.getCallSignatures();
}
/**
* Resolves the given node's type. Will resolve to the type's generic constraint, if it has one.
* Copied this method from @typescript-eslint/type-utils. https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/type-utils
* The MIT License (MIT) Copyright (c) 2021 TypeScript ESLint and other contributors
* https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/type-utils/LICENSE
*/
export function getConstrainedTypeAtLocation(checker, node) {
const nodeType = checker.getTypeAtLocation(node);
const constrained = checker.getBaseConstraintOfType(nodeType);
return constrained ?? nodeType;
}
/**
* Get the type name of a given type.
*
* Copied this method from @typescript-eslint/type-utils. https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/type-utils
* The MIT License (MIT) Copyright (c) 2021 TypeScript ESLint and other contributors
* https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/type-utils/LICENSE
*
* @param type The type to get the name of.
*/
export function getTypeName(type, tsTools) {
const { ts } = tsTools;
// It handles `string` and string literal types as string.
if ((type.flags & ts.TypeFlags.StringLike) !== 0) {
return 'string';
}
const typeChecker = tsTools.service.program.getTypeChecker();
// If the type is a type parameter which extends primitive string types,
// but it was not recognized as a string like. So check the constraint
// type of the type parameter.
if ((type.flags & ts.TypeFlags.TypeParameter) !== 0) {
// `type.getConstraint()` method doesn't return the constraint type of
// the type parameter for some reason. So this gets the constraint type
// via AST.
const symbol = type.getSymbol();
const decls = symbol?.getDeclarations();
const typeParamDecl = decls?.[0];
if (ts.isTypeParameterDeclaration(typeParamDecl) && typeParamDecl.constraint != null) {
return getTypeName(typeChecker.getTypeFromTypeNode(typeParamDecl.constraint), tsTools);
}
}
// If the type is a union and all types in the union are string like,
// return `string`. For example:
// - `"a" | "b"` is string.
// - `string | string[]` is not string.
if (type.isUnion() &&
type.types.map((value) => getTypeName(value, tsTools)).every((t) => t === 'string')) {
return 'string';
}
// If the type is an intersection and a type in the intersection is string
// like, return `string`. For example: `string & {__htmlEscaped: void}`
if (type.isIntersection() &&
type.types.map((value) => getTypeName(value, tsTools)).some((t) => t === 'string')) {
return 'string';
}
return typeChecker.typeToString(type);
}
/**
* Return the type of the given property in the given type, or undefined if no such property exists
*/
export function getTypeOfPropertyOfType(type, name, checker) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- getTypeOfPropertyOfType is an internal API of TS.
return checker.getTypeOfPropertyOfType(type, name);
}
/**
* Check whether the given symbol is a method type or not.
*/
export function isMethodSymbol(type, ts) {
return (type.getFlags() & ts.SymbolFlags.Method) !== 0;
}
/**
* Check whether the given node is a property signature kind or not.
*/
export function isPropertySignatureKind(node, ts) {
return node.kind === ts.SyntaxKind.PropertySignature;
}
/**
* Check whether the given node is a function type kind or not.
*/
export function isFunctionTypeKind(node, ts) {
return node.kind === ts.SyntaxKind.FunctionType;
}
/**
* Check whether the given node is a method signature kind or not.
*/
export function isMethodSignatureKind(node, ts) {
return node.kind === ts.SyntaxKind.MethodSignature;
}
/**
* Check whether the given node is a type reference kind or not.
*/
export function isTypeReferenceKind(node, ts) {
return node.kind === ts.SyntaxKind.TypeReference;
}
/**
* Check whether the given node is an identifier kind or not.
*/
export function isIdentifierKind(node, ts) {
return node.kind === ts.SyntaxKind.Identifier;
}