intial
This commit is contained in:
19
node_modules/svelte-eslint-parser/lib/parser/analyze-scope.d.ts
generated
vendored
Normal file
19
node_modules/svelte-eslint-parser/lib/parser/analyze-scope.d.ts
generated
vendored
Normal file
@@ -0,0 +1,19 @@
|
||||
import type ESTree from "estree";
|
||||
import type * as eslint from "eslint";
|
||||
import type { SvelteScriptElement, SvelteSnippetBlock } from "../ast/index.js";
|
||||
import type { NormalizedParserOptions } from "./parser-options.js";
|
||||
import type { SvelteParseContext } from "./svelte-parse-context.js";
|
||||
/**
|
||||
* Analyze scope
|
||||
*/
|
||||
export declare function analyzeScope(node: ESTree.Node, parserOptions: NormalizedParserOptions): eslint.Scope.ScopeManager;
|
||||
/** Analyze reactive scope */
|
||||
export declare function analyzeReactiveScope(scopeManager: eslint.Scope.ScopeManager): void;
|
||||
/**
|
||||
* Analyze store scope. e.g. $count
|
||||
*/
|
||||
export declare function analyzeStoreScope(scopeManager: eslint.Scope.ScopeManager, svelteParseContext: SvelteParseContext): void;
|
||||
/** Transform props exports */
|
||||
export declare function analyzePropsScope(body: SvelteScriptElement, scopeManager: eslint.Scope.ScopeManager, svelteParseContext: SvelteParseContext): void;
|
||||
/** Analyze snippets in component scope */
|
||||
export declare function analyzeSnippetsScope(snippets: SvelteSnippetBlock[], scopeManager: eslint.Scope.ScopeManager): void;
|
||||
308
node_modules/svelte-eslint-parser/lib/parser/analyze-scope.js
generated
vendored
Normal file
308
node_modules/svelte-eslint-parser/lib/parser/analyze-scope.js
generated
vendored
Normal file
@@ -0,0 +1,308 @@
|
||||
import { getFallbackKeys } from "../traverse.js";
|
||||
import { addReference, addVariable, getScopeFromNode, removeIdentifierVariable, } from "../scope/index.js";
|
||||
import { addElementToSortedArray } from "../utils/index.js";
|
||||
import { getGlobalsForSvelte } from "./globals.js";
|
||||
import { getESLintScope } from "./eslint-scope.js";
|
||||
/**
|
||||
* Analyze scope
|
||||
*/
|
||||
export function analyzeScope(node, parserOptions) {
|
||||
const ecmaVersion = parserOptions.ecmaVersion || 2020;
|
||||
const ecmaFeatures = parserOptions.ecmaFeatures || {};
|
||||
const sourceType = parserOptions.sourceType || "module";
|
||||
const root = node.type === "Program"
|
||||
? node
|
||||
: {
|
||||
type: "Program",
|
||||
body: [node],
|
||||
sourceType,
|
||||
};
|
||||
const { analyze } = getESLintScope();
|
||||
return analyze(root, {
|
||||
ignoreEval: true,
|
||||
nodejsScope: false,
|
||||
impliedStrict: ecmaFeatures.impliedStrict,
|
||||
ecmaVersion: typeof ecmaVersion === "number" ? ecmaVersion : 2022,
|
||||
sourceType,
|
||||
fallback: getFallbackKeys,
|
||||
});
|
||||
}
|
||||
/** Analyze reactive scope */
|
||||
export function analyzeReactiveScope(scopeManager) {
|
||||
for (const reference of [...scopeManager.globalScope.through]) {
|
||||
const parent = reference.writeExpr && getParent(reference.writeExpr);
|
||||
if (parent?.type === "AssignmentExpression") {
|
||||
const pp = getParent(parent);
|
||||
if (pp?.type === "ExpressionStatement") {
|
||||
const ppp = getParent(pp);
|
||||
if (ppp?.type === "SvelteReactiveStatement" && ppp.label.name === "$") {
|
||||
const referenceScope = reference.from;
|
||||
if (referenceScope.type === "module") {
|
||||
// It is computed
|
||||
transformComputedVariable(parent, ppp, reference);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/** Transform ref to ComputedVariable */
|
||||
function transformComputedVariable(node, parent, reference) {
|
||||
const referenceScope = reference.from;
|
||||
const name = reference.identifier.name;
|
||||
let variable = referenceScope.set.get(name);
|
||||
if (!variable) {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention -- class name
|
||||
const { Variable } = getESLintScope();
|
||||
variable = new Variable(name, referenceScope);
|
||||
variable.scope = referenceScope;
|
||||
variable.name = name;
|
||||
addElementToSortedArray(variable.defs, {
|
||||
type: "ComputedVariable",
|
||||
node: node,
|
||||
parent: parent,
|
||||
name: reference.identifier,
|
||||
}, (a, b) => a.node.range[0] - b.node.range[0]);
|
||||
addVariable(referenceScope.variables, variable);
|
||||
referenceScope.set.set(name, variable);
|
||||
}
|
||||
addElementToSortedArray(variable.identifiers, reference.identifier, (a, b) => a.range[0] - b.range[0]);
|
||||
reference.resolved = variable;
|
||||
removeReferenceFromThrough(reference, referenceScope);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Analyze store scope. e.g. $count
|
||||
*/
|
||||
export function analyzeStoreScope(scopeManager, svelteParseContext) {
|
||||
const moduleScope = scopeManager.scopes.find((scope) => scope.type === "module");
|
||||
if (!moduleScope) {
|
||||
return;
|
||||
}
|
||||
const toBeMarkAsUsedReferences = [];
|
||||
const globals = getGlobalsForSvelte(svelteParseContext);
|
||||
for (const reference of [...scopeManager.globalScope.through]) {
|
||||
if (reference.identifier.name.startsWith("$") &&
|
||||
!globals.includes(reference.identifier.name)) {
|
||||
const realName = reference.identifier.name.slice(1);
|
||||
const variable = moduleScope.set.get(realName);
|
||||
if (variable) {
|
||||
if (reference.isWriteOnly()) {
|
||||
// Need mark as used
|
||||
toBeMarkAsUsedReferences.push(reference);
|
||||
}
|
||||
// It does not write directly to the original variable.
|
||||
// Therefore, this variable is always a reference.
|
||||
reference.isWrite = () => false;
|
||||
reference.isWriteOnly = () => false;
|
||||
reference.isReadWrite = () => false;
|
||||
reference.isReadOnly = () => true;
|
||||
reference.isRead = () => true;
|
||||
addReference(variable.references, reference);
|
||||
reference.resolved = variable;
|
||||
removeReferenceFromThrough(reference, moduleScope);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const variable of new Set(toBeMarkAsUsedReferences.map((ref) => ref.resolved))) {
|
||||
if (variable.references.some((ref) => !toBeMarkAsUsedReferences.includes(ref) &&
|
||||
ref.identifier !== variable.identifiers[0])) {
|
||||
// It is already used.
|
||||
continue;
|
||||
}
|
||||
// Add the virtual reference for reading.
|
||||
addVirtualReference(variable.identifiers[0], variable, moduleScope, {
|
||||
read: true,
|
||||
}).svelteMarkAsUsed = true;
|
||||
}
|
||||
}
|
||||
/** Transform props exports */
|
||||
export function analyzePropsScope(body, scopeManager, svelteParseContext) {
|
||||
const moduleScope = scopeManager.scopes.find((scope) => scope.type === "module");
|
||||
if (!moduleScope) {
|
||||
return;
|
||||
}
|
||||
for (const node of body.body) {
|
||||
if (node.type === "ExportNamedDeclaration") {
|
||||
// Process for Svelte v4 style props. e.g. `export let x`;
|
||||
if (node.declaration) {
|
||||
if (node.declaration.type === "VariableDeclaration") {
|
||||
for (const decl of node.declaration.declarations) {
|
||||
for (const pattern of extractPattern(decl.id)) {
|
||||
if (pattern.type === "Identifier") {
|
||||
addPropReference(pattern, moduleScope);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
for (const spec of node.specifiers) {
|
||||
if (spec.local.type !== "Literal") {
|
||||
addPropReference(spec.local, moduleScope);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (node.type === "VariableDeclaration") {
|
||||
// Process if not confirmed as non-Runes mode.
|
||||
if (svelteParseContext.runes !== false) {
|
||||
// Process for Svelte v5 Runes props. e.g. `let { x = $bindable() } = $props()`;
|
||||
for (const decl of node.declarations) {
|
||||
if (decl.init?.type === "CallExpression" &&
|
||||
decl.init.callee.type === "Identifier" &&
|
||||
decl.init.callee.name === "$props" &&
|
||||
decl.id.type === "ObjectPattern") {
|
||||
for (const pattern of extractPattern(decl.id)) {
|
||||
if (pattern.type === "AssignmentPattern" &&
|
||||
pattern.left.type === "Identifier" &&
|
||||
pattern.right.type === "CallExpression" &&
|
||||
pattern.right.callee.type === "Identifier" &&
|
||||
pattern.right.callee.name === "$bindable") {
|
||||
addPropReference(pattern.left, moduleScope);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
function* extractPattern(node) {
|
||||
yield node;
|
||||
if (node.type === "Identifier") {
|
||||
return;
|
||||
}
|
||||
if (node.type === "ObjectPattern") {
|
||||
for (const prop of node.properties) {
|
||||
if (prop.type === "Property") {
|
||||
yield* extractPattern(prop.value);
|
||||
}
|
||||
else {
|
||||
yield* extractPattern(prop);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (node.type === "ArrayPattern") {
|
||||
for (const elem of node.elements) {
|
||||
if (elem) {
|
||||
yield* extractPattern(elem);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (node.type === "AssignmentPattern") {
|
||||
yield* extractPattern(node.left);
|
||||
return;
|
||||
}
|
||||
if (node.type === "RestElement") {
|
||||
yield* extractPattern(node.argument);
|
||||
}
|
||||
}
|
||||
/** Add virtual prop reference */
|
||||
function addPropReference(node, scope) {
|
||||
for (const variable of scope.variables) {
|
||||
if (variable.name !== node.name) {
|
||||
continue;
|
||||
}
|
||||
if (variable.references.some((ref) => ref.sveltePropReference)) {
|
||||
continue;
|
||||
}
|
||||
// Add the virtual reference for writing.
|
||||
const reference = addVirtualReference({
|
||||
...node,
|
||||
// @ts-expect-error -- ignore
|
||||
parent: body,
|
||||
loc: {
|
||||
start: { ...node.loc.start },
|
||||
end: { ...node.loc.end },
|
||||
},
|
||||
range: [...node.range],
|
||||
}, variable, scope, {
|
||||
write: true,
|
||||
read: true,
|
||||
});
|
||||
reference.sveltePropReference = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
/** Analyze snippets in component scope */
|
||||
export function analyzeSnippetsScope(snippets, scopeManager) {
|
||||
for (const snippet of snippets) {
|
||||
const parent = snippet.parent;
|
||||
if (parent.type === "SvelteElement" &&
|
||||
(parent.kind === "component" ||
|
||||
(parent.kind === "special" &&
|
||||
(parent.name.name === "svelte:component" ||
|
||||
parent.name.name === "svelte:boundary")))) {
|
||||
const scope = getScopeFromNode(scopeManager, snippet.id);
|
||||
const upperScope = scope.upper;
|
||||
if (!upperScope)
|
||||
continue;
|
||||
const variable = upperScope.set.get(snippet.id.name);
|
||||
if (!variable)
|
||||
continue;
|
||||
const defIds = variable.defs.map((d) => d.name);
|
||||
const refs = variable.references.filter((id) => !defIds.includes(id.identifier));
|
||||
if (refs.length <= 0) {
|
||||
// If the snippet is not referenced,
|
||||
// remove the a variable from the upperScope.
|
||||
removeIdentifierVariable(snippet.id, upperScope);
|
||||
}
|
||||
else {
|
||||
// Add the virtual reference for reading.
|
||||
const reference = addVirtualReference(snippet.id, variable, upperScope, {
|
||||
read: true,
|
||||
});
|
||||
reference.svelteSnippetReference = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/** Remove reference from through */
|
||||
function removeReferenceFromThrough(reference, baseScope) {
|
||||
const variable = reference.resolved;
|
||||
const name = reference.identifier.name;
|
||||
let scope = baseScope;
|
||||
while (scope) {
|
||||
scope.through = scope.through.filter((ref) => {
|
||||
if (reference === ref) {
|
||||
return false;
|
||||
}
|
||||
else if (ref.identifier.name === name) {
|
||||
ref.resolved = variable;
|
||||
if (!variable.references.includes(ref)) {
|
||||
addReference(variable.references, ref);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
scope = scope.upper;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Add the virtual reference.
|
||||
*/
|
||||
function addVirtualReference(node, variable, scope, readWrite) {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention -- class name
|
||||
const { Reference } = getESLintScope();
|
||||
const reference = new Reference(node, scope, (readWrite.write ? 0x1 : 0) | (readWrite.read ? 0x2 : 0), null, false, false,
|
||||
// for backwards compatibility
|
||||
null);
|
||||
reference.svelteVirtualReference = true;
|
||||
reference.from = scope;
|
||||
reference.identifier = node;
|
||||
reference.isWrite = () => Boolean(readWrite.write);
|
||||
reference.isWriteOnly = () => Boolean(readWrite.write) && !readWrite.read;
|
||||
reference.isRead = () => Boolean(readWrite.read);
|
||||
reference.isReadOnly = () => Boolean(readWrite.read) && !readWrite.write;
|
||||
reference.isReadWrite = () => Boolean(readWrite.read && readWrite.write);
|
||||
addReference(variable.references, reference);
|
||||
reference.resolved = variable;
|
||||
return reference;
|
||||
}
|
||||
/** Get parent node */
|
||||
function getParent(node) {
|
||||
return node.parent;
|
||||
}
|
||||
42
node_modules/svelte-eslint-parser/lib/parser/compat.d.ts
generated
vendored
Normal file
42
node_modules/svelte-eslint-parser/lib/parser/compat.d.ts
generated
vendored
Normal file
@@ -0,0 +1,42 @@
|
||||
/** Compatibility for Svelte v4 <-> v5 */
|
||||
import type ESTree from "estree";
|
||||
import type * as SvAST from "./svelte-ast-types.js";
|
||||
import type * as Compiler from "./svelte-ast-types-for-v5.js";
|
||||
export type Child = Compiler.AttachTag | Compiler.Text | Compiler.Tag | Compiler.ElementLike | Compiler.Block | Compiler.Comment;
|
||||
type HasChildren = {
|
||||
children?: SvAST.TemplateNode[];
|
||||
};
|
||||
export declare function getFragmentFromRoot(svelteAst: Compiler.Root | SvAST.AstLegacy): SvAST.Fragment | Compiler.Fragment | undefined;
|
||||
export declare function getInstanceFromRoot(svelteAst: Compiler.Root | SvAST.AstLegacy): SvAST.Script | Compiler.Script | null | undefined;
|
||||
export declare function getModuleFromRoot(svelteAst: Compiler.Root | SvAST.AstLegacy): SvAST.Script | Compiler.Script | null | undefined;
|
||||
/**
|
||||
* Source range of the instance `<script>` content, in original-source
|
||||
* coordinates. Used to tell instance-script statements apart from module-script
|
||||
* ones, which the virtual code concatenates.
|
||||
*/
|
||||
export declare function getInstanceScriptRange(svelteAst: Compiler.Root | SvAST.AstLegacy): [number, number] | null;
|
||||
export declare function getOptionsFromRoot(svelteAst: Compiler.Root | SvAST.AstLegacy): Compiler.SvelteOptionsRaw | null;
|
||||
export declare function getChildren(fragment: Required<HasChildren> | {
|
||||
nodes: (Child | SvAST.TemplateNode)[];
|
||||
}): (SvAST.TemplateNode | Child)[];
|
||||
export declare function getChildren(fragment: HasChildren | {
|
||||
nodes: (Child | SvAST.TemplateNode)[];
|
||||
}): (SvAST.TemplateNode | Child)[] | undefined;
|
||||
export declare function trimChildren(children: (SvAST.TemplateNode | Child)[]): (SvAST.TemplateNode | Child)[];
|
||||
export declare function getFragment(element: {
|
||||
fragment: Compiler.Fragment;
|
||||
} | Required<HasChildren>): Compiler.Fragment | Required<HasChildren>;
|
||||
export declare function getFragment(element: {
|
||||
fragment: Compiler.Fragment;
|
||||
} | HasChildren): Compiler.Fragment | HasChildren;
|
||||
export declare function getModifiers(node: SvAST.Directive | SvAST.StyleDirective | Compiler.Directive): string[];
|
||||
export declare function getTestFromIfBlock(block: SvAST.IfBlock | Compiler.IfBlock): ESTree.Expression;
|
||||
export declare function getConsequentFromIfBlock(block: SvAST.IfBlock | Compiler.IfBlock): Compiler.Fragment | SvAST.IfBlock;
|
||||
export declare function getAlternateFromIfBlock(block: SvAST.IfBlock | Compiler.IfBlock): Compiler.Fragment | SvAST.ElseBlock | null;
|
||||
export declare function getBodyFromEachBlock(block: SvAST.EachBlock | Compiler.EachBlock): Compiler.Fragment | SvAST.EachBlock;
|
||||
export declare function getFallbackFromEachBlock(block: SvAST.EachBlock | Compiler.EachBlock): Compiler.Fragment | SvAST.ElseBlock | null;
|
||||
export declare function getPendingFromAwaitBlock(block: SvAST.AwaitBlock | Compiler.AwaitBlock): Compiler.Fragment | SvAST.PendingBlock | null;
|
||||
export declare function getThenFromAwaitBlock(block: SvAST.AwaitBlock | Compiler.AwaitBlock): Compiler.Fragment | SvAST.ThenBlock | null;
|
||||
export declare function getCatchFromAwaitBlock(block: SvAST.AwaitBlock | Compiler.AwaitBlock): Compiler.Fragment | SvAST.CatchBlock | null;
|
||||
export declare function getDeclaratorFromConstTag(node: SvAST.ConstTag | Compiler.ConstTag): ESTree.AssignmentExpression | Compiler.ConstTag["declaration"]["declarations"][0];
|
||||
export {};
|
||||
163
node_modules/svelte-eslint-parser/lib/parser/compat.js
generated
vendored
Normal file
163
node_modules/svelte-eslint-parser/lib/parser/compat.js
generated
vendored
Normal file
@@ -0,0 +1,163 @@
|
||||
// Root
|
||||
export function getFragmentFromRoot(svelteAst) {
|
||||
return (svelteAst.fragment ?? svelteAst.html);
|
||||
}
|
||||
export function getInstanceFromRoot(svelteAst) {
|
||||
return svelteAst.instance;
|
||||
}
|
||||
export function getModuleFromRoot(svelteAst) {
|
||||
return svelteAst.module;
|
||||
}
|
||||
/**
|
||||
* Source range of the instance `<script>` content, in original-source
|
||||
* coordinates. Used to tell instance-script statements apart from module-script
|
||||
* ones, which the virtual code concatenates.
|
||||
*/
|
||||
export function getInstanceScriptRange(svelteAst) {
|
||||
const instance = getInstanceFromRoot(svelteAst);
|
||||
if (!instance) {
|
||||
return null;
|
||||
}
|
||||
const content = instance
|
||||
.content;
|
||||
if (content &&
|
||||
typeof content.start === "number" &&
|
||||
typeof content.end === "number") {
|
||||
return [content.start, content.end];
|
||||
}
|
||||
return [instance.start, instance.end];
|
||||
}
|
||||
export function getOptionsFromRoot(svelteAst) {
|
||||
const root = svelteAst;
|
||||
if (root.options) {
|
||||
return {
|
||||
type: "SvelteOptions",
|
||||
name: "svelte:options",
|
||||
// @ts-expect-error - name_loc is required in Svelte since 5.45.3 but we can not set it.
|
||||
name_loc: null,
|
||||
attributes: root.options.attributes,
|
||||
fragment: {
|
||||
type: "Fragment",
|
||||
nodes: [],
|
||||
},
|
||||
start: root.options.start,
|
||||
end: root.options.end,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
export function getChildren(fragment) {
|
||||
return (fragment.nodes ??
|
||||
fragment.children);
|
||||
}
|
||||
export function trimChildren(children) {
|
||||
if (!startsWithWhitespace(children[0]) &&
|
||||
!endsWithWhitespace(children[children.length - 1])) {
|
||||
return children;
|
||||
}
|
||||
const nodes = [...children];
|
||||
while (isWhitespace(nodes[0])) {
|
||||
nodes.shift();
|
||||
}
|
||||
const first = nodes[0];
|
||||
if (startsWithWhitespace(first)) {
|
||||
nodes[0] = { ...first, data: first.data.trimStart() };
|
||||
}
|
||||
while (isWhitespace(nodes[nodes.length - 1])) {
|
||||
nodes.pop();
|
||||
}
|
||||
const last = nodes[nodes.length - 1];
|
||||
if (endsWithWhitespace(last)) {
|
||||
nodes[nodes.length - 1] = { ...last, data: last.data.trimEnd() };
|
||||
}
|
||||
return nodes;
|
||||
function startsWithWhitespace(child) {
|
||||
if (!child) {
|
||||
return false;
|
||||
}
|
||||
return child.type === "Text" && child.data.trimStart() !== child.data;
|
||||
}
|
||||
function endsWithWhitespace(child) {
|
||||
if (!child) {
|
||||
return false;
|
||||
}
|
||||
return child.type === "Text" && child.data.trimEnd() !== child.data;
|
||||
}
|
||||
function isWhitespace(child) {
|
||||
if (!child) {
|
||||
return false;
|
||||
}
|
||||
return child.type === "Text" && child.data.trim() === "";
|
||||
}
|
||||
}
|
||||
export function getFragment(element) {
|
||||
if (element.fragment) {
|
||||
return element.fragment;
|
||||
}
|
||||
return element;
|
||||
}
|
||||
export function getModifiers(node) {
|
||||
return node.modifiers ?? [];
|
||||
}
|
||||
// IfBlock
|
||||
export function getTestFromIfBlock(block) {
|
||||
return (block.expression ?? block.test);
|
||||
}
|
||||
export function getConsequentFromIfBlock(block) {
|
||||
return block.consequent ?? block;
|
||||
}
|
||||
export function getAlternateFromIfBlock(block) {
|
||||
if (block.alternate) {
|
||||
return block.alternate;
|
||||
}
|
||||
return block.else ?? null;
|
||||
}
|
||||
// EachBlock
|
||||
export function getBodyFromEachBlock(block) {
|
||||
if (block.body) {
|
||||
return block.body;
|
||||
}
|
||||
return block;
|
||||
}
|
||||
export function getFallbackFromEachBlock(block) {
|
||||
if (block.fallback) {
|
||||
return block.fallback;
|
||||
}
|
||||
return block.else ?? null;
|
||||
}
|
||||
// AwaitBlock
|
||||
export function getPendingFromAwaitBlock(block) {
|
||||
const pending = block.pending;
|
||||
if (!pending) {
|
||||
return null;
|
||||
}
|
||||
if (pending.type === "Fragment") {
|
||||
return pending;
|
||||
}
|
||||
return pending.skip ? null : pending;
|
||||
}
|
||||
export function getThenFromAwaitBlock(block) {
|
||||
const then = block.then;
|
||||
if (!then) {
|
||||
return null;
|
||||
}
|
||||
if (then.type === "Fragment") {
|
||||
return then;
|
||||
}
|
||||
return then.skip ? null : then;
|
||||
}
|
||||
export function getCatchFromAwaitBlock(block) {
|
||||
const catchFragment = block.catch;
|
||||
if (!catchFragment) {
|
||||
return null;
|
||||
}
|
||||
if (catchFragment.type === "Fragment") {
|
||||
return catchFragment;
|
||||
}
|
||||
return catchFragment.skip ? null : catchFragment;
|
||||
}
|
||||
// ConstTag
|
||||
export function getDeclaratorFromConstTag(node) {
|
||||
return (node.declaration?.declarations?.[0] ??
|
||||
node.expression);
|
||||
}
|
||||
6
node_modules/svelte-eslint-parser/lib/parser/converts/attr.d.ts
generated
vendored
Normal file
6
node_modules/svelte-eslint-parser/lib/parser/converts/attr.d.ts
generated
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
import type { SvelteAttribute, SvelteShorthandAttribute, SvelteAttachTag, SvelteDirective, SvelteSpreadAttribute, SvelteStartTag, SvelteStyleDirective } from "../../ast/index.js";
|
||||
import type { Context } from "../../context/index.js";
|
||||
import type * as SvAST from "../svelte-ast-types.js";
|
||||
import type * as Compiler from "../svelte-ast-types-for-v5.js";
|
||||
/** Convert for Attributes */
|
||||
export declare function convertAttributes(attributes: (SvAST.AttributeOrDirective | Compiler.Attribute | Compiler.SpreadAttribute | Compiler.AttachTag | Compiler.Directive)[], parent: SvelteStartTag, ctx: Context): IterableIterator<SvelteAttribute | SvelteShorthandAttribute | SvelteSpreadAttribute | SvelteAttachTag | SvelteDirective | SvelteStyleDirective>;
|
||||
697
node_modules/svelte-eslint-parser/lib/parser/converts/attr.js
generated
vendored
Normal file
697
node_modules/svelte-eslint-parser/lib/parser/converts/attr.js
generated
vendored
Normal file
@@ -0,0 +1,697 @@
|
||||
import { getWithLoc, indexOf } from "./common.js";
|
||||
import { convertMustacheTag } from "./mustache.js";
|
||||
import { convertTextToLiteral } from "./text.js";
|
||||
import { ParseError } from "../../errors.js";
|
||||
import { svelteVersion } from "../svelte-version.js";
|
||||
import { hasTypeInfo } from "../../utils/index.js";
|
||||
import { getModifiers } from "../compat.js";
|
||||
/** Convert for Attributes */
|
||||
export function* convertAttributes(attributes, parent, ctx) {
|
||||
for (const attr of attributes) {
|
||||
if (attr.type === "Attribute") {
|
||||
yield convertAttribute(attr, parent, ctx);
|
||||
continue;
|
||||
}
|
||||
if (attr.type === "SpreadAttribute" || attr.type === "Spread") {
|
||||
yield convertSpreadAttribute(attr, parent, ctx);
|
||||
continue;
|
||||
}
|
||||
if (attr.type === "AttachTag") {
|
||||
yield convertAttachTag(attr, parent, ctx);
|
||||
continue;
|
||||
}
|
||||
if (attr.type === "BindDirective" || attr.type === "Binding") {
|
||||
yield convertBindingDirective(attr, parent, ctx);
|
||||
continue;
|
||||
}
|
||||
if (attr.type === "OnDirective" || attr.type === "EventHandler") {
|
||||
yield convertEventHandlerDirective(attr, parent, ctx);
|
||||
continue;
|
||||
}
|
||||
if (attr.type === "ClassDirective" || attr.type === "Class") {
|
||||
yield convertClassDirective(attr, parent, ctx);
|
||||
continue;
|
||||
}
|
||||
if (attr.type === "StyleDirective") {
|
||||
yield convertStyleDirective(attr, parent, ctx);
|
||||
continue;
|
||||
}
|
||||
if (attr.type === "TransitionDirective" || attr.type === "Transition") {
|
||||
yield convertTransitionDirective(attr, parent, ctx);
|
||||
continue;
|
||||
}
|
||||
if (attr.type === "AnimateDirective" || attr.type === "Animation") {
|
||||
yield convertAnimationDirective(attr, parent, ctx);
|
||||
continue;
|
||||
}
|
||||
if (attr.type === "UseDirective" || attr.type === "Action") {
|
||||
yield convertActionDirective(attr, parent, ctx);
|
||||
continue;
|
||||
}
|
||||
if (attr.type === "LetDirective") {
|
||||
yield convertLetDirective(attr, parent, ctx);
|
||||
continue;
|
||||
}
|
||||
if (attr.type === "Let") {
|
||||
yield convertLetDirective(attr, parent, ctx);
|
||||
continue;
|
||||
}
|
||||
if (attr.type === "Ref") {
|
||||
throw new ParseError("Ref are not supported.", attr.start, ctx);
|
||||
}
|
||||
if (attr.type === "Style") {
|
||||
throw new ParseError(`Svelte v3.46.0 is no longer supported. Please use Svelte>=v3.46.1.`, attr.start, ctx);
|
||||
}
|
||||
throw new ParseError(`Unknown directive or attribute (${attr.type}) are not supported.`, attr.start, ctx);
|
||||
}
|
||||
}
|
||||
/** Convert for Attribute */
|
||||
function convertAttribute(node, parent, ctx) {
|
||||
const attribute = {
|
||||
type: "SvelteAttribute",
|
||||
boolean: false,
|
||||
key: null,
|
||||
value: [],
|
||||
parent,
|
||||
...ctx.getConvertLocation(node),
|
||||
};
|
||||
const keyStart = ctx.code.indexOf(node.name, node.start);
|
||||
const keyRange = { start: keyStart, end: keyStart + node.name.length };
|
||||
attribute.key = {
|
||||
type: "SvelteName",
|
||||
name: node.name,
|
||||
parent: attribute,
|
||||
...ctx.getConvertLocation(keyRange),
|
||||
};
|
||||
if (node.value === true) {
|
||||
// Boolean attribute
|
||||
attribute.boolean = true;
|
||||
ctx.addToken("HTMLIdentifier", keyRange);
|
||||
return attribute;
|
||||
}
|
||||
const value = node.value;
|
||||
const shorthand = isAttributeShorthandForSvelteV4(value) ||
|
||||
isAttributeShorthandForSvelteV5(value);
|
||||
if (shorthand) {
|
||||
const key = {
|
||||
...attribute.key,
|
||||
type: "Identifier",
|
||||
};
|
||||
const sAttr = {
|
||||
type: "SvelteShorthandAttribute",
|
||||
key,
|
||||
value: key,
|
||||
parent,
|
||||
loc: attribute.loc,
|
||||
range: attribute.range,
|
||||
};
|
||||
key.parent = sAttr;
|
||||
ctx.scriptLet.addObjectShorthandProperty(attribute.key, sAttr, (es) => {
|
||||
if (
|
||||
// FIXME: Older parsers may use the same node. In that case, do not replace.
|
||||
// We will drop support for ESLint v7 in the next major version and remove this branch.
|
||||
es.key !== es.value) {
|
||||
sAttr.key = es.key;
|
||||
}
|
||||
sAttr.value = es.value;
|
||||
});
|
||||
return sAttr;
|
||||
}
|
||||
// Not required for shorthands. Therefore, register the token here.
|
||||
ctx.addToken("HTMLIdentifier", keyRange);
|
||||
processAttributeValue(value, attribute, parent, ctx);
|
||||
return attribute;
|
||||
function isAttributeShorthandForSvelteV4(value) {
|
||||
return Array.isArray(value) && value[0]?.type === "AttributeShorthand";
|
||||
}
|
||||
function isAttributeShorthandForSvelteV5(value) {
|
||||
return (!Array.isArray(value) &&
|
||||
value.type === "ExpressionTag" &&
|
||||
ctx.code[node.start] === "{" &&
|
||||
ctx.code[node.end - 1] === "}");
|
||||
}
|
||||
}
|
||||
/** Common process attribute value */
|
||||
function processAttributeValue(nodeValue, attribute, attributeParent, ctx) {
|
||||
const nodes = (Array.isArray(nodeValue) ? nodeValue : [nodeValue])
|
||||
.filter((v) => v.type !== "Text" ||
|
||||
// ignore empty
|
||||
// https://github.com/sveltejs/svelte/pull/6539
|
||||
v.start < v.end)
|
||||
.map((v, index, array) => {
|
||||
if (v.type === "Text") {
|
||||
const next = array[index + 1];
|
||||
if (next && next.start < v.end) {
|
||||
// Maybe bug in Svelte can cause the completion index to shift.
|
||||
return {
|
||||
...v,
|
||||
end: next.start,
|
||||
};
|
||||
}
|
||||
}
|
||||
return v;
|
||||
});
|
||||
if (nodes.length === 1 &&
|
||||
(nodes[0].type === "ExpressionTag" || nodes[0].type === "MustacheTag") &&
|
||||
attribute.type === "SvelteAttribute") {
|
||||
const typing = buildAttributeType(attributeParent.parent, attribute.key.name, ctx);
|
||||
const mustache = convertMustacheTag(nodes[0], attribute, typing, ctx);
|
||||
attribute.value.push(mustache);
|
||||
return;
|
||||
}
|
||||
for (const v of nodes) {
|
||||
if (v.type === "Text") {
|
||||
attribute.value.push(convertTextToLiteral(v, attribute, ctx));
|
||||
continue;
|
||||
}
|
||||
if (v.type === "ExpressionTag" || v.type === "MustacheTag") {
|
||||
const mustache = convertMustacheTag(v, attribute, null, ctx);
|
||||
attribute.value.push(mustache);
|
||||
continue;
|
||||
}
|
||||
const u = v;
|
||||
throw new ParseError(`Unknown attribute value (${u.type}) are not supported.`, u.start, ctx);
|
||||
}
|
||||
}
|
||||
/** Build attribute type */
|
||||
function buildAttributeType(element, attrName, ctx) {
|
||||
if (svelteVersion.gte(5) &&
|
||||
attrName.startsWith("on") &&
|
||||
(element.type !== "SvelteElement" || element.kind === "html")) {
|
||||
return buildEventHandlerType(element, attrName.slice(2), ctx);
|
||||
}
|
||||
if (element.type !== "SvelteElement" || element.kind !== "component") {
|
||||
return null;
|
||||
}
|
||||
const elementName = ctx.elements.get(element).name;
|
||||
// Svelte 3/4 ComponentProps takes an instance, while Svelte 5 also accepts
|
||||
// the component function. Extract the legacy constructor instance without
|
||||
// relying on a locally shadowable utility type such as InstanceType.
|
||||
const componentPropsType = svelteVersion.gte(5)
|
||||
? `import('svelte').ComponentProps<typeof ${elementName}>`
|
||||
: `(typeof ${elementName} extends new (...args: any[]) => (infer C extends import('svelte').SvelteComponent) ? import('svelte').ComponentProps<C> : never)`;
|
||||
return conditional({
|
||||
check: `'${attrName}'`,
|
||||
extends: `infer PROP`,
|
||||
true: conditional({
|
||||
check: `PROP`,
|
||||
extends: `keyof ${componentPropsType}`,
|
||||
true: `${componentPropsType}[PROP]`,
|
||||
false: `never`,
|
||||
}),
|
||||
false: `never`,
|
||||
});
|
||||
/** Generate `C extends E ? T : F` type. */
|
||||
function conditional(types) {
|
||||
return `${types.check} extends ${types.extends}?(${types.true}):(${types.false})`;
|
||||
}
|
||||
}
|
||||
/** Convert for Spread */
|
||||
function convertSpreadAttribute(node, parent, ctx) {
|
||||
const attribute = {
|
||||
type: "SvelteSpreadAttribute",
|
||||
argument: null,
|
||||
parent,
|
||||
...ctx.getConvertLocation(node),
|
||||
};
|
||||
const spreadStart = ctx.code.indexOf("...", node.start);
|
||||
ctx.addToken("Punctuator", {
|
||||
start: spreadStart,
|
||||
end: spreadStart + 3,
|
||||
});
|
||||
ctx.scriptLet.addExpression(node.expression, attribute, null, (es) => {
|
||||
attribute.argument = es;
|
||||
});
|
||||
return attribute;
|
||||
}
|
||||
function convertAttachTag(node, parent, ctx) {
|
||||
const attachTag = {
|
||||
type: "SvelteAttachTag",
|
||||
expression: node.expression,
|
||||
parent,
|
||||
...ctx.getConvertLocation(node),
|
||||
};
|
||||
ctx.scriptLet.addExpression(node.expression, attachTag, null, (es) => {
|
||||
attachTag.expression = es;
|
||||
});
|
||||
const atAttachStart = ctx.code.indexOf("@attach", attachTag.range[0]);
|
||||
ctx.addToken("MustacheKeyword", {
|
||||
start: atAttachStart,
|
||||
end: atAttachStart + 7,
|
||||
});
|
||||
return attachTag;
|
||||
}
|
||||
/** Convert for Binding Directive */
|
||||
function convertBindingDirective(node, parent, ctx) {
|
||||
const directive = {
|
||||
type: "SvelteDirective",
|
||||
kind: "Binding",
|
||||
key: null,
|
||||
shorthand: false,
|
||||
expression: null,
|
||||
parent,
|
||||
...ctx.getConvertLocation(node),
|
||||
};
|
||||
processDirective(node, directive, ctx, {
|
||||
processExpression(expression, shorthand) {
|
||||
directive.shorthand = shorthand;
|
||||
return ctx.scriptLet.addExpression(expression, directive, buildFunctionBindingsType(node, parent.parent, expression, ctx), (es, { getScope }) => {
|
||||
directive.expression = es;
|
||||
if (isFunctionBindings(ctx, es)) {
|
||||
directive.expression.type = "SvelteFunctionBindingsExpression";
|
||||
return;
|
||||
}
|
||||
const scope = getScope(es);
|
||||
const reference = scope.references.find((ref) => ref.identifier === es);
|
||||
if (reference) {
|
||||
// The bind directive does read and write.
|
||||
reference.isWrite = () => true;
|
||||
reference.isWriteOnly = () => false;
|
||||
reference.isReadWrite = () => true;
|
||||
reference.isReadOnly = () => false;
|
||||
reference.isRead = () => true;
|
||||
}
|
||||
});
|
||||
},
|
||||
});
|
||||
return directive;
|
||||
}
|
||||
/**
|
||||
* Function bindings on a component are typed as a setter of the bound prop. The
|
||||
* assertion applies to the whole `getter, setter` sequence, so it contextually
|
||||
* types only the setter, whose parameter receives the prop value.
|
||||
*/
|
||||
function buildFunctionBindingsType(node, element, expression, ctx) {
|
||||
if (element.type !== "SvelteElement" ||
|
||||
element.kind !== "component" ||
|
||||
expression.type !== "SequenceExpression" ||
|
||||
!isFunctionBindings(ctx, {
|
||||
...expression,
|
||||
range: [getWithLoc(expression).start, getWithLoc(expression).end],
|
||||
})) {
|
||||
return null;
|
||||
}
|
||||
const propType = buildAttributeType(element, node.name, ctx);
|
||||
// An undeclared prop resolves to `never`, which would poison the parameter.
|
||||
return (propType &&
|
||||
`(value: [${propType}] extends [never] ? any : (${propType})) => void`);
|
||||
}
|
||||
/**
|
||||
* Checks whether the given expression is Function bindings (added in Svelte 5.9.0) or not.
|
||||
* See https://svelte.dev/docs/svelte/bind#Function-bindings
|
||||
*/
|
||||
function isFunctionBindings(ctx, expression) {
|
||||
// Svelte 3/4 does not support Function bindings.
|
||||
if (!svelteVersion.gte(5)) {
|
||||
return false;
|
||||
}
|
||||
if (expression.type !== "SequenceExpression" ||
|
||||
expression.expressions.length !== 2) {
|
||||
return false;
|
||||
}
|
||||
const bindValueOpenIndex = ctx.code.lastIndexOf("{", expression.range[0]);
|
||||
if (bindValueOpenIndex < 0)
|
||||
return false;
|
||||
const betweenText = ctx.code
|
||||
.slice(bindValueOpenIndex + 1, expression.range[0])
|
||||
// Strip comments
|
||||
.replace(/\/\/[^\n]*\n|\/\*[\s\S]*?\*\//g, "")
|
||||
.trim();
|
||||
return !betweenText;
|
||||
}
|
||||
/** Convert for EventHandler Directive */
|
||||
function convertEventHandlerDirective(node, parent, ctx) {
|
||||
const directive = {
|
||||
type: "SvelteDirective",
|
||||
kind: "EventHandler",
|
||||
key: null,
|
||||
expression: null,
|
||||
parent,
|
||||
...ctx.getConvertLocation(node),
|
||||
};
|
||||
const typing = buildEventHandlerType(parent.parent, node.name, ctx);
|
||||
processDirective(node, directive, ctx, {
|
||||
processExpression: buildProcessExpressionForExpression(directive, ctx, typing),
|
||||
});
|
||||
return directive;
|
||||
}
|
||||
/** Build event handler type */
|
||||
function buildEventHandlerType(element, eventName, ctx) {
|
||||
const nativeEventHandlerType = `(e:${conditional({
|
||||
check: `'${eventName}'`,
|
||||
extends: `infer EVT`,
|
||||
true: conditional({
|
||||
check: `EVT`,
|
||||
extends: `keyof HTMLElementEventMap`,
|
||||
true: `HTMLElementEventMap[EVT]`,
|
||||
false: `CustomEvent<any>`,
|
||||
}),
|
||||
false: `never`,
|
||||
})})=>void`;
|
||||
if (element.type !== "SvelteElement") {
|
||||
return nativeEventHandlerType;
|
||||
}
|
||||
const elementName = ctx.elements.get(element).name;
|
||||
if (element.kind === "component") {
|
||||
const componentEventsType = `import('svelte').ComponentEvents<${elementName}>`;
|
||||
return `(e:${conditional({
|
||||
check: `0`,
|
||||
extends: `(1 & ${componentEventsType})`,
|
||||
// `componentEventsType` is `any`
|
||||
// `@typescript-eslint/parser` currently cannot parse `*.svelte` import types correctly.
|
||||
// So if we try to do a correct type parsing, it's argument type will be `any`.
|
||||
// A workaround is to inject the type directly, as `CustomEvent<any>` is better than `any`.
|
||||
true: `CustomEvent<any>`,
|
||||
// `componentEventsType` has an exact type.
|
||||
false: conditional({
|
||||
check: `'${eventName}'`,
|
||||
extends: `infer EVT`,
|
||||
true: conditional({
|
||||
check: `EVT`,
|
||||
extends: `keyof ${componentEventsType}`,
|
||||
true: `${componentEventsType}[EVT]`,
|
||||
false: `CustomEvent<any>`,
|
||||
}),
|
||||
false: `never`,
|
||||
}),
|
||||
})})=>void`;
|
||||
}
|
||||
if (element.kind === "special") {
|
||||
if (elementName === "svelte:component")
|
||||
return `(e:CustomEvent<any>)=>void`;
|
||||
return nativeEventHandlerType;
|
||||
}
|
||||
const attrName = `on:${eventName}`;
|
||||
const svelteHTMLElementsType = "import('svelte/elements').SvelteHTMLElements";
|
||||
return conditional({
|
||||
check: `'${elementName}'`,
|
||||
extends: "infer EL",
|
||||
true: conditional({
|
||||
check: `EL`,
|
||||
extends: `keyof ${svelteHTMLElementsType}`,
|
||||
true: conditional({
|
||||
check: `'${attrName}'`,
|
||||
extends: "infer ATTR",
|
||||
true: conditional({
|
||||
check: `ATTR`,
|
||||
extends: `keyof ${svelteHTMLElementsType}[EL]`,
|
||||
true: `${svelteHTMLElementsType}[EL][ATTR]`,
|
||||
false: nativeEventHandlerType,
|
||||
}),
|
||||
false: `never`,
|
||||
}),
|
||||
false: nativeEventHandlerType,
|
||||
}),
|
||||
false: `never`,
|
||||
});
|
||||
/** Generate `C extends E ? T : F` type. */
|
||||
function conditional(types) {
|
||||
return `${types.check} extends ${types.extends}?(${types.true}):(${types.false})`;
|
||||
}
|
||||
}
|
||||
/** Convert for Class Directive */
|
||||
function convertClassDirective(node, parent, ctx) {
|
||||
const directive = {
|
||||
type: "SvelteDirective",
|
||||
kind: "Class",
|
||||
key: null,
|
||||
shorthand: false,
|
||||
expression: null,
|
||||
parent,
|
||||
...ctx.getConvertLocation(node),
|
||||
};
|
||||
processDirective(node, directive, ctx, {
|
||||
processExpression(expression, shorthand) {
|
||||
directive.shorthand = shorthand;
|
||||
return ctx.scriptLet.addExpression(expression, directive);
|
||||
},
|
||||
});
|
||||
return directive;
|
||||
}
|
||||
/** Convert for Style Directive */
|
||||
function convertStyleDirective(node, parent, ctx) {
|
||||
const directive = {
|
||||
type: "SvelteStyleDirective",
|
||||
key: null,
|
||||
shorthand: false,
|
||||
value: [],
|
||||
parent,
|
||||
...ctx.getConvertLocation(node),
|
||||
};
|
||||
processDirectiveKey(node, directive, ctx);
|
||||
const keyName = directive.key.name;
|
||||
if (node.value === true) {
|
||||
const shorthandDirective = directive;
|
||||
shorthandDirective.shorthand = true;
|
||||
ctx.scriptLet.addExpression(keyName, shorthandDirective.key, null, (expression) => {
|
||||
if (expression.type !== "Identifier") {
|
||||
throw new ParseError(`Expected JS identifier or attribute value.`, expression.range[0], ctx);
|
||||
}
|
||||
shorthandDirective.key.name = expression;
|
||||
});
|
||||
return shorthandDirective;
|
||||
}
|
||||
ctx.addToken("HTMLIdentifier", {
|
||||
start: keyName.range[0],
|
||||
end: keyName.range[1],
|
||||
});
|
||||
processAttributeValue(node.value, directive, parent, ctx);
|
||||
return directive;
|
||||
}
|
||||
/** Convert for Transition Directive */
|
||||
function convertTransitionDirective(node, parent, ctx) {
|
||||
const directive = {
|
||||
type: "SvelteDirective",
|
||||
kind: "Transition",
|
||||
intro: node.intro,
|
||||
outro: node.outro,
|
||||
key: null,
|
||||
expression: null,
|
||||
parent,
|
||||
...ctx.getConvertLocation(node),
|
||||
};
|
||||
processDirective(node, directive, ctx, {
|
||||
processExpression: buildProcessExpressionForExpression(directive, ctx, null),
|
||||
processName: (name) => ctx.scriptLet.addExpression(name, directive.key, null, buildExpressionTypeChecker(["Identifier"], ctx)),
|
||||
});
|
||||
return directive;
|
||||
}
|
||||
/** Convert for Animation Directive */
|
||||
function convertAnimationDirective(node, parent, ctx) {
|
||||
const directive = {
|
||||
type: "SvelteDirective",
|
||||
kind: "Animation",
|
||||
key: null,
|
||||
expression: null,
|
||||
parent,
|
||||
...ctx.getConvertLocation(node),
|
||||
};
|
||||
processDirective(node, directive, ctx, {
|
||||
processExpression: buildProcessExpressionForExpression(directive, ctx, null),
|
||||
processName: (name) => ctx.scriptLet.addExpression(name, directive.key, null, buildExpressionTypeChecker(["Identifier"], ctx)),
|
||||
});
|
||||
return directive;
|
||||
}
|
||||
/** Convert for Action Directive */
|
||||
function convertActionDirective(node, parent, ctx) {
|
||||
const directive = {
|
||||
type: "SvelteDirective",
|
||||
kind: "Action",
|
||||
key: null,
|
||||
expression: null,
|
||||
parent,
|
||||
...ctx.getConvertLocation(node),
|
||||
};
|
||||
processDirective(node, directive, ctx, {
|
||||
processExpression: buildProcessExpressionForExpression(directive, ctx, `Parameters<typeof ${node.name}>[1]`),
|
||||
processName: (name) => ctx.scriptLet.addExpression(name, directive.key, null, buildExpressionTypeChecker(["Identifier", "MemberExpression"], ctx)),
|
||||
});
|
||||
return directive;
|
||||
}
|
||||
/** Convert for Let Directive */
|
||||
function convertLetDirective(node, parent, ctx) {
|
||||
const directive = {
|
||||
type: "SvelteDirective",
|
||||
kind: "Let",
|
||||
key: null,
|
||||
expression: null,
|
||||
parent,
|
||||
...ctx.getConvertLocation(node),
|
||||
};
|
||||
processDirective(node, directive, ctx, {
|
||||
processPattern(pattern) {
|
||||
return ctx.letDirCollections
|
||||
.getCollection()
|
||||
.addPattern(pattern, directive, buildLetDirectiveType(parent.parent, node.name, ctx));
|
||||
},
|
||||
processName: node.expression
|
||||
? undefined
|
||||
: (name) => {
|
||||
// shorthand
|
||||
ctx.letDirCollections
|
||||
.getCollection()
|
||||
.addPattern(name, directive, buildLetDirectiveType(parent.parent, node.name, ctx), (es) => {
|
||||
directive.expression = es;
|
||||
});
|
||||
return [];
|
||||
},
|
||||
});
|
||||
return directive;
|
||||
}
|
||||
/** Build let directive param type */
|
||||
function buildLetDirectiveType(element, letName, ctx) {
|
||||
if (element.type !== "SvelteElement") {
|
||||
return "any";
|
||||
}
|
||||
let slotName = "default";
|
||||
let componentName;
|
||||
const svelteNode = ctx.elements.get(element);
|
||||
const slotAttr = svelteNode.attributes.find((attr) => {
|
||||
return attr.type === "Attribute" && attr.name === "slot";
|
||||
});
|
||||
if (slotAttr) {
|
||||
if (Array.isArray(slotAttr.value) &&
|
||||
slotAttr.value.length === 1 &&
|
||||
slotAttr.value[0].type === "Text") {
|
||||
slotName = slotAttr.value[0].data;
|
||||
}
|
||||
else {
|
||||
return "any";
|
||||
}
|
||||
const parent = findParentComponent(element);
|
||||
if (parent == null)
|
||||
return "any";
|
||||
componentName = ctx.elements.get(parent).name;
|
||||
}
|
||||
else {
|
||||
if (element.kind === "component") {
|
||||
componentName = svelteNode.name;
|
||||
}
|
||||
else {
|
||||
const parent = findParentComponent(element);
|
||||
if (parent == null)
|
||||
return "any";
|
||||
componentName = ctx.elements.get(parent).name;
|
||||
}
|
||||
}
|
||||
return `${String(componentName)}['$$slot_def'][${JSON.stringify(slotName)}][${JSON.stringify(letName)}]`;
|
||||
/** Find parent component element */
|
||||
function findParentComponent(node) {
|
||||
let parent = node.parent;
|
||||
while (parent && parent.type !== "SvelteElement") {
|
||||
parent = parent.parent;
|
||||
}
|
||||
if (!parent || parent.kind !== "component") {
|
||||
return null;
|
||||
}
|
||||
return parent;
|
||||
}
|
||||
}
|
||||
/** Common process for directive */
|
||||
function processDirective(node, directive, ctx, processors) {
|
||||
processDirectiveKey(node, directive, ctx);
|
||||
processDirectiveExpression(node, directive, ctx, processors);
|
||||
}
|
||||
/** Common process for directive key */
|
||||
function processDirectiveKey(node, directive, ctx) {
|
||||
const colonIndex = ctx.code.indexOf(":", directive.range[0]);
|
||||
ctx.addToken("HTMLIdentifier", {
|
||||
start: directive.range[0],
|
||||
end: colonIndex,
|
||||
});
|
||||
const nameIndex = ctx.code.indexOf(node.name, colonIndex + 1);
|
||||
const nameRange = {
|
||||
start: nameIndex,
|
||||
end: nameIndex + node.name.length,
|
||||
};
|
||||
let keyEndIndex = nameRange.end;
|
||||
// modifiers
|
||||
if (ctx.code[nameRange.end] === "|") {
|
||||
let nextStart = nameRange.end + 1;
|
||||
let nextEnd = indexOf(ctx.code, (c) => c === "=" || c === ">" || c === "/" || c === "|" || !c.trim(), nextStart);
|
||||
ctx.addToken("HTMLIdentifier", { start: nextStart, end: nextEnd });
|
||||
while (ctx.code[nextEnd] === "|") {
|
||||
nextStart = nextEnd + 1;
|
||||
nextEnd = indexOf(ctx.code, (c) => c === "=" || c === ">" || c === "/" || c === "|" || !c.trim(), nextStart);
|
||||
ctx.addToken("HTMLIdentifier", { start: nextStart, end: nextEnd });
|
||||
}
|
||||
keyEndIndex = nextEnd;
|
||||
}
|
||||
const key = (directive.key = {
|
||||
type: "SvelteDirectiveKey",
|
||||
name: null,
|
||||
modifiers: getModifiers(node),
|
||||
parent: directive,
|
||||
...ctx.getConvertLocation({ start: node.start, end: keyEndIndex }),
|
||||
});
|
||||
// put name
|
||||
key.name = {
|
||||
type: "SvelteName",
|
||||
name: node.name,
|
||||
parent: key,
|
||||
...ctx.getConvertLocation(nameRange),
|
||||
};
|
||||
}
|
||||
/** Common process for directive expression */
|
||||
function processDirectiveExpression(node, directive, ctx, processors) {
|
||||
const key = directive.key;
|
||||
const keyName = key.name;
|
||||
let shorthand = false;
|
||||
if (node.expression) {
|
||||
shorthand =
|
||||
node.expression.type === "Identifier" &&
|
||||
node.expression.name === node.name &&
|
||||
getWithLoc(node.expression).start === keyName.range[0];
|
||||
if (shorthand && getWithLoc(node.expression).end !== keyName.range[1]) {
|
||||
// The identifier location may be incorrect in some edge cases.
|
||||
// e.g. bind:value=""
|
||||
getWithLoc(node.expression).end = keyName.range[1];
|
||||
}
|
||||
if (processors.processExpression) {
|
||||
processors.processExpression(node.expression, shorthand).push((es) => {
|
||||
if (node.expression &&
|
||||
(es.type === "SvelteFunctionBindingsExpression"
|
||||
? "SequenceExpression"
|
||||
: es.type) !== node.expression.type) {
|
||||
throw new ParseError(`Expected ${node.expression.type}, but ${es.type} found.`, es.range[0], ctx);
|
||||
}
|
||||
directive.expression = es;
|
||||
});
|
||||
}
|
||||
else {
|
||||
processors.processPattern(node.expression, shorthand).push((es) => {
|
||||
directive.expression = es;
|
||||
});
|
||||
}
|
||||
}
|
||||
if (!shorthand) {
|
||||
if (processors.processName) {
|
||||
processors.processName(keyName).push((es) => {
|
||||
key.name = es;
|
||||
});
|
||||
}
|
||||
else {
|
||||
ctx.addToken("HTMLIdentifier", {
|
||||
start: keyName.range[0],
|
||||
end: keyName.range[1],
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
/** Build processExpression for Expression */
|
||||
function buildProcessExpressionForExpression(directive, ctx, typing) {
|
||||
return (expression) => {
|
||||
if (hasTypeInfo(expression)) {
|
||||
return ctx.scriptLet.addExpression(expression, directive, null);
|
||||
}
|
||||
return ctx.scriptLet.addExpression(expression, directive, typing);
|
||||
};
|
||||
}
|
||||
/** Build expression type checker to script let callbacks */
|
||||
function buildExpressionTypeChecker(expected, ctx) {
|
||||
return (node) => {
|
||||
if (!expected.includes(node.type)) {
|
||||
throw new ParseError(`Expected JS ${expected.join(", or ")}, but ${node.type} found.`, node.range[0], ctx);
|
||||
}
|
||||
};
|
||||
}
|
||||
16
node_modules/svelte-eslint-parser/lib/parser/converts/block.d.ts
generated
vendored
Normal file
16
node_modules/svelte-eslint-parser/lib/parser/converts/block.d.ts
generated
vendored
Normal file
@@ -0,0 +1,16 @@
|
||||
import type * as SvAST from "../svelte-ast-types.js";
|
||||
import type * as Compiler from "../svelte-ast-types-for-v5.js";
|
||||
import type { SvelteAwaitBlock, SvelteEachBlock, SvelteIfBlock, SvelteIfBlockAlone, SvelteIfBlockElseIf, SvelteKeyBlock, SvelteSnippetBlock } from "../../ast/index.js";
|
||||
import type { Context } from "../../context/index.js";
|
||||
export declare function convertIfBlock(node: SvAST.IfBlock | Compiler.IfBlock, parent: SvelteIfBlock["parent"], ctx: Context): SvelteIfBlockAlone;
|
||||
export declare function convertIfBlock(node: SvAST.IfBlock | Compiler.IfBlock, parent: SvelteIfBlock["parent"], ctx: Context, elseifContext?: {
|
||||
start: number;
|
||||
}): SvelteIfBlockElseIf;
|
||||
/** Convert for EachBlock */
|
||||
export declare function convertEachBlock(node: SvAST.EachBlock | Compiler.EachBlock, parent: SvelteEachBlock["parent"], ctx: Context): SvelteEachBlock;
|
||||
/** Convert for AwaitBlock */
|
||||
export declare function convertAwaitBlock(node: SvAST.AwaitBlock | Compiler.AwaitBlock, parent: SvelteAwaitBlock["parent"], ctx: Context): SvelteAwaitBlock;
|
||||
/** Convert for KeyBlock */
|
||||
export declare function convertKeyBlock(node: SvAST.KeyBlock | Compiler.KeyBlock, parent: SvelteKeyBlock["parent"], ctx: Context): SvelteKeyBlock;
|
||||
/** Convert for SnippetBlock */
|
||||
export declare function convertSnippetBlock(node: Compiler.SnippetBlock, parent: SvelteSnippetBlock["parent"], ctx: Context): SvelteSnippetBlock;
|
||||
555
node_modules/svelte-eslint-parser/lib/parser/converts/block.js
generated
vendored
Normal file
555
node_modules/svelte-eslint-parser/lib/parser/converts/block.js
generated
vendored
Normal file
@@ -0,0 +1,555 @@
|
||||
import { convertChildren } from "./element.js";
|
||||
import { getWithLoc, indexOf, lastIndexOf } from "./common.js";
|
||||
import { svelteVersion } from "../svelte-version.js";
|
||||
import { getAlternateFromIfBlock, getBodyFromEachBlock, getCatchFromAwaitBlock, getChildren, getConsequentFromIfBlock, getFallbackFromEachBlock, getFragment, getPendingFromAwaitBlock, getTestFromIfBlock, getThenFromAwaitBlock, trimChildren, } from "../compat.js";
|
||||
/** Get start index of block */
|
||||
function startBlockIndex(code, endIndex, block) {
|
||||
return lastIndexOf(code, (c, index) => {
|
||||
if (c !== "{") {
|
||||
return false;
|
||||
}
|
||||
for (let next = index + 1; next < code.length; next++) {
|
||||
const nextC = code[next];
|
||||
if (!nextC.trim()) {
|
||||
continue;
|
||||
}
|
||||
return code.startsWith(block, next);
|
||||
}
|
||||
return false;
|
||||
}, endIndex);
|
||||
}
|
||||
function startIndexFromFragment(fragment, getBeforeEndIndex) {
|
||||
if (fragment.start != null) {
|
||||
return fragment.start;
|
||||
}
|
||||
const children = getChildren(fragment);
|
||||
return children.length ? children[0].start : getBeforeEndIndex();
|
||||
}
|
||||
function endIndexFromFragment(fragment, getBeforeEndIndex) {
|
||||
if (fragment.end != null) {
|
||||
return fragment.end;
|
||||
}
|
||||
const children = getChildren(fragment);
|
||||
return children.length
|
||||
? children[children.length - 1].end
|
||||
: getBeforeEndIndex();
|
||||
}
|
||||
function endIndexFromBlock(fragment, lastExpression, ctx) {
|
||||
return endIndexFromFragment(fragment, () => {
|
||||
return ctx.code.indexOf("}", getWithLoc(lastExpression).end) + 1;
|
||||
});
|
||||
}
|
||||
/** Convert for IfBlock */
|
||||
export function convertIfBlock(node, parent, ctx, elseifContext) {
|
||||
// {#if expr} {:else} {/if}
|
||||
// {:else if expr} {/if}
|
||||
const elseif = Boolean(elseifContext);
|
||||
const nodeStart = startBlockIndex(ctx.code, elseifContext?.start ?? node.start, elseif ? ":else" : "#if");
|
||||
const ifBlock = {
|
||||
type: "SvelteIfBlock",
|
||||
elseif: Boolean(elseif),
|
||||
expression: null,
|
||||
children: [],
|
||||
else: null,
|
||||
parent,
|
||||
...ctx.getConvertLocation({ start: nodeStart, end: node.end }),
|
||||
};
|
||||
const test = getTestFromIfBlock(node);
|
||||
const { beginElse } = ctx.scriptLet.nestIfBlock(test, ifBlock, (es) => {
|
||||
ifBlock.expression = es;
|
||||
});
|
||||
const consequent = getConsequentFromIfBlock(node);
|
||||
for (const child of convertChildren({
|
||||
nodes:
|
||||
// Adjust for Svelte v5
|
||||
trimChildren(getChildren(consequent)),
|
||||
}, ifBlock, ctx)) {
|
||||
ifBlock.children.push(child);
|
||||
}
|
||||
if (elseif) {
|
||||
const index = ctx.code.indexOf("if", nodeStart);
|
||||
ctx.addToken("MustacheKeyword", { start: index, end: index + 2 });
|
||||
}
|
||||
extractMustacheBlockTokens(ifBlock, ctx, { startOnly: elseif });
|
||||
const elseFragment = getAlternateFromIfBlock(node);
|
||||
if (!elseFragment) {
|
||||
ctx.scriptLet.closeScope();
|
||||
return ifBlock;
|
||||
}
|
||||
beginElse();
|
||||
const elseStart = startBlockIndexForElse(elseFragment, consequent, test, ctx);
|
||||
const elseChildren = getChildren(elseFragment);
|
||||
if (elseChildren.length === 1) {
|
||||
const c = elseChildren[0];
|
||||
if (c.type === "IfBlock" && c.elseif) {
|
||||
const elseBlock = {
|
||||
type: "SvelteElseBlock",
|
||||
elseif: true,
|
||||
children: [],
|
||||
parent: ifBlock,
|
||||
...ctx.getConvertLocation({
|
||||
start: elseStart,
|
||||
end: c.end,
|
||||
}),
|
||||
};
|
||||
ifBlock.else = elseBlock;
|
||||
const elseIfBlock = convertIfBlock(c, elseBlock, ctx, {
|
||||
start: elseStart,
|
||||
});
|
||||
// adjust loc
|
||||
elseBlock.range[1] = elseIfBlock.range[1];
|
||||
elseBlock.loc.end = {
|
||||
line: elseIfBlock.loc.end.line,
|
||||
column: elseIfBlock.loc.end.column,
|
||||
};
|
||||
elseBlock.children = [elseIfBlock];
|
||||
ctx.scriptLet.closeScope();
|
||||
return ifBlock;
|
||||
}
|
||||
}
|
||||
const elseBlock = {
|
||||
type: "SvelteElseBlock",
|
||||
elseif: false,
|
||||
children: [],
|
||||
parent: ifBlock,
|
||||
...ctx.getConvertLocation({
|
||||
start: elseStart,
|
||||
end: endIndexFromFragment(elseFragment, () => ctx.code.indexOf("}", elseStart + 5) + 1),
|
||||
}),
|
||||
};
|
||||
ifBlock.else = elseBlock;
|
||||
ctx.scriptLet.nestBlock(elseBlock);
|
||||
for (const child of convertChildren({
|
||||
nodes:
|
||||
// Adjust for Svelte v5
|
||||
trimChildren(elseChildren),
|
||||
}, elseBlock, ctx)) {
|
||||
elseBlock.children.push(child);
|
||||
}
|
||||
ctx.scriptLet.closeScope(); // else block
|
||||
ctx.scriptLet.closeScope(); // if statement
|
||||
extractMustacheBlockTokens(elseBlock, ctx, { startOnly: true });
|
||||
return ifBlock;
|
||||
}
|
||||
function startBlockIndexForElse(elseFragment, beforeFragment, lastExpression, ctx) {
|
||||
const elseChildren = getChildren(elseFragment);
|
||||
if (elseChildren.length > 0) {
|
||||
const c = elseChildren[0];
|
||||
if (c.type === "IfBlock" && c.elseif) {
|
||||
const contentStart = getWithLoc(getTestFromIfBlock(c)).start;
|
||||
if (contentStart <= c.start) {
|
||||
return startBlockIndex(ctx.code, contentStart - 1, ":else");
|
||||
}
|
||||
}
|
||||
return startBlockIndex(ctx.code, c.start, ":else");
|
||||
}
|
||||
const beforeEnd = endIndexFromFragment(beforeFragment, () => {
|
||||
return ctx.code.indexOf("}", getWithLoc(lastExpression).end) + 1;
|
||||
});
|
||||
return startBlockIndex(ctx.code, beforeEnd, ":else");
|
||||
}
|
||||
/** Convert for EachBlock */
|
||||
export function convertEachBlock(node, parent, ctx) {
|
||||
// {#each expr as item, index (key)} {/each}
|
||||
const nodeStart = startBlockIndex(ctx.code, node.start, "#each");
|
||||
const eachBlock = {
|
||||
type: "SvelteEachBlock",
|
||||
expression: null,
|
||||
context: null,
|
||||
index: null,
|
||||
key: null,
|
||||
children: [],
|
||||
else: null,
|
||||
parent,
|
||||
...ctx.getConvertLocation({ start: nodeStart, end: node.end }),
|
||||
};
|
||||
let indexRange = null;
|
||||
if (node.index) {
|
||||
const start = ctx.code.indexOf(node.index, getWithLoc(node.context ?? node.expression).end);
|
||||
indexRange = {
|
||||
start,
|
||||
end: start + node.index.length,
|
||||
};
|
||||
}
|
||||
ctx.scriptLet.nestEachBlock(node.expression, node.context, indexRange, eachBlock, (expression, context, index) => {
|
||||
eachBlock.expression = expression;
|
||||
eachBlock.context = context;
|
||||
eachBlock.index = index;
|
||||
});
|
||||
if (node.context) {
|
||||
const asStart = ctx.code.indexOf("as", getWithLoc(node.expression).end);
|
||||
ctx.addToken("Keyword", {
|
||||
start: asStart,
|
||||
end: asStart + 2,
|
||||
});
|
||||
}
|
||||
if (node.key) {
|
||||
ctx.scriptLet.addExpression(node.key, eachBlock, null, (key) => {
|
||||
eachBlock.key = key;
|
||||
});
|
||||
}
|
||||
const body = getBodyFromEachBlock(node);
|
||||
eachBlock.children.push(...convertChildren({
|
||||
nodes:
|
||||
// Adjust for Svelte v5
|
||||
trimChildren(getChildren(body)),
|
||||
}, eachBlock, ctx));
|
||||
ctx.scriptLet.closeScope();
|
||||
extractMustacheBlockTokens(eachBlock, ctx);
|
||||
const fallbackFragment = getFallbackFromEachBlock(node);
|
||||
if (!fallbackFragment) {
|
||||
return eachBlock;
|
||||
}
|
||||
const elseStart = startBlockIndexForElse(fallbackFragment, body, node.key || indexRange || node.context || node.expression, ctx);
|
||||
const elseBlock = {
|
||||
type: "SvelteElseBlock",
|
||||
elseif: false,
|
||||
children: [],
|
||||
parent: eachBlock,
|
||||
...ctx.getConvertLocation({
|
||||
start: elseStart,
|
||||
end: endIndexFromFragment(fallbackFragment, () => elseStart),
|
||||
}),
|
||||
};
|
||||
eachBlock.else = elseBlock;
|
||||
ctx.scriptLet.nestBlock(elseBlock);
|
||||
elseBlock.children.push(...convertChildren({
|
||||
nodes:
|
||||
// Adjust for Svelte v5
|
||||
trimChildren(getChildren(fallbackFragment)),
|
||||
}, elseBlock, ctx));
|
||||
ctx.scriptLet.closeScope();
|
||||
extractMustacheBlockTokens(elseBlock, ctx, { startOnly: true });
|
||||
return eachBlock;
|
||||
}
|
||||
/** Convert for AwaitBlock */
|
||||
export function convertAwaitBlock(node, parent, ctx) {
|
||||
const nodeStart = startBlockIndex(ctx.code, node.start, "#await");
|
||||
const awaitBlock = {
|
||||
type: "SvelteAwaitBlock",
|
||||
expression: null,
|
||||
kind: "await",
|
||||
pending: null,
|
||||
then: null,
|
||||
catch: null,
|
||||
parent,
|
||||
...ctx.getConvertLocation({ start: nodeStart, end: node.end }),
|
||||
};
|
||||
ctx.scriptLet.addExpression(node.expression, awaitBlock, null, (expression) => {
|
||||
awaitBlock.expression = expression;
|
||||
});
|
||||
const pending = getPendingFromAwaitBlock(node);
|
||||
if (pending) {
|
||||
const pendingBlock = {
|
||||
type: "SvelteAwaitPendingBlock",
|
||||
children: [],
|
||||
parent: awaitBlock,
|
||||
...ctx.getConvertLocation({
|
||||
start: awaitBlock.range[0],
|
||||
end: endIndexFromBlock(pending, node.expression, ctx),
|
||||
}),
|
||||
};
|
||||
ctx.scriptLet.nestBlock(pendingBlock);
|
||||
pendingBlock.children.push(...convertChildren(pending, pendingBlock, ctx));
|
||||
awaitBlock.pending = pendingBlock;
|
||||
ctx.scriptLet.closeScope();
|
||||
}
|
||||
const then = getThenFromAwaitBlock(node);
|
||||
if (then) {
|
||||
const awaitThen = !pending;
|
||||
if (awaitThen) {
|
||||
awaitBlock.kind = "await-then";
|
||||
}
|
||||
const thenStart = awaitBlock.pending
|
||||
? startBlockIndex(ctx.code, node.value
|
||||
? getWithLoc(node.value).start
|
||||
: startIndexFromFragment(then, () => {
|
||||
return awaitBlock.pending.range[1];
|
||||
}), ":then")
|
||||
: nodeStart;
|
||||
const thenBlock = {
|
||||
type: "SvelteAwaitThenBlock",
|
||||
awaitThen,
|
||||
value: null,
|
||||
children: [],
|
||||
parent: awaitBlock,
|
||||
...ctx.getConvertLocation({
|
||||
start: thenStart,
|
||||
end: endIndexFromFragment(then, () => {
|
||||
return (ctx.code.indexOf("}", node.value ? getWithLoc(node.value).end : thenStart + 5) + 1);
|
||||
}),
|
||||
}),
|
||||
};
|
||||
if (node.value) {
|
||||
const baseParam = {
|
||||
node: node.value,
|
||||
parent: thenBlock,
|
||||
callback(value) {
|
||||
thenBlock.value = value;
|
||||
},
|
||||
typing: "any",
|
||||
};
|
||||
ctx.scriptLet.nestBlock(thenBlock, (typeCtx) => {
|
||||
if (!typeCtx) {
|
||||
return {
|
||||
param: baseParam,
|
||||
};
|
||||
}
|
||||
const expression = ctx.getText(node.expression);
|
||||
if (node.expression.type === "Literal") {
|
||||
return {
|
||||
param: {
|
||||
...baseParam,
|
||||
typing: expression,
|
||||
},
|
||||
};
|
||||
}
|
||||
const idAwaitThenValue = typeCtx.generateUniqueId("AwaitThenValue");
|
||||
if (node.expression.type === "Identifier" &&
|
||||
// We cannot use type annotations like `(x: Foo<x>)` if they have the same identifier name.
|
||||
!hasIdentifierFor(node.expression.name, baseParam.node)) {
|
||||
return {
|
||||
preparationScript: [generateAwaitThenValueType(idAwaitThenValue)],
|
||||
param: {
|
||||
...baseParam,
|
||||
typing: `${idAwaitThenValue}<(typeof ${expression})>`,
|
||||
},
|
||||
};
|
||||
}
|
||||
const id = typeCtx.generateUniqueId(expression);
|
||||
return {
|
||||
preparationScript: [
|
||||
{
|
||||
script: `const ${id} = ${expression};`,
|
||||
nodeType: "VariableDeclaration",
|
||||
},
|
||||
generateAwaitThenValueType(idAwaitThenValue),
|
||||
],
|
||||
param: {
|
||||
...baseParam,
|
||||
typing: `${idAwaitThenValue}<(typeof ${id})>`,
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
else {
|
||||
ctx.scriptLet.nestBlock(thenBlock);
|
||||
}
|
||||
thenBlock.children.push(...convertChildren(then, thenBlock, ctx));
|
||||
if (awaitBlock.pending) {
|
||||
extractMustacheBlockTokens(thenBlock, ctx, { startOnly: true });
|
||||
}
|
||||
else {
|
||||
const thenIndex = ctx.code.indexOf("then", getWithLoc(node.expression).end);
|
||||
ctx.addToken("MustacheKeyword", {
|
||||
start: thenIndex,
|
||||
end: thenIndex + 4,
|
||||
});
|
||||
}
|
||||
awaitBlock.then = thenBlock;
|
||||
ctx.scriptLet.closeScope();
|
||||
}
|
||||
const catchFragment = getCatchFromAwaitBlock(node);
|
||||
if (catchFragment) {
|
||||
const awaitCatch = !pending && !then;
|
||||
if (awaitCatch) {
|
||||
awaitBlock.kind = "await-catch";
|
||||
}
|
||||
const catchStart = awaitBlock.then || awaitBlock.pending
|
||||
? startBlockIndex(ctx.code, node.error
|
||||
? getWithLoc(node.error).start
|
||||
: startIndexFromFragment(catchFragment, () => {
|
||||
return (awaitBlock.then || awaitBlock.pending).range[1];
|
||||
}), ":catch")
|
||||
: nodeStart;
|
||||
const catchBlock = {
|
||||
type: "SvelteAwaitCatchBlock",
|
||||
awaitCatch,
|
||||
error: null,
|
||||
children: [],
|
||||
parent: awaitBlock,
|
||||
...ctx.getConvertLocation({
|
||||
start: catchStart,
|
||||
end: endIndexFromFragment(catchFragment, () => {
|
||||
return (ctx.code.indexOf("}", node.error ? getWithLoc(node.error).end : catchStart + 6) + 1);
|
||||
}),
|
||||
}),
|
||||
};
|
||||
if (node.error) {
|
||||
ctx.scriptLet.nestBlock(catchBlock, [
|
||||
{
|
||||
node: node.error,
|
||||
parent: catchBlock,
|
||||
typing: "Error",
|
||||
callback: (error) => {
|
||||
catchBlock.error = error;
|
||||
},
|
||||
},
|
||||
]);
|
||||
}
|
||||
else {
|
||||
ctx.scriptLet.nestBlock(catchBlock);
|
||||
}
|
||||
catchBlock.children.push(...convertChildren(catchFragment, catchBlock, ctx));
|
||||
if (awaitBlock.pending || awaitBlock.then) {
|
||||
extractMustacheBlockTokens(catchBlock, ctx, { startOnly: true });
|
||||
}
|
||||
else {
|
||||
const catchIndex = ctx.code.indexOf("catch", getWithLoc(node.expression).end);
|
||||
ctx.addToken("MustacheKeyword", {
|
||||
start: catchIndex,
|
||||
end: catchIndex + 5,
|
||||
});
|
||||
}
|
||||
awaitBlock.catch = catchBlock;
|
||||
ctx.scriptLet.closeScope();
|
||||
}
|
||||
extractMustacheBlockTokens(awaitBlock, ctx);
|
||||
return awaitBlock;
|
||||
}
|
||||
/** Convert for KeyBlock */
|
||||
export function convertKeyBlock(node, parent, ctx) {
|
||||
const nodeStart = startBlockIndex(ctx.code, node.start, "#key");
|
||||
const keyBlock = {
|
||||
type: "SvelteKeyBlock",
|
||||
expression: null,
|
||||
children: [],
|
||||
parent,
|
||||
...ctx.getConvertLocation({ start: nodeStart, end: node.end }),
|
||||
};
|
||||
ctx.scriptLet.addExpression(node.expression, keyBlock, null, (expression) => {
|
||||
keyBlock.expression = expression;
|
||||
});
|
||||
ctx.scriptLet.nestBlock(keyBlock);
|
||||
keyBlock.children.push(...convertChildren({
|
||||
nodes:
|
||||
// Adjust for Svelte v5
|
||||
trimChildren(getChildren(getFragment(node))),
|
||||
}, keyBlock, ctx));
|
||||
ctx.scriptLet.closeScope();
|
||||
extractMustacheBlockTokens(keyBlock, ctx);
|
||||
return keyBlock;
|
||||
}
|
||||
/** Convert for SnippetBlock */
|
||||
export function convertSnippetBlock(node, parent, ctx) {
|
||||
// {#snippet x(args)}...{/snippet}
|
||||
const nodeStart = startBlockIndex(ctx.code, node.start, "#snippet");
|
||||
const snippetBlock = {
|
||||
type: "SvelteSnippetBlock",
|
||||
id: null,
|
||||
params: [],
|
||||
children: [],
|
||||
parent,
|
||||
...ctx.getConvertLocation({ start: nodeStart, end: node.end }),
|
||||
};
|
||||
let beforeClosingParen;
|
||||
if (node.parameters.length > 0) {
|
||||
const lastParam = node.parameters[node.parameters.length - 1];
|
||||
beforeClosingParen = lastParam.typeAnnotation ?? lastParam;
|
||||
}
|
||||
else {
|
||||
beforeClosingParen = node.expression;
|
||||
}
|
||||
const closeParenIndex = ctx.code.indexOf(")", getWithLoc(beforeClosingParen).end);
|
||||
const scopeKind = parent.type === "Program"
|
||||
? "snippet"
|
||||
: // use currentScriptScopeKind
|
||||
null;
|
||||
ctx.scriptLet.nestSnippetBlock(node.expression, closeParenIndex, snippetBlock, scopeKind, buildSnippetParamTypes(node, parent, ctx), (id, params) => {
|
||||
snippetBlock.id = id;
|
||||
snippetBlock.params = params;
|
||||
});
|
||||
snippetBlock.children.push(...convertChildren({
|
||||
nodes:
|
||||
// Adjust for Svelte v5
|
||||
trimChildren(node.body.nodes),
|
||||
}, snippetBlock, ctx));
|
||||
ctx.scriptLet.closeScope();
|
||||
extractMustacheBlockTokens(snippetBlock, ctx);
|
||||
ctx.snippets.push(snippetBlock);
|
||||
return snippetBlock;
|
||||
}
|
||||
/**
|
||||
* A snippet written as a child of a component is passed to it as the prop of
|
||||
* the same name, so its unannotated parameters take their types from that prop.
|
||||
*/
|
||||
function buildSnippetParamTypes(node, parent, ctx) {
|
||||
if (!ctx.isTypeScript() ||
|
||||
!svelteVersion.gte(5) ||
|
||||
parent.type !== "SvelteElement" ||
|
||||
parent.kind !== "component") {
|
||||
return null;
|
||||
}
|
||||
const elementName = ctx.elements.get(parent).name;
|
||||
const componentPropsType = `import('svelte').ComponentProps<typeof ${elementName}>`;
|
||||
const snippetName = node.expression.name;
|
||||
// Fall back to `any` for a prop the component does not declare, rather than
|
||||
// letting `never` poison every use of the parameter.
|
||||
const snippetType = `('${snippetName}' extends infer KEY?KEY extends keyof ${componentPropsType}?NonNullable<${componentPropsType}[KEY]>:any:any)`;
|
||||
const types = [];
|
||||
node.parameters.forEach((param, index) => {
|
||||
// A default value or rest element cannot take a positional annotation.
|
||||
if (param.typeAnnotation ||
|
||||
param.type === "AssignmentPattern" ||
|
||||
param.type === "RestElement") {
|
||||
return;
|
||||
}
|
||||
types.push({
|
||||
param,
|
||||
type: `${snippetType} extends (...args: infer A) => any ? A[${index}] : any`,
|
||||
});
|
||||
});
|
||||
return types.length ? types : null;
|
||||
}
|
||||
/** Extract mustache block tokens */
|
||||
function extractMustacheBlockTokens(node, ctx, option) {
|
||||
const startSectionNameStart = indexOf(ctx.code, (c) => Boolean(c.trim()), node.range[0] + 1);
|
||||
const startSectionNameEnd = indexOf(ctx.code, (c) => c === "}" || !c.trim(), startSectionNameStart + 1);
|
||||
ctx.addToken("MustacheKeyword", {
|
||||
start: startSectionNameStart,
|
||||
end: startSectionNameEnd,
|
||||
});
|
||||
if (option?.startOnly) {
|
||||
return;
|
||||
}
|
||||
const endSectionNameEnd = lastIndexOf(ctx.code, (c) => Boolean(c.trim()), node.range[1] - 2) + 1;
|
||||
const endSectionNameStart = lastIndexOf(ctx.code, (c) => c === "{" || c === "/" || !c.trim(), endSectionNameEnd - 1);
|
||||
ctx.addToken("MustacheKeyword", {
|
||||
start: endSectionNameStart,
|
||||
end: endSectionNameEnd,
|
||||
});
|
||||
}
|
||||
/** Generate Awaited like type code */
|
||||
function generateAwaitThenValueType(id) {
|
||||
return {
|
||||
script: `type ${id}<T> = T extends null | undefined
|
||||
? T
|
||||
: T extends { then(value: infer F): any }
|
||||
? F extends (value: infer V, ...args: any) => any
|
||||
? ${id}<V>
|
||||
: never
|
||||
: T;`,
|
||||
nodeType: "TSTypeAliasDeclaration",
|
||||
};
|
||||
}
|
||||
/** Checks whether the given name identifier is exists or not. */
|
||||
function hasIdentifierFor(name, node) {
|
||||
if (node.type === "Identifier") {
|
||||
return node.name === name;
|
||||
}
|
||||
if (node.type === "ObjectPattern") {
|
||||
return node.properties.some((property) => property.type === "Property"
|
||||
? hasIdentifierFor(name, property.value)
|
||||
: hasIdentifierFor(name, property));
|
||||
}
|
||||
if (node.type === "ArrayPattern") {
|
||||
return node.elements.some((element) => element && hasIdentifierFor(name, element));
|
||||
}
|
||||
if (node.type === "RestElement") {
|
||||
return hasIdentifierFor(name, node.argument);
|
||||
}
|
||||
if (node.type === "AssignmentPattern") {
|
||||
return hasIdentifierFor(name, node.left);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
23
node_modules/svelte-eslint-parser/lib/parser/converts/common.d.ts
generated
vendored
Normal file
23
node_modules/svelte-eslint-parser/lib/parser/converts/common.d.ts
generated
vendored
Normal file
@@ -0,0 +1,23 @@
|
||||
import type ESTree from "estree";
|
||||
/** indexOf */
|
||||
export declare function indexOf(str: string, search: (c: string, index: number) => boolean, start: number, end?: number): number;
|
||||
/** lastIndexOf */
|
||||
export declare function lastIndexOf(str: string, search: (c: string, index: number) => boolean, end: number): number;
|
||||
export declare function getWithLoc<N extends ESTree.Comment>(node: N): N & {
|
||||
start: number;
|
||||
end: number;
|
||||
};
|
||||
export declare function getWithLoc<N extends ESTree.Node | {
|
||||
start: number;
|
||||
end: number;
|
||||
}>(node: N): N & {
|
||||
start: number;
|
||||
end: number;
|
||||
};
|
||||
export declare function getWithLoc<N extends ESTree.Node | {
|
||||
start: number;
|
||||
end: number;
|
||||
}>(node: N | null | undefined): (N & {
|
||||
start: number;
|
||||
end: number;
|
||||
}) | null | undefined;
|
||||
25
node_modules/svelte-eslint-parser/lib/parser/converts/common.js
generated
vendored
Normal file
25
node_modules/svelte-eslint-parser/lib/parser/converts/common.js
generated
vendored
Normal file
@@ -0,0 +1,25 @@
|
||||
/** indexOf */
|
||||
export function indexOf(str, search, start, end) {
|
||||
const endIndex = end ?? str.length;
|
||||
for (let index = start; index < endIndex; index++) {
|
||||
const c = str[index];
|
||||
if (search(c, index)) {
|
||||
return index;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
/** lastIndexOf */
|
||||
export function lastIndexOf(str, search, end) {
|
||||
for (let index = end; index >= 0; index--) {
|
||||
const c = str[index];
|
||||
if (search(c, index)) {
|
||||
return index;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
/** Get node with location */
|
||||
export function getWithLoc(node) {
|
||||
return node;
|
||||
}
|
||||
6
node_modules/svelte-eslint-parser/lib/parser/converts/const.d.ts
generated
vendored
Normal file
6
node_modules/svelte-eslint-parser/lib/parser/converts/const.d.ts
generated
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
import type { SvelteConstTag } from "../../ast/index.js";
|
||||
import type { Context } from "../../context/index.js";
|
||||
import type * as SvAST from "../svelte-ast-types.js";
|
||||
import type * as Compiler from "../svelte-ast-types-for-v5.js";
|
||||
/** Convert for ConstTag */
|
||||
export declare function convertConstTag(node: SvAST.ConstTag | Compiler.ConstTag, parent: SvelteConstTag["parent"], ctx: Context): SvelteConstTag;
|
||||
31
node_modules/svelte-eslint-parser/lib/parser/converts/const.js
generated
vendored
Normal file
31
node_modules/svelte-eslint-parser/lib/parser/converts/const.js
generated
vendored
Normal file
@@ -0,0 +1,31 @@
|
||||
import { getDeclaratorFromConstTag } from "../compat.js";
|
||||
/** Convert for ConstTag */
|
||||
export function convertConstTag(node, parent, ctx) {
|
||||
const mustache = {
|
||||
type: "SvelteConstTag",
|
||||
declaration: null,
|
||||
declarations: [],
|
||||
parent,
|
||||
...ctx.getConvertLocation(node),
|
||||
};
|
||||
// Link declaration and declarations for backward compatibility.
|
||||
// TODO Remove in v2 and later.
|
||||
Object.defineProperty(mustache, "declaration", {
|
||||
get() {
|
||||
return mustache.declarations[0];
|
||||
},
|
||||
set(value) {
|
||||
mustache.declarations = [value];
|
||||
},
|
||||
enumerable: false,
|
||||
});
|
||||
ctx.scriptLet.addVariableDeclarator(getDeclaratorFromConstTag(node), mustache, (declaration) => {
|
||||
mustache.declarations = [declaration];
|
||||
});
|
||||
const atConstStart = ctx.code.indexOf("@const", mustache.range[0]);
|
||||
ctx.addToken("MustacheKeyword", {
|
||||
start: atConstStart,
|
||||
end: atConstStart + 6,
|
||||
});
|
||||
return mustache;
|
||||
}
|
||||
5
node_modules/svelte-eslint-parser/lib/parser/converts/declaration.d.ts
generated
vendored
Normal file
5
node_modules/svelte-eslint-parser/lib/parser/converts/declaration.d.ts
generated
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
import type { SvelteDeclarationTag, SvelteElement, SvelteElseBlockAlone, SvelteAwaitCatchBlock, SvelteAwaitPendingBlock, SvelteAwaitThenBlock, SvelteEachBlock, SvelteIfBlock, SvelteKeyBlock, SvelteProgram, SvelteSnippetBlock } from "../../ast/index.js";
|
||||
import type { Context } from "../../context/index.js";
|
||||
import type * as Compiler from "../svelte-ast-types-for-v5.js";
|
||||
/** Convert for DeclarationTag */
|
||||
export declare function convertDeclarationTag(node: Compiler.DeclarationTag, parent: SvelteProgram | SvelteElement | SvelteIfBlock | SvelteElseBlockAlone | SvelteEachBlock | SvelteAwaitPendingBlock | SvelteAwaitThenBlock | SvelteAwaitCatchBlock | SvelteKeyBlock | SvelteSnippetBlock, ctx: Context): SvelteDeclarationTag;
|
||||
13
node_modules/svelte-eslint-parser/lib/parser/converts/declaration.js
generated
vendored
Normal file
13
node_modules/svelte-eslint-parser/lib/parser/converts/declaration.js
generated
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
/** Convert for DeclarationTag */
|
||||
export function convertDeclarationTag(node, parent, ctx) {
|
||||
const declarationTag = {
|
||||
type: "SvelteDeclarationTag",
|
||||
declaration: null,
|
||||
parent,
|
||||
...ctx.getConvertLocation(node),
|
||||
};
|
||||
ctx.scriptLet.addDeclaration(node.declaration, declarationTag, (declaration) => {
|
||||
declarationTag.declaration = declaration;
|
||||
});
|
||||
return declarationTag;
|
||||
}
|
||||
19
node_modules/svelte-eslint-parser/lib/parser/converts/element.d.ts
generated
vendored
Normal file
19
node_modules/svelte-eslint-parser/lib/parser/converts/element.d.ts
generated
vendored
Normal file
@@ -0,0 +1,19 @@
|
||||
import type { SvelteAwaitBlock, SvelteAwaitCatchBlock, SvelteAwaitPendingBlock, SvelteAwaitThenBlock, SvelteConstTag, SvelteDeclarationTag, SvelteDebugTag, SvelteEachBlock, SvelteElement, SvelteElseBlockAlone, SvelteHTMLComment, SvelteIfBlock, SvelteIfBlockAlone, SvelteKeyBlock, SvelteMustacheTag, SvelteProgram, SvelteRenderTag, SvelteScriptElement, SvelteSnippetBlock, SvelteStyleElement, SvelteText } from "../../ast/index.js";
|
||||
import type { Context } from "../../context/index.js";
|
||||
import type * as SvAST from "../svelte-ast-types.js";
|
||||
import type * as Compiler from "../svelte-ast-types-for-v5.js";
|
||||
import type { Child } from "../compat.js";
|
||||
/** Convert for Fragment or Element or ... */
|
||||
export declare function convertChildren(fragment: {
|
||||
children?: SvAST.TemplateNode[];
|
||||
} | Compiler.Fragment | {
|
||||
nodes: (Child | SvAST.TemplateNode)[];
|
||||
}, parent: SvelteProgram | SvelteElement | SvelteIfBlock | SvelteElseBlockAlone | SvelteEachBlock | SvelteAwaitPendingBlock | SvelteAwaitThenBlock | SvelteAwaitCatchBlock | SvelteKeyBlock | SvelteSnippetBlock, ctx: Context): IterableIterator<SvelteText | SvelteElement | SvelteMustacheTag | SvelteDebugTag | SvelteConstTag | SvelteDeclarationTag | SvelteRenderTag | SvelteIfBlockAlone | SvelteEachBlock | SvelteAwaitBlock | SvelteKeyBlock | SvelteSnippetBlock | SvelteHTMLComment>;
|
||||
/** Extract element tag and tokens */
|
||||
export declare function extractElementTags<E extends SvelteScriptElement | SvelteElement | SvelteStyleElement>(element: E, ctx: Context, options: {
|
||||
buildNameNode: (openTokenRange: {
|
||||
start: number;
|
||||
end: number;
|
||||
}) => E["name"];
|
||||
extractAttribute?: boolean;
|
||||
}): void;
|
||||
671
node_modules/svelte-eslint-parser/lib/parser/converts/element.js
generated
vendored
Normal file
671
node_modules/svelte-eslint-parser/lib/parser/converts/element.js
generated
vendored
Normal file
@@ -0,0 +1,671 @@
|
||||
import { convertAwaitBlock, convertEachBlock, convertIfBlock, convertKeyBlock, convertSnippetBlock, } from "./block.js";
|
||||
import { getWithLoc, indexOf } from "./common.js";
|
||||
import { convertMustacheTag, convertDebugTag, convertRawMustacheTag, } from "./mustache.js";
|
||||
import { convertText } from "./text.js";
|
||||
import { convertAttributes } from "./attr.js";
|
||||
import { convertConstTag } from "./const.js";
|
||||
import { convertDeclarationTag } from "./declaration.js";
|
||||
import { sortNodes } from "../sort.js";
|
||||
import { ParseError } from "../../index.js";
|
||||
import { convertRenderTag } from "./render.js";
|
||||
import { getChildren, getFragment } from "../compat.js";
|
||||
/** Convert for Fragment or Element or ... */
|
||||
export function* convertChildren(fragment, parent, ctx) {
|
||||
const children = getChildren(fragment);
|
||||
if (!children)
|
||||
return;
|
||||
for (const child of children) {
|
||||
if (child.type === "Comment") {
|
||||
yield convertComment(child, parent, ctx);
|
||||
continue;
|
||||
}
|
||||
if (child.type === "Text") {
|
||||
if (!child.data && child.start === child.end) {
|
||||
continue;
|
||||
}
|
||||
yield convertText(child, parent, ctx);
|
||||
continue;
|
||||
}
|
||||
if (child.type === "RegularElement") {
|
||||
yield convertHTMLElement(child, parent, ctx);
|
||||
continue;
|
||||
}
|
||||
if (child.type === "Element") {
|
||||
if (child.name.includes(":")) {
|
||||
yield convertSpecialElement(child, parent, ctx);
|
||||
}
|
||||
else {
|
||||
yield convertHTMLElement(child, parent, ctx);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (child.type === "Component") {
|
||||
yield convertComponentElement(child, parent, ctx);
|
||||
continue;
|
||||
}
|
||||
if (child.type === "InlineComponent") {
|
||||
if (child.name.includes(":")) {
|
||||
yield convertSpecialElement(child, parent, ctx);
|
||||
}
|
||||
else {
|
||||
yield convertComponentElement(child, parent, ctx);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (child.type === "SvelteComponent" ||
|
||||
child.type === "SvelteElement" ||
|
||||
child.type === "SvelteSelf") {
|
||||
yield convertSpecialElement(child, parent, ctx);
|
||||
continue;
|
||||
}
|
||||
if (child.type === "SlotElement" || child.type === "Slot") {
|
||||
yield convertSlotElement(child, parent, ctx);
|
||||
continue;
|
||||
}
|
||||
if (child.type === "ExpressionTag" || child.type === "MustacheTag") {
|
||||
yield convertMustacheTag(child, parent, null, ctx);
|
||||
continue;
|
||||
}
|
||||
if (child.type === "HtmlTag" || child.type === "RawMustacheTag") {
|
||||
yield convertRawMustacheTag(child, parent, ctx);
|
||||
continue;
|
||||
}
|
||||
if (child.type === "IfBlock") {
|
||||
// {#if expr} {/if}
|
||||
yield convertIfBlock(child, parent, ctx);
|
||||
continue;
|
||||
}
|
||||
if (child.type === "EachBlock") {
|
||||
// {#each expr as item, index (key)} {/each}
|
||||
yield convertEachBlock(child, parent, ctx);
|
||||
continue;
|
||||
}
|
||||
if (child.type === "AwaitBlock") {
|
||||
// {#await promise} {:then number} {:catch error} {/await}
|
||||
yield convertAwaitBlock(child, parent, ctx);
|
||||
continue;
|
||||
}
|
||||
if (child.type === "KeyBlock") {
|
||||
// {#key expression}...{/key}
|
||||
yield convertKeyBlock(child, parent, ctx);
|
||||
continue;
|
||||
}
|
||||
if (child.type === "SnippetBlock") {
|
||||
// {#snippet x(args)}...{/snippet}
|
||||
yield convertSnippetBlock(child, parent, ctx);
|
||||
continue;
|
||||
}
|
||||
if (child.type === "SvelteWindow" || child.type === "Window") {
|
||||
yield convertWindowElement(child, parent, ctx);
|
||||
continue;
|
||||
}
|
||||
if (child.type === "SvelteBody" || child.type === "Body") {
|
||||
yield convertBodyElement(child, parent, ctx);
|
||||
continue;
|
||||
}
|
||||
if (child.type === "SvelteHead" || child.type === "Head") {
|
||||
yield convertHeadElement(child, parent, ctx);
|
||||
continue;
|
||||
}
|
||||
if (child.type === "TitleElement" || child.type === "Title") {
|
||||
yield convertTitleElement(child, parent, ctx);
|
||||
continue;
|
||||
}
|
||||
if (child.type === "SvelteOptions" || child.type === "Options") {
|
||||
yield convertOptionsElement(child, parent, ctx);
|
||||
continue;
|
||||
}
|
||||
if (child.type === "SvelteFragment" || child.type === "SlotTemplate") {
|
||||
yield convertSlotTemplateElement(child, parent, ctx);
|
||||
continue;
|
||||
}
|
||||
if (child.type === "DebugTag") {
|
||||
yield convertDebugTag(child, parent, ctx);
|
||||
continue;
|
||||
}
|
||||
if (child.type === "ConstTag") {
|
||||
yield convertConstTag(child, parent, ctx);
|
||||
continue;
|
||||
}
|
||||
if (child.type === "DeclarationTag") {
|
||||
yield convertDeclarationTag(child, parent, ctx);
|
||||
continue;
|
||||
}
|
||||
if (child.type === "RenderTag") {
|
||||
yield convertRenderTag(child, parent, ctx);
|
||||
continue;
|
||||
}
|
||||
if (child.type === "SvelteDocument" || child.type === "Document") {
|
||||
yield convertDocumentElement(child, parent, ctx);
|
||||
continue;
|
||||
}
|
||||
if (child.type === "SvelteBoundary") {
|
||||
yield convertSvelteBoundaryElement(child, parent, ctx);
|
||||
continue;
|
||||
}
|
||||
throw new Error(`Unknown type:${child.type}`);
|
||||
}
|
||||
}
|
||||
/** Extract `let:` directives. */
|
||||
function extractLetDirectives(fragment) {
|
||||
const letDirectives = [];
|
||||
const attributes = [];
|
||||
for (const attr of fragment.attributes) {
|
||||
if (attr.type === "LetDirective" || attr.type === "Let") {
|
||||
letDirectives.push(attr);
|
||||
}
|
||||
else {
|
||||
attributes.push(attr);
|
||||
}
|
||||
}
|
||||
return { letDirectives, attributes };
|
||||
}
|
||||
/** Check if children needs a scope. */
|
||||
function needScopeByChildren(fragment) {
|
||||
const children = getChildren(fragment);
|
||||
if (!children)
|
||||
return false;
|
||||
for (const child of children) {
|
||||
if (child.type === "ConstTag") {
|
||||
return true;
|
||||
}
|
||||
if (child.type === "DeclarationTag") {
|
||||
return true;
|
||||
}
|
||||
if (child.type === "SnippetBlock") {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
/** Convert for HTML Comment */
|
||||
function convertComment(node, parent, ctx) {
|
||||
const comment = {
|
||||
type: "SvelteHTMLComment",
|
||||
value: node.data,
|
||||
parent,
|
||||
...ctx.getConvertLocation(node),
|
||||
};
|
||||
ctx.addToken("HTMLComment", node);
|
||||
return comment;
|
||||
}
|
||||
/** Convert for HTMLElement */
|
||||
function convertHTMLElement(node, parent, ctx) {
|
||||
const locs = ctx.getConvertLocation(node);
|
||||
const element = {
|
||||
type: "SvelteElement",
|
||||
kind: "html",
|
||||
name: null,
|
||||
startTag: {
|
||||
type: "SvelteStartTag",
|
||||
attributes: [],
|
||||
selfClosing: false,
|
||||
parent: null,
|
||||
range: [locs.range[0], null],
|
||||
loc: {
|
||||
start: {
|
||||
line: locs.loc.start.line,
|
||||
column: locs.loc.start.column,
|
||||
},
|
||||
end: null,
|
||||
},
|
||||
},
|
||||
children: [],
|
||||
endTag: null,
|
||||
parent,
|
||||
...locs,
|
||||
};
|
||||
ctx.elements.set(element, node);
|
||||
element.startTag.parent = element;
|
||||
const elementName = node.name;
|
||||
const { letDirectives, attributes } = extractLetDirectives(node);
|
||||
const letParams = [];
|
||||
if (letDirectives.length) {
|
||||
ctx.letDirCollections.beginExtract();
|
||||
element.startTag.attributes.push(...convertAttributes(letDirectives, element.startTag, ctx));
|
||||
letParams.push(...ctx.letDirCollections.extract().getLetParams());
|
||||
}
|
||||
const fragment = getFragment(node);
|
||||
if (!letParams.length && !needScopeByChildren(fragment)) {
|
||||
element.startTag.attributes.push(...convertAttributes(attributes, element.startTag, ctx));
|
||||
element.children.push(...convertChildren(fragment, element, ctx));
|
||||
}
|
||||
else {
|
||||
ctx.scriptLet.nestBlock(element, letParams);
|
||||
element.startTag.attributes.push(...convertAttributes(attributes, element.startTag, ctx));
|
||||
sortNodes(element.startTag.attributes);
|
||||
element.children.push(...convertChildren(fragment, element, ctx));
|
||||
ctx.scriptLet.closeScope();
|
||||
}
|
||||
extractElementTags(element, ctx, {
|
||||
buildNameNode: (openTokenRange) => {
|
||||
ctx.addToken("HTMLIdentifier", openTokenRange);
|
||||
const name = {
|
||||
type: "SvelteName",
|
||||
name: elementName,
|
||||
parent: element,
|
||||
...ctx.getConvertLocation(openTokenRange),
|
||||
};
|
||||
return name;
|
||||
},
|
||||
});
|
||||
if (element.name.name === "script" ||
|
||||
element.name.name === "style" ||
|
||||
(element.name.name === "template" && ctx.findBlock(element))) {
|
||||
// Restore the block-like element.
|
||||
for (const child of element.children) {
|
||||
if (child.type === "SvelteText") {
|
||||
child.value = ctx.code.slice(...child.range);
|
||||
}
|
||||
}
|
||||
if (element.name.name === "script") {
|
||||
ctx.stripScriptCode(element.startTag.range[1], element.endTag?.range[0] ?? element.range[1]);
|
||||
}
|
||||
}
|
||||
if (element.startTag.selfClosing && element.name.name.endsWith("-")) {
|
||||
// Restore the self-closing block.
|
||||
const selfClosingBlock = /^[a-z]-+$/iu.test(element.name.name) &&
|
||||
ctx.findSelfClosingBlock(element);
|
||||
if (selfClosingBlock) {
|
||||
element.name.name = selfClosingBlock.originalTag;
|
||||
}
|
||||
}
|
||||
return element;
|
||||
}
|
||||
/** Convert for Special element. e.g. <svelte:self> */
|
||||
function convertSpecialElement(node, parent, ctx) {
|
||||
const locs = ctx.getConvertLocation(node);
|
||||
const element = {
|
||||
type: "SvelteElement",
|
||||
kind: "special",
|
||||
name: null,
|
||||
startTag: {
|
||||
type: "SvelteStartTag",
|
||||
attributes: [],
|
||||
selfClosing: false,
|
||||
parent: null,
|
||||
range: [locs.range[0], null],
|
||||
loc: {
|
||||
start: {
|
||||
line: locs.loc.start.line,
|
||||
column: locs.loc.start.column,
|
||||
},
|
||||
end: null,
|
||||
},
|
||||
},
|
||||
children: [],
|
||||
endTag: null,
|
||||
parent,
|
||||
...locs,
|
||||
};
|
||||
ctx.elements.set(element, node);
|
||||
element.startTag.parent = element;
|
||||
const elementName = node.name;
|
||||
const { letDirectives, attributes } = extractLetDirectives(node);
|
||||
const letParams = [];
|
||||
if (letDirectives.length) {
|
||||
ctx.letDirCollections.beginExtract();
|
||||
element.startTag.attributes.push(...convertAttributes(letDirectives, element.startTag, ctx));
|
||||
letParams.push(...ctx.letDirCollections.extract().getLetParams());
|
||||
}
|
||||
const fragment = getFragment(node);
|
||||
if (!letParams.length && !needScopeByChildren(fragment)) {
|
||||
element.startTag.attributes.push(...convertAttributes(attributes, element.startTag, ctx));
|
||||
element.children.push(...convertChildren(fragment, element, ctx));
|
||||
}
|
||||
else {
|
||||
ctx.scriptLet.nestBlock(element, letParams);
|
||||
element.startTag.attributes.push(...convertAttributes(attributes, element.startTag, ctx));
|
||||
sortNodes(element.startTag.attributes);
|
||||
element.children.push(...convertChildren(fragment, element, ctx));
|
||||
ctx.scriptLet.closeScope();
|
||||
}
|
||||
const thisExpression = (node.type === "SvelteComponent" && node.expression) ||
|
||||
(node.type === "SvelteElement" && node.tag) ||
|
||||
(node.type === "InlineComponent" &&
|
||||
elementName === "svelte:component" &&
|
||||
node.expression) ||
|
||||
(node.type === "Element" && elementName === "svelte:element" && node.tag);
|
||||
if (thisExpression) {
|
||||
processThisAttribute(node, thisExpression, element, ctx);
|
||||
}
|
||||
extractElementTags(element, ctx, {
|
||||
buildNameNode: (openTokenRange) => {
|
||||
ctx.addToken("HTMLIdentifier", openTokenRange);
|
||||
const name = {
|
||||
type: "SvelteName",
|
||||
name: elementName,
|
||||
parent: element,
|
||||
...ctx.getConvertLocation(openTokenRange),
|
||||
};
|
||||
return name;
|
||||
},
|
||||
});
|
||||
return element;
|
||||
}
|
||||
/** process `this=` */
|
||||
function processThisAttribute(node, thisValue, element, ctx) {
|
||||
const startIndex = findStartIndexOfThis(node, ctx);
|
||||
const eqIndex = ctx.code.indexOf("=", startIndex + 4 /* t,h,i,s */);
|
||||
let thisNode;
|
||||
if (typeof thisValue === "string") {
|
||||
// Svelte v4
|
||||
// this="..."
|
||||
thisNode = createSvelteAttribute(startIndex, eqIndex, thisValue);
|
||||
}
|
||||
else {
|
||||
// this={...}
|
||||
const valueStartIndex = indexOf(ctx.code, (c) => Boolean(c.trim()), eqIndex + 1);
|
||||
if (thisValue.type === "Literal" &&
|
||||
typeof thisValue.value === "string" &&
|
||||
ctx.code[valueStartIndex] !== "{") {
|
||||
thisNode = createSvelteAttribute(startIndex, eqIndex, thisValue.value);
|
||||
}
|
||||
else {
|
||||
thisNode = createSvelteSpecialDirective(startIndex, eqIndex, thisValue);
|
||||
}
|
||||
}
|
||||
const targetIndex = element.startTag.attributes.findIndex((attr) => thisNode.range[1] <= attr.range[0]);
|
||||
if (targetIndex === -1) {
|
||||
element.startTag.attributes.push(thisNode);
|
||||
}
|
||||
else {
|
||||
element.startTag.attributes.splice(targetIndex, 0, thisNode);
|
||||
}
|
||||
/** Create SvelteAttribute */
|
||||
function createSvelteAttribute(startIndex, eqIndex, thisValue) {
|
||||
const valueStartIndex = indexOf(ctx.code, (c) => Boolean(c.trim()), eqIndex + 1);
|
||||
const quote = ctx.code.startsWith(thisValue, valueStartIndex)
|
||||
? null
|
||||
: ctx.code[valueStartIndex];
|
||||
const literalStartIndex = quote
|
||||
? valueStartIndex + quote.length
|
||||
: valueStartIndex;
|
||||
const literalEndIndex = literalStartIndex + thisValue.length;
|
||||
const endIndex = quote ? literalEndIndex + quote.length : literalEndIndex;
|
||||
const thisAttr = {
|
||||
type: "SvelteAttribute",
|
||||
key: null,
|
||||
boolean: false,
|
||||
value: [],
|
||||
parent: element.startTag,
|
||||
...ctx.getConvertLocation({ start: startIndex, end: endIndex }),
|
||||
};
|
||||
thisAttr.key = {
|
||||
type: "SvelteName",
|
||||
name: "this",
|
||||
parent: thisAttr,
|
||||
...ctx.getConvertLocation({ start: startIndex, end: eqIndex }),
|
||||
};
|
||||
thisAttr.value.push({
|
||||
type: "SvelteLiteral",
|
||||
value: thisValue,
|
||||
parent: thisAttr,
|
||||
...ctx.getConvertLocation({
|
||||
start: literalStartIndex,
|
||||
end: literalEndIndex,
|
||||
}),
|
||||
});
|
||||
// this
|
||||
ctx.addToken("HTMLIdentifier", {
|
||||
start: startIndex,
|
||||
end: startIndex + 4,
|
||||
});
|
||||
// =
|
||||
ctx.addToken("Punctuator", {
|
||||
start: eqIndex,
|
||||
end: eqIndex + 1,
|
||||
});
|
||||
if (quote) {
|
||||
// "
|
||||
ctx.addToken("Punctuator", {
|
||||
start: valueStartIndex,
|
||||
end: literalStartIndex,
|
||||
});
|
||||
}
|
||||
ctx.addToken("HTMLText", {
|
||||
start: literalStartIndex,
|
||||
end: literalEndIndex,
|
||||
});
|
||||
if (quote) {
|
||||
// "
|
||||
ctx.addToken("Punctuator", {
|
||||
start: literalEndIndex,
|
||||
end: endIndex,
|
||||
});
|
||||
}
|
||||
return thisAttr;
|
||||
}
|
||||
/** Create SvelteSpecialDirective */
|
||||
function createSvelteSpecialDirective(startIndex, eqIndex, expression) {
|
||||
const closeIndex = ctx.code.indexOf("}", getWithLoc(expression).end);
|
||||
const endIndex = indexOf(ctx.code, (c) => c === ">" || !c.trim(), closeIndex);
|
||||
const thisDir = {
|
||||
type: "SvelteSpecialDirective",
|
||||
kind: "this",
|
||||
key: null,
|
||||
expression: null,
|
||||
parent: element.startTag,
|
||||
...ctx.getConvertLocation({ start: startIndex, end: endIndex }),
|
||||
};
|
||||
thisDir.key = {
|
||||
type: "SvelteSpecialDirectiveKey",
|
||||
parent: thisDir,
|
||||
...ctx.getConvertLocation({ start: startIndex, end: eqIndex }),
|
||||
};
|
||||
// this
|
||||
ctx.addToken("HTMLIdentifier", {
|
||||
start: startIndex,
|
||||
end: startIndex + 4,
|
||||
});
|
||||
// =
|
||||
ctx.addToken("Punctuator", {
|
||||
start: eqIndex,
|
||||
end: eqIndex + 1,
|
||||
});
|
||||
ctx.scriptLet.addExpression(expression, thisDir, null, (es) => {
|
||||
thisDir.expression = es;
|
||||
});
|
||||
return thisDir;
|
||||
}
|
||||
}
|
||||
/** Find the start index of `this` */
|
||||
function findStartIndexOfThis(node, ctx) {
|
||||
// Get the end index of `svelte:element`
|
||||
const startIndex = ctx.code.indexOf(node.name, node.start) + node.name.length;
|
||||
const sortedAttrs = [...node.attributes].sort((a, b) => a.start - b.start);
|
||||
// Find the start index of `this` from the end index of `svelte:element`.
|
||||
// However, it only seeks to the start index of the first attribute (or the end index of element node).
|
||||
let thisIndex = indexOf(ctx.code, (_c, index) => ctx.code.startsWith("this", index), startIndex, sortedAttrs[0]?.start ?? node.end);
|
||||
while (thisIndex < 0) {
|
||||
if (sortedAttrs.length === 0)
|
||||
throw new ParseError("Cannot resolved `this` attribute.", thisIndex, ctx);
|
||||
// Step3: Find the start index of `this` from the end index of attribute.
|
||||
// However, it only seeks to the start index of the first attribute (or the end index of element node).
|
||||
const nextStartIndex = sortedAttrs.shift().end;
|
||||
thisIndex = indexOf(ctx.code, (_c, index) => ctx.code.startsWith("this", index), nextStartIndex, sortedAttrs[0]?.start ?? node.end);
|
||||
}
|
||||
return thisIndex;
|
||||
}
|
||||
/** Convert for ComponentElement */
|
||||
function convertComponentElement(node, parent, ctx) {
|
||||
const locs = ctx.getConvertLocation(node);
|
||||
const element = {
|
||||
type: "SvelteElement",
|
||||
kind: "component",
|
||||
name: null,
|
||||
startTag: {
|
||||
type: "SvelteStartTag",
|
||||
attributes: [],
|
||||
selfClosing: false,
|
||||
parent: null,
|
||||
range: [locs.range[0], null],
|
||||
loc: {
|
||||
start: {
|
||||
line: locs.loc.start.line,
|
||||
column: locs.loc.start.column,
|
||||
},
|
||||
end: null,
|
||||
},
|
||||
},
|
||||
children: [],
|
||||
endTag: null,
|
||||
parent,
|
||||
...locs,
|
||||
};
|
||||
ctx.elements.set(element, node);
|
||||
element.startTag.parent = element;
|
||||
const elementName = node.name;
|
||||
const { letDirectives, attributes } = extractLetDirectives(node);
|
||||
const letParams = [];
|
||||
if (letDirectives.length) {
|
||||
ctx.letDirCollections.beginExtract();
|
||||
element.startTag.attributes.push(...convertAttributes(letDirectives, element.startTag, ctx));
|
||||
letParams.push(...ctx.letDirCollections.extract().getLetParams());
|
||||
}
|
||||
const fragment = getFragment(node);
|
||||
if (!letParams.length && !needScopeByChildren(fragment)) {
|
||||
element.startTag.attributes.push(...convertAttributes(attributes, element.startTag, ctx));
|
||||
element.children.push(...convertChildren(fragment, element, ctx));
|
||||
}
|
||||
else {
|
||||
ctx.scriptLet.nestBlock(element, letParams);
|
||||
element.startTag.attributes.push(...convertAttributes(attributes, element.startTag, ctx));
|
||||
sortNodes(element.startTag.attributes);
|
||||
element.children.push(...convertChildren(fragment, element, ctx));
|
||||
ctx.scriptLet.closeScope();
|
||||
}
|
||||
extractElementTags(element, ctx, {
|
||||
buildNameNode: (openTokenRange) => {
|
||||
const chains = elementName.split(".");
|
||||
const id = chains.shift();
|
||||
const idRange = {
|
||||
start: openTokenRange.start,
|
||||
end: openTokenRange.start + id.length,
|
||||
};
|
||||
// ctx.addToken("Identifier", idRange)
|
||||
const identifier = {
|
||||
type: "Identifier",
|
||||
name: id,
|
||||
// @ts-expect-error -- ignore
|
||||
parent: element,
|
||||
...ctx.getConvertLocation(idRange),
|
||||
};
|
||||
let object = identifier;
|
||||
// eslint-disable-next-line func-style -- var
|
||||
let esCallback = (es) => {
|
||||
element.name = es;
|
||||
};
|
||||
let start = idRange.end + 1;
|
||||
for (const name of chains) {
|
||||
const range = { start, end: start + name.length };
|
||||
ctx.addToken("HTMLIdentifier", range);
|
||||
const mem = {
|
||||
type: "SvelteMemberExpressionName",
|
||||
object,
|
||||
property: {
|
||||
type: "SvelteName",
|
||||
name,
|
||||
parent: null,
|
||||
...ctx.getConvertLocation(range),
|
||||
},
|
||||
parent: element,
|
||||
...ctx.getConvertLocation({
|
||||
start: openTokenRange.start,
|
||||
end: range.end,
|
||||
}),
|
||||
};
|
||||
mem.property.parent = mem;
|
||||
object.parent = mem;
|
||||
object = mem;
|
||||
start = range.end + 1;
|
||||
if (mem.object === identifier) {
|
||||
esCallback = (es) => {
|
||||
mem.object = es;
|
||||
};
|
||||
}
|
||||
}
|
||||
ctx.scriptLet.addExpression(identifier, identifier.parent, null, esCallback);
|
||||
return object;
|
||||
},
|
||||
});
|
||||
return element;
|
||||
}
|
||||
/** Convert for Slot */
|
||||
function convertSlotElement(node, parent, ctx) {
|
||||
// Slot translates to SvelteHTMLElement.
|
||||
const element = convertHTMLElement(node, parent, ctx);
|
||||
ctx.slots.add(element);
|
||||
return element;
|
||||
}
|
||||
/** Convert for window element. e.g. <svelte:window> */
|
||||
function convertWindowElement(node, parent, ctx) {
|
||||
return convertSpecialElement(node, parent, ctx);
|
||||
}
|
||||
/** Convert for document element. e.g. <svelte:document> */
|
||||
function convertDocumentElement(node, parent, ctx) {
|
||||
return convertSpecialElement(node, parent, ctx);
|
||||
}
|
||||
/** Convert for body element. e.g. <svelte:body> */
|
||||
function convertBodyElement(node, parent, ctx) {
|
||||
return convertSpecialElement(node, parent, ctx);
|
||||
}
|
||||
/** Convert for head element. e.g. <svelte:head> */
|
||||
function convertHeadElement(node, parent, ctx) {
|
||||
return convertSpecialElement(node, parent, ctx);
|
||||
}
|
||||
/** Convert for title element. e.g. <title> */
|
||||
function convertTitleElement(node, parent, ctx) {
|
||||
return convertHTMLElement(node, parent, ctx);
|
||||
}
|
||||
/** Convert for options element. e.g. <svelte:options> */
|
||||
function convertOptionsElement(node, parent, ctx) {
|
||||
return convertSpecialElement(node, parent, ctx);
|
||||
}
|
||||
/** Convert for <svelte:fragment> element. */
|
||||
function convertSlotTemplateElement(node, parent, ctx) {
|
||||
return convertSpecialElement(node, parent, ctx);
|
||||
}
|
||||
/** Convert for <svelte:boundary> element. */
|
||||
function convertSvelteBoundaryElement(node, parent, ctx) {
|
||||
return convertSpecialElement(node, parent, ctx);
|
||||
}
|
||||
/** Extract element tag and tokens */
|
||||
export function extractElementTags(element, ctx, options) {
|
||||
const startTagNameEnd = indexOf(ctx.code, (c) => c === "/" || c === ">" || !c.trim(), element.range[0] + 1);
|
||||
const openTokenRange = {
|
||||
start: element.range[0] + 1,
|
||||
end: startTagNameEnd,
|
||||
};
|
||||
element.name = options.buildNameNode(openTokenRange);
|
||||
const startTagEnd = ctx.code.indexOf(">", element.startTag.attributes[element.startTag.attributes.length - 1]
|
||||
?.range[1] ?? openTokenRange.end) + 1;
|
||||
element.startTag.range[1] = startTagEnd;
|
||||
element.startTag.loc.end = ctx.getLocFromIndex(startTagEnd);
|
||||
if (ctx.code[element.range[1] - 1] !== ">") {
|
||||
// Have not end tag
|
||||
return;
|
||||
}
|
||||
if (ctx.code[element.range[1] - 2] === "/") {
|
||||
// self close
|
||||
element.startTag.selfClosing = true;
|
||||
return;
|
||||
}
|
||||
const endTagOpen = ctx.code.lastIndexOf("<", element.range[1] - 1);
|
||||
if (endTagOpen <= startTagEnd - 1) {
|
||||
// void element
|
||||
return;
|
||||
}
|
||||
const endTagNameStart = endTagOpen + 2;
|
||||
const endTagNameEnd = indexOf(ctx.code, (c) => c === ">" || !c.trim(), endTagNameStart);
|
||||
const endTagClose = ctx.code.indexOf(">", endTagNameEnd);
|
||||
element.endTag = {
|
||||
type: "SvelteEndTag",
|
||||
parent: element,
|
||||
...ctx.getConvertLocation({ start: endTagOpen, end: endTagClose + 1 }),
|
||||
};
|
||||
ctx.addToken("HTMLIdentifier", {
|
||||
start: endTagNameStart,
|
||||
end: endTagNameEnd,
|
||||
});
|
||||
}
|
||||
1
node_modules/svelte-eslint-parser/lib/parser/converts/index.d.ts
generated
vendored
Normal file
1
node_modules/svelte-eslint-parser/lib/parser/converts/index.d.ts
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
export { convertSvelteRoot } from "./root.js";
|
||||
1
node_modules/svelte-eslint-parser/lib/parser/converts/index.js
generated
vendored
Normal file
1
node_modules/svelte-eslint-parser/lib/parser/converts/index.js
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
export { convertSvelteRoot } from "./root.js";
|
||||
10
node_modules/svelte-eslint-parser/lib/parser/converts/mustache.d.ts
generated
vendored
Normal file
10
node_modules/svelte-eslint-parser/lib/parser/converts/mustache.d.ts
generated
vendored
Normal file
@@ -0,0 +1,10 @@
|
||||
import type { SvelteDebugTag, SvelteMustacheTag, SvelteMustacheTagRaw, SvelteMustacheTagText } from "../../ast/index.js";
|
||||
import type { Context } from "../../context/index.js";
|
||||
import type * as SvAST from "../svelte-ast-types.js";
|
||||
import type * as Compiler from "../svelte-ast-types-for-v5.js";
|
||||
/** Convert for MustacheTag */
|
||||
export declare function convertMustacheTag(node: SvAST.MustacheTag | Compiler.ExpressionTag, parent: SvelteMustacheTag["parent"], typing: string | null, ctx: Context): SvelteMustacheTagText;
|
||||
/** Convert for MustacheTag */
|
||||
export declare function convertRawMustacheTag(node: SvAST.RawMustacheTag | Compiler.HtmlTag, parent: SvelteMustacheTagRaw["parent"], ctx: Context): SvelteMustacheTagRaw;
|
||||
/** Convert for DebugTag */
|
||||
export declare function convertDebugTag(node: SvAST.DebugTag, parent: SvelteDebugTag["parent"], ctx: Context): SvelteDebugTag;
|
||||
49
node_modules/svelte-eslint-parser/lib/parser/converts/mustache.js
generated
vendored
Normal file
49
node_modules/svelte-eslint-parser/lib/parser/converts/mustache.js
generated
vendored
Normal file
@@ -0,0 +1,49 @@
|
||||
import { hasTypeInfo } from "../../utils/index.js";
|
||||
/** Convert for MustacheTag */
|
||||
export function convertMustacheTag(node, parent, typing, ctx) {
|
||||
return convertMustacheTag0(node, "text", parent, typing, ctx);
|
||||
}
|
||||
/** Convert for MustacheTag */
|
||||
export function convertRawMustacheTag(node, parent, ctx) {
|
||||
const mustache = convertMustacheTag0(node, "raw", parent, null, ctx);
|
||||
const atHtmlStart = ctx.code.indexOf("@html", mustache.range[0]);
|
||||
ctx.addToken("MustacheKeyword", {
|
||||
start: atHtmlStart,
|
||||
end: atHtmlStart + 5,
|
||||
});
|
||||
return mustache;
|
||||
}
|
||||
/** Convert for DebugTag */
|
||||
export function convertDebugTag(node, parent, ctx) {
|
||||
const mustache = {
|
||||
type: "SvelteDebugTag",
|
||||
identifiers: [],
|
||||
parent,
|
||||
...ctx.getConvertLocation(node),
|
||||
};
|
||||
for (const id of node.identifiers) {
|
||||
ctx.scriptLet.addExpression(id, mustache, null, (es) => {
|
||||
mustache.identifiers.push(es);
|
||||
});
|
||||
}
|
||||
const atDebugStart = ctx.code.indexOf("@debug", mustache.range[0]);
|
||||
ctx.addToken("MustacheKeyword", {
|
||||
start: atDebugStart,
|
||||
end: atDebugStart + 6,
|
||||
});
|
||||
return mustache;
|
||||
}
|
||||
/** Convert to MustacheTag */
|
||||
function convertMustacheTag0(node, kind, parent, typing, ctx) {
|
||||
const mustache = {
|
||||
type: "SvelteMustacheTag",
|
||||
kind,
|
||||
expression: null,
|
||||
parent,
|
||||
...ctx.getConvertLocation(node),
|
||||
};
|
||||
ctx.scriptLet.addExpression(node.expression, mustache, hasTypeInfo(node.expression) ? null : typing, (es) => {
|
||||
mustache.expression = es;
|
||||
});
|
||||
return mustache;
|
||||
}
|
||||
5
node_modules/svelte-eslint-parser/lib/parser/converts/render.d.ts
generated
vendored
Normal file
5
node_modules/svelte-eslint-parser/lib/parser/converts/render.d.ts
generated
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
import type { SvelteRenderTag } from "../../ast/index.js";
|
||||
import type { Context } from "../../context/index.js";
|
||||
import type * as Compiler from "../svelte-ast-types-for-v5.js";
|
||||
/** Convert for RenderTag */
|
||||
export declare function convertRenderTag(node: Compiler.RenderTag, parent: SvelteRenderTag["parent"], ctx: Context): SvelteRenderTag;
|
||||
21
node_modules/svelte-eslint-parser/lib/parser/converts/render.js
generated
vendored
Normal file
21
node_modules/svelte-eslint-parser/lib/parser/converts/render.js
generated
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
import { getWithLoc } from "./common.js";
|
||||
/** Convert for RenderTag */
|
||||
export function convertRenderTag(node, parent, ctx) {
|
||||
const mustache = {
|
||||
type: "SvelteRenderTag",
|
||||
expression: null,
|
||||
parent,
|
||||
...ctx.getConvertLocation(node),
|
||||
};
|
||||
const callRange = getWithLoc(node.expression);
|
||||
ctx.scriptLet.addExpressionFromRange([callRange.start, callRange.end], mustache, null, (expression) => {
|
||||
mustache.expression = expression;
|
||||
mustache.expression.parent = mustache;
|
||||
});
|
||||
const atRenderStart = ctx.code.indexOf("@render", mustache.range[0]);
|
||||
ctx.addToken("MustacheKeyword", {
|
||||
start: atRenderStart,
|
||||
end: atRenderStart + 7,
|
||||
});
|
||||
return mustache;
|
||||
}
|
||||
8
node_modules/svelte-eslint-parser/lib/parser/converts/root.d.ts
generated
vendored
Normal file
8
node_modules/svelte-eslint-parser/lib/parser/converts/root.d.ts
generated
vendored
Normal file
@@ -0,0 +1,8 @@
|
||||
import type * as SvAST from "../svelte-ast-types.js";
|
||||
import type * as Compiler from "../svelte-ast-types-for-v5.js";
|
||||
import type { SvelteProgram } from "../../ast/index.js";
|
||||
import type { Context } from "../../context/index.js";
|
||||
/**
|
||||
* Convert root
|
||||
*/
|
||||
export declare function convertSvelteRoot(svelteAst: Compiler.Root | SvAST.AstLegacy, ctx: Context): SvelteProgram;
|
||||
302
node_modules/svelte-eslint-parser/lib/parser/converts/root.js
generated
vendored
Normal file
302
node_modules/svelte-eslint-parser/lib/parser/converts/root.js
generated
vendored
Normal file
@@ -0,0 +1,302 @@
|
||||
import { convertChildren, extractElementTags } from "./element.js";
|
||||
import { convertAttributes } from "./attr.js";
|
||||
import { parseScriptWithoutAnalyzeScope } from "../script.js";
|
||||
import { fixLocations } from "../../context/fix-locations.js";
|
||||
import { getChildren, getFragmentFromRoot, getInstanceFromRoot, getModuleFromRoot, getOptionsFromRoot, } from "../compat.js";
|
||||
import { sortNodes } from "../sort.js";
|
||||
import { withoutProjectParserOptions } from "../parser-options.js";
|
||||
import { ParseError } from "../../main.js";
|
||||
/**
|
||||
* Convert root
|
||||
*/
|
||||
export function convertSvelteRoot(svelteAst, ctx) {
|
||||
const ast = {
|
||||
type: "Program",
|
||||
body: [],
|
||||
comments: ctx.comments,
|
||||
sourceType: "module",
|
||||
tokens: ctx.tokens,
|
||||
parent: null,
|
||||
...ctx.getConvertLocation({ start: 0, end: ctx.code.length }),
|
||||
};
|
||||
const body = ast.body;
|
||||
const snippetChildren = [];
|
||||
const fragment = getFragmentFromRoot(svelteAst);
|
||||
if (fragment) {
|
||||
let children = getChildren(fragment);
|
||||
const options = getOptionsFromRoot(svelteAst);
|
||||
if (options) {
|
||||
children = [...children];
|
||||
if (!children.some((node, idx) => {
|
||||
if (options.end <= node.start) {
|
||||
children.splice(idx, 0, options);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
})) {
|
||||
children.push(options);
|
||||
}
|
||||
}
|
||||
const nonSnippetChildren = [];
|
||||
for (const child of children) {
|
||||
if (child.type === "SnippetBlock") {
|
||||
snippetChildren.push(child);
|
||||
}
|
||||
else {
|
||||
nonSnippetChildren.push(child);
|
||||
}
|
||||
}
|
||||
body.push(...convertChildren({ nodes: nonSnippetChildren }, ast, ctx));
|
||||
}
|
||||
let script = null;
|
||||
const instance = getInstanceFromRoot(svelteAst);
|
||||
if (instance) {
|
||||
script = {
|
||||
type: "SvelteScriptElement",
|
||||
name: null,
|
||||
startTag: null,
|
||||
body: [],
|
||||
endTag: null,
|
||||
parent: ast,
|
||||
...ctx.getConvertLocation(instance),
|
||||
};
|
||||
extractAttributes(script, ctx);
|
||||
extractElementTags(script, ctx, {
|
||||
buildNameNode: (openTokenRange) => {
|
||||
ctx.addToken("HTMLIdentifier", openTokenRange);
|
||||
const name = {
|
||||
type: "SvelteName",
|
||||
name: "script",
|
||||
parent: script,
|
||||
...ctx.getConvertLocation(openTokenRange),
|
||||
};
|
||||
return name;
|
||||
},
|
||||
});
|
||||
body.push(script);
|
||||
}
|
||||
const module = getModuleFromRoot(svelteAst);
|
||||
if (module) {
|
||||
const script = {
|
||||
type: "SvelteScriptElement",
|
||||
name: null,
|
||||
startTag: null,
|
||||
body: [],
|
||||
endTag: null,
|
||||
parent: ast,
|
||||
...ctx.getConvertLocation(module),
|
||||
};
|
||||
extractAttributes(script, ctx);
|
||||
extractElementTags(script, ctx, {
|
||||
buildNameNode: (openTokenRange) => {
|
||||
ctx.addToken("HTMLIdentifier", openTokenRange);
|
||||
const name = {
|
||||
type: "SvelteName",
|
||||
name: "script",
|
||||
parent: script,
|
||||
...ctx.getConvertLocation(openTokenRange),
|
||||
};
|
||||
return name;
|
||||
},
|
||||
});
|
||||
body.push(script);
|
||||
}
|
||||
if (svelteAst.css) {
|
||||
const style = {
|
||||
type: "SvelteStyleElement",
|
||||
name: null,
|
||||
startTag: null,
|
||||
children: [],
|
||||
endTag: null,
|
||||
parent: ast,
|
||||
...ctx.getConvertLocation(svelteAst.css),
|
||||
};
|
||||
extractAttributes(style, ctx);
|
||||
extractElementTags(style, ctx, {
|
||||
buildNameNode: (openTokenRange) => {
|
||||
ctx.addToken("HTMLIdentifier", openTokenRange);
|
||||
const name = {
|
||||
type: "SvelteName",
|
||||
name: "style",
|
||||
parent: style,
|
||||
...ctx.getConvertLocation(openTokenRange),
|
||||
};
|
||||
return name;
|
||||
},
|
||||
});
|
||||
if (style.endTag && style.startTag.range[1] < style.endTag.range[0]) {
|
||||
const contentRange = {
|
||||
start: style.startTag.range[1],
|
||||
end: style.endTag.range[0],
|
||||
};
|
||||
ctx.addToken("HTMLText", contentRange);
|
||||
style.children = [
|
||||
{
|
||||
type: "SvelteText",
|
||||
value: ctx.code.slice(contentRange.start, contentRange.end),
|
||||
parent: style,
|
||||
...ctx.getConvertLocation(contentRange),
|
||||
},
|
||||
];
|
||||
}
|
||||
body.push(style);
|
||||
}
|
||||
body.push(...convertChildren({ nodes: snippetChildren }, ast, ctx));
|
||||
if (script)
|
||||
convertGenericsAttribute(script, ctx);
|
||||
// Process for comments in tags
|
||||
const comments = svelteAst.comments;
|
||||
if (comments && Array.isArray(comments) && comments.length > 0) {
|
||||
const tags = [];
|
||||
// Extract tags in order to check whether comments are inside tags or not.
|
||||
const elementsBuffer = [
|
||||
...body.filter((node) => {
|
||||
return (node.type === "SvelteScriptElement" ||
|
||||
node.type === "SvelteStyleElement" ||
|
||||
node.type === "SvelteElement");
|
||||
}),
|
||||
];
|
||||
let element;
|
||||
while ((element = elementsBuffer.shift())) {
|
||||
tags.push(element.startTag);
|
||||
if (element.type === "SvelteElement") {
|
||||
elementsBuffer.unshift(...element.children.filter((node) => node.type === "SvelteElement"));
|
||||
}
|
||||
}
|
||||
// Process all comments from Svelte compiler
|
||||
for (const comment of comments) {
|
||||
if (comment.type !== "Block" && comment.type !== "Line") {
|
||||
throw new ParseError(`Unknown comment type: ${comment.type}`, comment.start, ctx);
|
||||
}
|
||||
const tag = tags.find((tag) => tag.range[0] <= comment.start && comment.end <= tag.range[1]);
|
||||
if (!tag) {
|
||||
// If the comment is outside of all tags, it will be skipped.
|
||||
continue;
|
||||
}
|
||||
if (tag.attributes.some((attr) => attr.range[0] <= comment.start && comment.end <= attr.range[1])) {
|
||||
// If the comment is inside the attributes, it will be skipped because it is a comment inside an expression.
|
||||
continue;
|
||||
}
|
||||
ctx.addComment({
|
||||
type: comment.type === "Block" ? "Block" : "Line",
|
||||
value: comment.value,
|
||||
...ctx.getConvertLocation(comment),
|
||||
});
|
||||
}
|
||||
}
|
||||
// Set the scope of the Program node.
|
||||
ctx.scriptLet.addProgramRestore((node, _tokens, _comments, { scopeManager, registerNodeToScope, addPostProcess }) => {
|
||||
const scopes = [];
|
||||
for (const scope of scopeManager.scopes) {
|
||||
if (scope.block === node) {
|
||||
registerNodeToScope(ast, scope);
|
||||
scopes.push(scope);
|
||||
}
|
||||
}
|
||||
addPostProcess(() => {
|
||||
// Reverts the node indicated by `block` to the original Program node.
|
||||
// This state is incorrect, but `eslint-utils`'s `referenceTracker.iterateEsmReferences()` tracks import statements
|
||||
// from Program nodes set to `block` in global scope. This can only be handled by the original Program node.
|
||||
scopeManager.globalScope.block = node;
|
||||
});
|
||||
});
|
||||
sortNodes(body);
|
||||
return ast;
|
||||
}
|
||||
/** Extract attrs */
|
||||
function extractAttributes(element, ctx) {
|
||||
element.startTag = {
|
||||
type: "SvelteStartTag",
|
||||
attributes: [],
|
||||
selfClosing: false,
|
||||
parent: element,
|
||||
range: [element.range[0], null],
|
||||
loc: {
|
||||
start: {
|
||||
line: element.loc.start.line,
|
||||
column: element.loc.start.column,
|
||||
},
|
||||
end: null,
|
||||
},
|
||||
};
|
||||
const block = ctx.findBlock(element);
|
||||
if (block) {
|
||||
element.startTag.attributes.push(...convertAttributes(block.attrs, element.startTag, ctx));
|
||||
}
|
||||
}
|
||||
/** Convert generics attribute */
|
||||
function convertGenericsAttribute(script, ctx) {
|
||||
const lang = ctx.sourceCode.scripts.attrs.lang;
|
||||
if (lang !== "ts" && lang !== "typescript") {
|
||||
return;
|
||||
}
|
||||
const genericsAttribute = script.startTag.attributes.find((attr) => {
|
||||
return (attr.type === "SvelteAttribute" &&
|
||||
attr.key.name === "generics" &&
|
||||
attr.value.length === 1 &&
|
||||
attr.value[0].type === "SvelteLiteral");
|
||||
});
|
||||
if (!genericsAttribute) {
|
||||
return;
|
||||
}
|
||||
const value = genericsAttribute.value[0];
|
||||
const genericValueCode = ctx.code.slice(value.range[0], value.range[1]);
|
||||
const scriptLet = `void function<${genericValueCode}>(){}`;
|
||||
let result;
|
||||
try {
|
||||
result = parseScriptWithoutAnalyzeScope(scriptLet, ctx.sourceCode.scripts.attrs, withoutProjectParserOptions(ctx.parserOptions));
|
||||
}
|
||||
catch {
|
||||
// ignore
|
||||
return;
|
||||
}
|
||||
delete genericsAttribute.boolean;
|
||||
delete genericsAttribute.value;
|
||||
// Remove value token indexes
|
||||
sortNodes(ctx.tokens);
|
||||
const firstTokenIndex = ctx.tokens.findIndex((token) => value.range[0] <= token.range[0] && token.range[1] <= value.range[1]);
|
||||
const lastTokenCount = ctx.tokens
|
||||
.slice(firstTokenIndex)
|
||||
.findIndex((token) => value.range[1] <= token.range[0]);
|
||||
ctx.tokens.splice(firstTokenIndex, lastTokenCount >= 0 ? lastTokenCount : Infinity);
|
||||
const generics = genericsAttribute;
|
||||
generics.type = "SvelteGenericsDirective";
|
||||
generics.params = [];
|
||||
result.ast.tokens.shift(); // void
|
||||
result.ast.tokens.shift(); // function
|
||||
result.ast.tokens.shift(); // <
|
||||
result.ast.tokens.pop(); // }
|
||||
result.ast.tokens.pop(); // {
|
||||
result.ast.tokens.pop(); // )
|
||||
result.ast.tokens.pop(); // (
|
||||
result.ast.tokens.pop(); // >
|
||||
fixLocations(result.ast, result.ast.tokens, result.ast.comments, value.range[0] - 14, result.visitorKeys, ctx);
|
||||
const { ast } = result;
|
||||
const statement = ast.body[0];
|
||||
const rawExpression = statement.expression;
|
||||
const fnDecl = rawExpression.argument;
|
||||
const typeParameters = fnDecl
|
||||
.typeParameters;
|
||||
const params = typeParameters.params;
|
||||
// Replace tokens
|
||||
for (const tokensKey of ["tokens", "comments"]) {
|
||||
for (const token of result.ast[tokensKey]) {
|
||||
if (params.every((param) => token.range[1] <= param.range[0] ||
|
||||
param.range[1] <= token.range[0])) {
|
||||
ctx[tokensKey].push(token);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const param of params) {
|
||||
param.parent = generics;
|
||||
generics.params.push(param);
|
||||
ctx.scriptLet.addGenericTypeAliasDeclaration(param, (id, typeNode) => {
|
||||
param.name = id;
|
||||
if (param.constraint) {
|
||||
param.constraint = typeNode;
|
||||
}
|
||||
}, (typeNode) => {
|
||||
param.default = typeNode;
|
||||
});
|
||||
}
|
||||
}
|
||||
7
node_modules/svelte-eslint-parser/lib/parser/converts/text.d.ts
generated
vendored
Normal file
7
node_modules/svelte-eslint-parser/lib/parser/converts/text.d.ts
generated
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
import type { SvelteLiteral, SvelteText } from "../../ast/index.js";
|
||||
import type { Context } from "../../context/index.js";
|
||||
import type * as SvAST from "../svelte-ast-types.js";
|
||||
/** Convert for Text */
|
||||
export declare function convertText(node: SvAST.Text, parent: SvelteText["parent"], ctx: Context): SvelteText;
|
||||
/** Convert for Text to Literal */
|
||||
export declare function convertTextToLiteral(node: SvAST.Text, parent: SvelteLiteral["parent"], ctx: Context): SvelteLiteral;
|
||||
40
node_modules/svelte-eslint-parser/lib/parser/converts/text.js
generated
vendored
Normal file
40
node_modules/svelte-eslint-parser/lib/parser/converts/text.js
generated
vendored
Normal file
@@ -0,0 +1,40 @@
|
||||
/** Convert for Text */
|
||||
export function convertText(node, parent, ctx) {
|
||||
const text = {
|
||||
type: "SvelteText",
|
||||
value: node.data,
|
||||
parent,
|
||||
...ctx.getConvertLocation(node),
|
||||
};
|
||||
extractTextTokens(node, ctx);
|
||||
return text;
|
||||
}
|
||||
/** Convert for Text to Literal */
|
||||
export function convertTextToLiteral(node, parent, ctx) {
|
||||
const text = {
|
||||
type: "SvelteLiteral",
|
||||
value: node.data,
|
||||
parent,
|
||||
...ctx.getConvertLocation(node),
|
||||
};
|
||||
extractTextTokens(node, ctx);
|
||||
return text;
|
||||
}
|
||||
/** Extract tokens */
|
||||
function extractTextTokens(node, ctx) {
|
||||
const loc = node;
|
||||
let start = loc.start;
|
||||
let word = false;
|
||||
for (let index = loc.start; index < loc.end; index++) {
|
||||
if (word !== Boolean(ctx.code[index].trim())) {
|
||||
if (start < index) {
|
||||
ctx.addToken("HTMLText", { start, end: index });
|
||||
}
|
||||
word = !word;
|
||||
start = index;
|
||||
}
|
||||
}
|
||||
if (start < loc.end) {
|
||||
ctx.addToken("HTMLText", { start, end: loc.end });
|
||||
}
|
||||
}
|
||||
6
node_modules/svelte-eslint-parser/lib/parser/eslint-scope.d.ts
generated
vendored
Normal file
6
node_modules/svelte-eslint-parser/lib/parser/eslint-scope.d.ts
generated
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
import * as eslintScope from "eslint-scope";
|
||||
/**
|
||||
* Load `eslint-scope` from ESLint's dependencies, user dependencies, or this package's dependencies.
|
||||
* Return the latest version among them.
|
||||
*/
|
||||
export declare function getESLintScope(): typeof eslintScope;
|
||||
21
node_modules/svelte-eslint-parser/lib/parser/eslint-scope.js
generated
vendored
Normal file
21
node_modules/svelte-eslint-parser/lib/parser/eslint-scope.js
generated
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
import { loadNewestModule } from "../utils/cjs-module.js";
|
||||
import * as eslintScope from "eslint-scope";
|
||||
let eslintScopeCache = null;
|
||||
/**
|
||||
* Load `eslint-scope` from ESLint's dependencies, user dependencies, or this package's dependencies.
|
||||
* Return the latest version among them.
|
||||
*/
|
||||
export function getESLintScope() {
|
||||
if (!eslintScopeCache) {
|
||||
try {
|
||||
eslintScopeCache = loadNewestModule("eslint-scope");
|
||||
}
|
||||
catch {
|
||||
// ignore
|
||||
}
|
||||
if (!eslintScopeCache) {
|
||||
eslintScopeCache = eslintScope.default || eslintScope;
|
||||
}
|
||||
}
|
||||
return eslintScopeCache;
|
||||
}
|
||||
8
node_modules/svelte-eslint-parser/lib/parser/espree.d.ts
generated
vendored
Normal file
8
node_modules/svelte-eslint-parser/lib/parser/espree.d.ts
generated
vendored
Normal file
@@ -0,0 +1,8 @@
|
||||
import type { BasicParserObject } from "./parser-object.js";
|
||||
/**
|
||||
* Load `espree` from ESLint's dependencies, user dependencies, or this package's dependencies.
|
||||
* Return the latest version among them.
|
||||
*/
|
||||
export declare function getEspree(): BasicParserObject & {
|
||||
latestEcmaVersion: number;
|
||||
};
|
||||
21
node_modules/svelte-eslint-parser/lib/parser/espree.js
generated
vendored
Normal file
21
node_modules/svelte-eslint-parser/lib/parser/espree.js
generated
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
import { loadNewestModule } from "../utils/cjs-module.js";
|
||||
import * as espree from "espree";
|
||||
let espreeCache = null;
|
||||
/**
|
||||
* Load `espree` from ESLint's dependencies, user dependencies, or this package's dependencies.
|
||||
* Return the latest version among them.
|
||||
*/
|
||||
export function getEspree() {
|
||||
if (!espreeCache) {
|
||||
try {
|
||||
espreeCache = loadNewestModule("espree");
|
||||
}
|
||||
catch {
|
||||
// ignore
|
||||
}
|
||||
if (!espreeCache) {
|
||||
espreeCache = espree.default || espree;
|
||||
}
|
||||
}
|
||||
return espreeCache;
|
||||
}
|
||||
7
node_modules/svelte-eslint-parser/lib/parser/globals.d.ts
generated
vendored
Normal file
7
node_modules/svelte-eslint-parser/lib/parser/globals.d.ts
generated
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
import type { SvelteParseContext } from "./svelte-parse-context.js";
|
||||
declare const globalsForSvelte: readonly ["$$slots", "$$props", "$$restProps"];
|
||||
export declare const globalsForRunes: readonly ["$state", "$derived", "$effect", "$props", "$bindable", "$inspect", "$host"];
|
||||
type Global = (typeof globalsForSvelte)[number] | (typeof globalsForRunes)[number];
|
||||
export declare function getGlobalsForSvelte(svelteParseContext: SvelteParseContext): readonly Global[];
|
||||
export declare function getGlobalsForSvelteScript(svelteParseContext: SvelteParseContext): readonly Global[];
|
||||
export {};
|
||||
24
node_modules/svelte-eslint-parser/lib/parser/globals.js
generated
vendored
Normal file
24
node_modules/svelte-eslint-parser/lib/parser/globals.js
generated
vendored
Normal file
@@ -0,0 +1,24 @@
|
||||
const globalsForSvelte = ["$$slots", "$$props", "$$restProps"];
|
||||
export const globalsForRunes = [
|
||||
"$state",
|
||||
"$derived",
|
||||
"$effect",
|
||||
"$props",
|
||||
"$bindable",
|
||||
"$inspect",
|
||||
"$host",
|
||||
];
|
||||
export function getGlobalsForSvelte(svelteParseContext) {
|
||||
// Process if not confirmed as non-Runes mode.
|
||||
if (svelteParseContext.runes !== false) {
|
||||
return [...globalsForSvelte, ...globalsForRunes];
|
||||
}
|
||||
return globalsForSvelte;
|
||||
}
|
||||
export function getGlobalsForSvelteScript(svelteParseContext) {
|
||||
// Process if not confirmed as non-Runes mode.
|
||||
if (svelteParseContext.runes !== false) {
|
||||
return globalsForRunes;
|
||||
}
|
||||
return [];
|
||||
}
|
||||
6
node_modules/svelte-eslint-parser/lib/parser/html.d.ts
generated
vendored
Normal file
6
node_modules/svelte-eslint-parser/lib/parser/html.d.ts
generated
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
import type * as Compiler from "./svelte-ast-types-for-v5.js";
|
||||
/** Parse HTML attributes */
|
||||
export declare function parseAttributes(code: string, startIndex: number): {
|
||||
attributes: Compiler.Attribute[];
|
||||
index: number;
|
||||
};
|
||||
271
node_modules/svelte-eslint-parser/lib/parser/html.js
generated
vendored
Normal file
271
node_modules/svelte-eslint-parser/lib/parser/html.js
generated
vendored
Normal file
@@ -0,0 +1,271 @@
|
||||
import { getEspree } from "./espree.js";
|
||||
const RE_IS_SPACE = /^\s$/u;
|
||||
class State {
|
||||
constructor(code, index) {
|
||||
this.code = code;
|
||||
this.index = index;
|
||||
}
|
||||
getCurr() {
|
||||
return this.code[this.index];
|
||||
}
|
||||
skipSpaces() {
|
||||
while (this.currIsSpace()) {
|
||||
this.advance();
|
||||
if (this.eof())
|
||||
break;
|
||||
}
|
||||
}
|
||||
currIsSpace() {
|
||||
return RE_IS_SPACE.test(this.getCurr() || "");
|
||||
}
|
||||
currIs(expect) {
|
||||
return this.code.startsWith(expect, this.index);
|
||||
}
|
||||
eof() {
|
||||
return this.index >= this.code.length;
|
||||
}
|
||||
eat(expect) {
|
||||
if (!this.currIs(expect)) {
|
||||
return null;
|
||||
}
|
||||
this.index += expect.length;
|
||||
return expect;
|
||||
}
|
||||
advance() {
|
||||
this.index++;
|
||||
return this.getCurr();
|
||||
}
|
||||
}
|
||||
/** Parse HTML attributes */
|
||||
export function parseAttributes(code, startIndex) {
|
||||
const attributes = [];
|
||||
const state = new State(code, startIndex);
|
||||
while (!state.eof()) {
|
||||
state.skipSpaces();
|
||||
if (state.currIs(">") || state.currIs("/>") || state.eof())
|
||||
break;
|
||||
attributes.push(parseAttribute(state));
|
||||
}
|
||||
return { attributes, index: state.index };
|
||||
}
|
||||
/** Parse HTML attribute */
|
||||
function parseAttribute(state) {
|
||||
const start = state.index;
|
||||
// parse key
|
||||
const key = parseAttributeKey(state);
|
||||
const keyEnd = state.index;
|
||||
state.skipSpaces();
|
||||
if (!state.eat("=")) {
|
||||
return {
|
||||
type: "Attribute",
|
||||
name: key,
|
||||
name_loc: null,
|
||||
value: true,
|
||||
start,
|
||||
end: keyEnd,
|
||||
};
|
||||
}
|
||||
state.skipSpaces();
|
||||
if (state.eof()) {
|
||||
return {
|
||||
type: "Attribute",
|
||||
name: key,
|
||||
name_loc: null,
|
||||
value: true,
|
||||
start,
|
||||
end: keyEnd,
|
||||
};
|
||||
}
|
||||
// parse value
|
||||
const value = parseAttributeValue(state);
|
||||
return {
|
||||
type: "Attribute",
|
||||
name: key,
|
||||
name_loc: null,
|
||||
value: [value],
|
||||
start,
|
||||
end: state.index,
|
||||
};
|
||||
}
|
||||
/** Parse HTML attribute key */
|
||||
function parseAttributeKey(state) {
|
||||
const start = state.index;
|
||||
while (state.advance()) {
|
||||
if (state.currIs("=") ||
|
||||
state.currIs(">") ||
|
||||
state.currIs("/>") ||
|
||||
state.currIsSpace()) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
const end = state.index;
|
||||
return state.code.slice(start, end);
|
||||
}
|
||||
/** Parse HTML attribute value */
|
||||
function parseAttributeValue(state) {
|
||||
const start = state.index;
|
||||
const quote = state.eat('"') || state.eat("'");
|
||||
const startBk = state.index;
|
||||
const expression = parseAttributeMustache(state);
|
||||
if (expression) {
|
||||
if (!quote || state.eat(quote)) {
|
||||
const end = state.index;
|
||||
return {
|
||||
type: "ExpressionTag",
|
||||
expression,
|
||||
start,
|
||||
end,
|
||||
};
|
||||
}
|
||||
}
|
||||
state.index = startBk;
|
||||
if (quote) {
|
||||
if (state.eof()) {
|
||||
return {
|
||||
type: "Text",
|
||||
data: quote,
|
||||
raw: quote,
|
||||
start,
|
||||
end: state.index,
|
||||
};
|
||||
}
|
||||
let c;
|
||||
while ((c = state.getCurr())) {
|
||||
state.advance();
|
||||
if (c === quote) {
|
||||
const end = state.index;
|
||||
const data = state.code.slice(start + 1, end - 1);
|
||||
return {
|
||||
type: "Text",
|
||||
data,
|
||||
raw: data,
|
||||
start: start + 1,
|
||||
end: end - 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
while (state.advance()) {
|
||||
if (state.currIsSpace() || state.currIs(">") || state.currIs("/>")) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
const end = state.index;
|
||||
const data = state.code.slice(start, end);
|
||||
return {
|
||||
type: "Text",
|
||||
data,
|
||||
raw: data,
|
||||
start,
|
||||
end,
|
||||
};
|
||||
}
|
||||
/** Parse mustache */
|
||||
function parseAttributeMustache(state) {
|
||||
if (!state.eat("{")) {
|
||||
return null;
|
||||
}
|
||||
// parse simple expression
|
||||
const leadingComments = [];
|
||||
const startBk = state.index;
|
||||
state.skipSpaces();
|
||||
let start = state.index;
|
||||
while (!state.eof()) {
|
||||
if (state.eat("//")) {
|
||||
leadingComments.push(parseInlineComment(state.index - 2));
|
||||
state.skipSpaces();
|
||||
start = state.index;
|
||||
continue;
|
||||
}
|
||||
if (state.eat("/*")) {
|
||||
leadingComments.push(parseBlockComment(state.index - 2));
|
||||
state.skipSpaces();
|
||||
start = state.index;
|
||||
continue;
|
||||
}
|
||||
const stringQuote = state.eat('"') || state.eat("'");
|
||||
if (stringQuote) {
|
||||
skipString(stringQuote);
|
||||
state.skipSpaces();
|
||||
continue;
|
||||
}
|
||||
const endCandidate = state.index;
|
||||
state.skipSpaces();
|
||||
if (state.eat("}")) {
|
||||
const end = endCandidate;
|
||||
try {
|
||||
const espree = getEspree();
|
||||
const expression = espree.parse(state.code.slice(start, end), {
|
||||
ecmaVersion: espree.latestEcmaVersion,
|
||||
}).body[0].expression;
|
||||
delete expression.range;
|
||||
return {
|
||||
...expression,
|
||||
leadingComments,
|
||||
start,
|
||||
end,
|
||||
};
|
||||
}
|
||||
catch {
|
||||
break;
|
||||
}
|
||||
}
|
||||
state.advance();
|
||||
}
|
||||
state.index = startBk;
|
||||
return null;
|
||||
function parseInlineComment(tokenStart) {
|
||||
const valueStart = state.index;
|
||||
let valueEnd = null;
|
||||
while (!state.eof()) {
|
||||
if (state.eat("\n")) {
|
||||
valueEnd = state.index - 1;
|
||||
break;
|
||||
}
|
||||
state.advance();
|
||||
}
|
||||
if (valueEnd == null) {
|
||||
valueEnd = state.index;
|
||||
}
|
||||
return {
|
||||
type: "Line",
|
||||
value: state.code.slice(valueStart, valueEnd),
|
||||
start: tokenStart,
|
||||
end: state.index,
|
||||
};
|
||||
}
|
||||
function parseBlockComment(tokenStart) {
|
||||
const valueStart = state.index;
|
||||
let valueEnd = null;
|
||||
while (!state.eof()) {
|
||||
if (state.eat("*/")) {
|
||||
valueEnd = state.index - 2;
|
||||
break;
|
||||
}
|
||||
state.advance();
|
||||
}
|
||||
if (valueEnd == null) {
|
||||
valueEnd = state.index;
|
||||
}
|
||||
return {
|
||||
type: "Block",
|
||||
value: state.code.slice(valueStart, valueEnd),
|
||||
start: tokenStart,
|
||||
end: state.index,
|
||||
};
|
||||
}
|
||||
function skipString(stringQuote) {
|
||||
while (!state.eof()) {
|
||||
if (state.eat(stringQuote)) {
|
||||
break;
|
||||
}
|
||||
if (state.eat("\\")) {
|
||||
// escape
|
||||
state.advance();
|
||||
}
|
||||
state.advance();
|
||||
}
|
||||
}
|
||||
}
|
||||
52
node_modules/svelte-eslint-parser/lib/parser/index.d.ts
generated
vendored
Normal file
52
node_modules/svelte-eslint-parser/lib/parser/index.d.ts
generated
vendored
Normal file
@@ -0,0 +1,52 @@
|
||||
import type { Comment, SourceLocation, SvelteProgram, Token } from "../ast/index.js";
|
||||
import type { Program } from "estree";
|
||||
import type * as eslint from "eslint";
|
||||
import type { Rule, Node } from "postcss";
|
||||
import type { Node as SelectorNode, Root as SelectorRoot } from "postcss-selector-parser";
|
||||
import type * as SvAST from "./svelte-ast-types.js";
|
||||
import type * as Compiler from "./svelte-ast-types-for-v5.js";
|
||||
import { type StyleContext, type StyleContextNoStyleElement, type StyleContextParseError, type StyleContextSuccess, type StyleContextUnknownLang } from "./style-context.js";
|
||||
import { type SvelteParseContext } from "./svelte-parse-context.js";
|
||||
export { StyleContext, StyleContextNoStyleElement, StyleContextParseError, StyleContextSuccess, StyleContextUnknownLang, };
|
||||
export interface ESLintProgram extends Program {
|
||||
comments: Comment[];
|
||||
tokens: Token[];
|
||||
}
|
||||
/**
|
||||
* The parsing result of ESLint custom parsers.
|
||||
*/
|
||||
export interface ESLintExtendedProgram {
|
||||
ast: ESLintProgram;
|
||||
services?: Record<string, any>;
|
||||
visitorKeys?: {
|
||||
[type: string]: string[];
|
||||
};
|
||||
scopeManager?: eslint.Scope.ScopeManager;
|
||||
_virtualScriptCode?: string;
|
||||
}
|
||||
type ParseResult = {
|
||||
ast: SvelteProgram;
|
||||
services: Record<string, any> & ({
|
||||
isSvelte: true;
|
||||
isSvelteScript: false;
|
||||
getSvelteHtmlAst: () => SvAST.Fragment | Compiler.Fragment;
|
||||
getStyleContext: () => StyleContext;
|
||||
getStyleSelectorAST: (rule: Rule) => SelectorRoot;
|
||||
styleNodeLoc: (node: Node) => Partial<SourceLocation>;
|
||||
styleNodeRange: (node: Node) => [number | undefined, number | undefined];
|
||||
styleSelectorNodeLoc: (node: SelectorNode) => Partial<SourceLocation>;
|
||||
svelteParseContext: SvelteParseContext;
|
||||
} | {
|
||||
isSvelte: false;
|
||||
isSvelteScript: true;
|
||||
svelteParseContext: SvelteParseContext;
|
||||
});
|
||||
visitorKeys: {
|
||||
[type: string]: string[];
|
||||
};
|
||||
scopeManager: eslint.Scope.ScopeManager;
|
||||
};
|
||||
/**
|
||||
* Parse source code
|
||||
*/
|
||||
export declare function parseForESLint(code: string, options?: any): ParseResult;
|
||||
201
node_modules/svelte-eslint-parser/lib/parser/index.js
generated
vendored
Normal file
201
node_modules/svelte-eslint-parser/lib/parser/index.js
generated
vendored
Normal file
@@ -0,0 +1,201 @@
|
||||
import { KEYS } from "../visitor-keys.js";
|
||||
import { Context } from "../context/index.js";
|
||||
import { parseScript, parseScriptInSvelte } from "./script.js";
|
||||
import { sortNodes } from "./sort.js";
|
||||
import { parseTemplate } from "./template.js";
|
||||
import { analyzePropsScope, analyzeReactiveScope, analyzeSnippetsScope, analyzeStoreScope, } from "./analyze-scope.js";
|
||||
import { ParseError } from "../errors.js";
|
||||
import { parseTypeScript, parseTypeScriptInSvelte, } from "./typescript/index.js";
|
||||
import { addReference } from "../scope/index.js";
|
||||
import { parseStyleContext, parseSelector, styleNodeLoc, styleNodeRange, styleSelectorNodeLoc, } from "./style-context.js";
|
||||
import { getGlobalsForSvelte, getGlobalsForSvelteScript } from "./globals.js";
|
||||
import { isTypeScript, normalizeParserOptions } from "./parser-options.js";
|
||||
import { getFragmentFromRoot, getInstanceScriptRange } from "./compat.js";
|
||||
import { hasRunesSymbol, resolveSvelteParseContextForSvelte, resolveSvelteParseContextForSvelteScript, } from "./svelte-parse-context.js";
|
||||
import { resolveSvelteConfigFromOption } from "../svelte-config/index.js";
|
||||
import { getESLintScope } from "./eslint-scope.js";
|
||||
import { rememberParserOptions } from "../ts-sys-hook.js";
|
||||
/**
|
||||
* Parse source code
|
||||
*/
|
||||
export function parseForESLint(code, options) {
|
||||
const svelteConfig = resolveSvelteConfigFromOption(options);
|
||||
const parserOptions = normalizeParserOptions(options);
|
||||
// Keep the `ts.sys` hook in sync with the parser/svelte config ESLint is
|
||||
// currently using. The latest set wins for any in-process TS read.
|
||||
rememberParserOptions(parserOptions);
|
||||
if (parserOptions.filePath &&
|
||||
(parserOptions.filePath.endsWith(".svelte.js") ||
|
||||
parserOptions.filePath.endsWith(".svelte.ts"))) {
|
||||
const svelteParseContext = resolveSvelteParseContextForSvelteScript(svelteConfig);
|
||||
return parseAsScript(code, parserOptions, svelteParseContext);
|
||||
}
|
||||
return parseAsSvelte(code, svelteConfig, parserOptions);
|
||||
}
|
||||
/**
|
||||
* Parse source code as svelte component
|
||||
*/
|
||||
function parseAsSvelte(code, svelteConfig, parserOptions) {
|
||||
const ctx = new Context(code, parserOptions);
|
||||
const resultTemplate = parseTemplate(ctx.sourceCode.template, ctx, parserOptions);
|
||||
const svelteParseContext = resolveSvelteParseContextForSvelte(svelteConfig, parserOptions, resultTemplate.svelteAst);
|
||||
const scripts = ctx.sourceCode.scripts;
|
||||
const resultScript = ctx.isTypeScript()
|
||||
? parseTypeScriptInSvelte(scripts.getCurrentVirtualCodeInfo(), scripts.attrs, parserOptions, {
|
||||
slots: ctx.slots,
|
||||
svelteParseContext,
|
||||
instanceScriptRange: getInstanceScriptRange(resultTemplate.svelteAst),
|
||||
})
|
||||
: parseScriptInSvelte(scripts.getCurrentVirtualCode(), scripts.attrs, parserOptions);
|
||||
ctx.scriptLet.restore(resultScript);
|
||||
ctx.tokens.push(...resultScript.ast.tokens);
|
||||
ctx.comments.push(...resultScript.ast.comments);
|
||||
sortNodes(ctx.comments);
|
||||
sortNodes(ctx.tokens);
|
||||
extractTokens(ctx);
|
||||
analyzeStoreScope(resultScript.scopeManager, svelteParseContext);
|
||||
analyzeReactiveScope(resultScript.scopeManager);
|
||||
analyzeStoreScope(resultScript.scopeManager, svelteParseContext); // for reactive vars
|
||||
analyzeSnippetsScope(ctx.snippets, resultScript.scopeManager);
|
||||
// Add $$xxx variable
|
||||
addGlobalVariables(resultScript.scopeManager, getGlobalsForSvelte(svelteParseContext));
|
||||
const ast = resultTemplate.ast;
|
||||
const statements = [...resultScript.ast.body];
|
||||
ast.sourceType = resultScript.ast.sourceType;
|
||||
const scriptElements = ast.body.filter((b) => b.type === "SvelteScriptElement");
|
||||
for (let index = 0; index < scriptElements.length; index++) {
|
||||
const body = scriptElements[index];
|
||||
let statement = statements[0];
|
||||
while (statement &&
|
||||
body.range[0] <= statement.range[0] &&
|
||||
(statement.range[1] <= body.range[1] ||
|
||||
index === scriptElements.length - 1)) {
|
||||
statement.parent = body;
|
||||
body.body.push(statement);
|
||||
statements.shift();
|
||||
statement = statements[0];
|
||||
}
|
||||
if (!body.startTag.attributes.some((attr) => attr.type === "SvelteAttribute" &&
|
||||
attr.key.name === "context" &&
|
||||
attr.value.length === 1 &&
|
||||
attr.value[0].type === "SvelteLiteral" &&
|
||||
attr.value[0].value === "module")) {
|
||||
analyzePropsScope(body, resultScript.scopeManager, svelteParseContext);
|
||||
}
|
||||
}
|
||||
if (statements.length) {
|
||||
throw new ParseError("The script is unterminated", statements[0].range[1], ctx);
|
||||
}
|
||||
const styleElement = ast.body.find((b) => b.type === "SvelteStyleElement");
|
||||
let styleContext = null;
|
||||
const selectorASTs = new Map();
|
||||
resultScript.ast = ast;
|
||||
resultScript.services = Object.assign(resultScript.services || {}, {
|
||||
isSvelte: true,
|
||||
isSvelteScript: false,
|
||||
getSvelteHtmlAst() {
|
||||
return getFragmentFromRoot(resultTemplate.svelteAst);
|
||||
},
|
||||
getStyleContext() {
|
||||
if (styleContext === null) {
|
||||
styleContext = parseStyleContext(styleElement, ctx);
|
||||
}
|
||||
return styleContext;
|
||||
},
|
||||
getStyleSelectorAST(rule) {
|
||||
const cached = selectorASTs.get(rule);
|
||||
if (cached !== undefined) {
|
||||
return cached;
|
||||
}
|
||||
const ast = parseSelector(rule);
|
||||
selectorASTs.set(rule, ast);
|
||||
return ast;
|
||||
},
|
||||
styleNodeLoc,
|
||||
styleNodeRange,
|
||||
styleSelectorNodeLoc,
|
||||
svelteParseContext: {
|
||||
...svelteParseContext,
|
||||
// The compiler decides if runes mode is used after parsing.
|
||||
runes: svelteParseContext.runes ?? hasRunesSymbol(resultScript.ast),
|
||||
},
|
||||
});
|
||||
resultScript.visitorKeys = Object.assign({}, KEYS, resultScript.visitorKeys);
|
||||
return resultScript;
|
||||
}
|
||||
/**
|
||||
* Parse source code as script
|
||||
*/
|
||||
function parseAsScript(code, parserOptions, svelteParseContext) {
|
||||
const lang = parserOptions.filePath?.split(".").pop();
|
||||
const resultScript = isTypeScript(parserOptions, lang)
|
||||
? parseTypeScript(code, { lang }, parserOptions, svelteParseContext)
|
||||
: parseScript(code, { lang }, parserOptions);
|
||||
// Add $$xxx variable
|
||||
addGlobalVariables(resultScript.scopeManager, getGlobalsForSvelteScript(svelteParseContext));
|
||||
resultScript.services = Object.assign(resultScript.services || {}, {
|
||||
isSvelte: false,
|
||||
isSvelteScript: true,
|
||||
svelteParseContext,
|
||||
});
|
||||
resultScript.visitorKeys = Object.assign({}, KEYS, resultScript.visitorKeys);
|
||||
return resultScript;
|
||||
}
|
||||
function addGlobalVariables(scopeManager, globals) {
|
||||
const globalScope = scopeManager.globalScope;
|
||||
for (const globalName of globals) {
|
||||
if (globalScope.set.has(globalName))
|
||||
continue;
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention -- class name
|
||||
const { Variable } = getESLintScope();
|
||||
const variable = new Variable(globalName, globalScope);
|
||||
variable.name = globalName;
|
||||
variable.scope = globalScope;
|
||||
globalScope.variables.push(variable);
|
||||
globalScope.set.set(globalName, variable);
|
||||
globalScope.through = globalScope.through.filter((reference) => {
|
||||
if (reference.identifier.name === globalName) {
|
||||
// Links the variable and the reference.
|
||||
// And this reference is removed from `Scope#through`.
|
||||
reference.resolved = variable;
|
||||
addReference(variable.references, reference);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}
|
||||
}
|
||||
/** Extract tokens */
|
||||
function extractTokens(ctx) {
|
||||
const useRanges = sortNodes([...ctx.tokens, ...ctx.comments]).map((t) => t.range);
|
||||
let range = useRanges.shift();
|
||||
for (let index = 0; index < ctx.sourceCode.template.length; index++) {
|
||||
while (range && range[1] <= index) {
|
||||
range = useRanges.shift();
|
||||
}
|
||||
if (range && range[0] <= index) {
|
||||
index = range[1] - 1;
|
||||
continue;
|
||||
}
|
||||
const c = ctx.sourceCode.template[index];
|
||||
if (!c.trim()) {
|
||||
continue;
|
||||
}
|
||||
if (isPunctuator(c)) {
|
||||
ctx.addToken("Punctuator", { start: index, end: index + 1 });
|
||||
}
|
||||
else {
|
||||
// unknown
|
||||
// It is may be a bug.
|
||||
ctx.addToken("Identifier", { start: index, end: index + 1 });
|
||||
}
|
||||
}
|
||||
sortNodes(ctx.comments);
|
||||
sortNodes(ctx.tokens);
|
||||
/**
|
||||
* Checks if the given char is punctuator
|
||||
*/
|
||||
function isPunctuator(c) {
|
||||
return /^[^\w$]$/iu.test(c);
|
||||
}
|
||||
}
|
||||
34
node_modules/svelte-eslint-parser/lib/parser/parser-object.d.ts
generated
vendored
Normal file
34
node_modules/svelte-eslint-parser/lib/parser/parser-object.d.ts
generated
vendored
Normal file
@@ -0,0 +1,34 @@
|
||||
import type { ESLintExtendedProgram, ESLintProgram } from "./index.js";
|
||||
import type * as tsESLintParser from "@typescript-eslint/parser";
|
||||
type TSESLintParser = typeof tsESLintParser;
|
||||
/**
|
||||
* The type of basic ESLint custom parser.
|
||||
* e.g. espree
|
||||
*/
|
||||
export type BasicParserObject = {
|
||||
parse(code: string, options: any): ESLintProgram;
|
||||
parseForESLint: undefined;
|
||||
};
|
||||
/**
|
||||
* The type of ESLint custom parser enhanced for ESLint.
|
||||
* e.g. @babel/eslint-parser, @typescript-eslint/parser
|
||||
*/
|
||||
export type EnhancedParserObject = {
|
||||
parseForESLint(code: string, options: any): ESLintExtendedProgram;
|
||||
parse: undefined;
|
||||
};
|
||||
/**
|
||||
* The type of ESLint (custom) parsers.
|
||||
*/
|
||||
export type ParserObject = EnhancedParserObject | BasicParserObject;
|
||||
/** Checks whether given object is ParserObject */
|
||||
export declare function isParserObject(value: unknown): value is ParserObject;
|
||||
/** Checks whether given object is EnhancedParserObject */
|
||||
export declare function isEnhancedParserObject(value: unknown): value is EnhancedParserObject;
|
||||
/** Checks whether given object is BasicParserObject */
|
||||
export declare function isBasicParserObject(value: unknown): value is BasicParserObject;
|
||||
/** Checks whether given object maybe "@typescript-eslint/parser" */
|
||||
export declare function maybeTSESLintParserObject(value: unknown): value is TSESLintParser;
|
||||
/** Checks whether given object is "@typescript-eslint/parser" */
|
||||
export declare function isTSESLintParserObject(value: unknown): value is TSESLintParser;
|
||||
export {};
|
||||
35
node_modules/svelte-eslint-parser/lib/parser/parser-object.js
generated
vendored
Normal file
35
node_modules/svelte-eslint-parser/lib/parser/parser-object.js
generated
vendored
Normal file
@@ -0,0 +1,35 @@
|
||||
/** Checks whether given object is ParserObject */
|
||||
export function isParserObject(value) {
|
||||
return isEnhancedParserObject(value) || isBasicParserObject(value);
|
||||
}
|
||||
/** Checks whether given object is EnhancedParserObject */
|
||||
export function isEnhancedParserObject(value) {
|
||||
return Boolean(value && typeof value.parseForESLint === "function");
|
||||
}
|
||||
/** Checks whether given object is BasicParserObject */
|
||||
export function isBasicParserObject(value) {
|
||||
return Boolean(value && typeof value.parse === "function");
|
||||
}
|
||||
/** Checks whether given object maybe "@typescript-eslint/parser" */
|
||||
export function maybeTSESLintParserObject(value) {
|
||||
return (isEnhancedParserObject(value) &&
|
||||
isBasicParserObject(value) &&
|
||||
typeof value.createProgram === "function" &&
|
||||
typeof value.clearCaches === "function" &&
|
||||
typeof value.version === "string");
|
||||
}
|
||||
/** Checks whether given object is "@typescript-eslint/parser" */
|
||||
export function isTSESLintParserObject(value) {
|
||||
if (!isEnhancedParserObject(value))
|
||||
return false;
|
||||
try {
|
||||
const result = value.parseForESLint("", {});
|
||||
const services = result.services;
|
||||
return Boolean(services &&
|
||||
services.esTreeNodeToTSNodeMap &&
|
||||
services.tsNodeToESTreeNodeMap);
|
||||
}
|
||||
catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
42
node_modules/svelte-eslint-parser/lib/parser/parser-options.d.ts
generated
vendored
Normal file
42
node_modules/svelte-eslint-parser/lib/parser/parser-options.d.ts
generated
vendored
Normal file
@@ -0,0 +1,42 @@
|
||||
import type { Program } from "typescript";
|
||||
import { type UserOptionParser } from "./resolve-parser.js";
|
||||
export type NormalizedParserOptions = {
|
||||
parser?: UserOptionParser;
|
||||
project?: string | string[] | null;
|
||||
programs?: Program[] | null;
|
||||
disallowAutomaticSingleRunInference?: boolean;
|
||||
projectService?: unknown;
|
||||
EXPERIMENTAL_useProjectService?: unknown;
|
||||
ecmaVersion: number | "latest";
|
||||
sourceType: "module" | "script";
|
||||
ecmaFeatures?: {
|
||||
globalReturn?: boolean | undefined;
|
||||
impliedStrict?: boolean | undefined;
|
||||
jsx?: boolean | undefined;
|
||||
experimentalObjectRestSpread?: boolean | undefined;
|
||||
[key: string]: any;
|
||||
};
|
||||
svelteFeatures?: {
|
||||
runes?: boolean;
|
||||
};
|
||||
loc: boolean;
|
||||
range: boolean;
|
||||
raw: boolean;
|
||||
tokens: boolean;
|
||||
comment: boolean;
|
||||
eslintVisitorKeys: boolean;
|
||||
eslintScopeManager: boolean;
|
||||
filePath?: string;
|
||||
};
|
||||
/** Normalize parserOptions */
|
||||
export declare function normalizeParserOptions(options: any): NormalizedParserOptions;
|
||||
export declare function isTypeScript(parserOptions: NormalizedParserOptions, lang: string | undefined): boolean;
|
||||
/**
|
||||
* Remove typing-related options from parser options.
|
||||
*
|
||||
* Allows the typescript-eslint parser to parse a file without
|
||||
* trying to collect typing information from TypeScript.
|
||||
*
|
||||
* See https://typescript-eslint.io/packages/parser#withoutprojectparseroptionsparseroptions
|
||||
*/
|
||||
export declare function withoutProjectParserOptions(options: NormalizedParserOptions): NormalizedParserOptions;
|
||||
71
node_modules/svelte-eslint-parser/lib/parser/parser-options.js
generated
vendored
Normal file
71
node_modules/svelte-eslint-parser/lib/parser/parser-options.js
generated
vendored
Normal file
@@ -0,0 +1,71 @@
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import { isTSESLintParserObject, maybeTSESLintParserObject, } from "./parser-object.js";
|
||||
import { getParserForLang } from "./resolve-parser.js";
|
||||
/** Normalize parserOptions */
|
||||
export function normalizeParserOptions(options) {
|
||||
const parserOptions = {
|
||||
ecmaVersion: 2024,
|
||||
sourceType: "module",
|
||||
loc: true,
|
||||
range: true,
|
||||
raw: true,
|
||||
tokens: true,
|
||||
comment: true,
|
||||
eslintVisitorKeys: true,
|
||||
eslintScopeManager: true,
|
||||
...(options || {}),
|
||||
};
|
||||
parserOptions.sourceType = "module";
|
||||
if (parserOptions.ecmaVersion <= 5 || parserOptions.ecmaVersion == null) {
|
||||
parserOptions.ecmaVersion = 2015;
|
||||
}
|
||||
return parserOptions;
|
||||
}
|
||||
const TS_PARSER_NAMES = [
|
||||
"@typescript-eslint/parser",
|
||||
"typescript-eslint-parser-for-extra-files",
|
||||
];
|
||||
export function isTypeScript(parserOptions, lang) {
|
||||
const parserValue = getParserForLang(lang, parserOptions?.parser);
|
||||
if (typeof parserValue !== "string") {
|
||||
return (maybeTSESLintParserObject(parserValue) ||
|
||||
isTSESLintParserObject(parserValue));
|
||||
}
|
||||
const parserName = parserValue;
|
||||
if (TS_PARSER_NAMES.includes(parserName)) {
|
||||
return true;
|
||||
}
|
||||
if (TS_PARSER_NAMES.some((nm) => parserName.includes(nm))) {
|
||||
let targetPath = parserName;
|
||||
while (targetPath) {
|
||||
const pkgPath = path.join(targetPath, "package.json");
|
||||
if (fs.existsSync(pkgPath)) {
|
||||
try {
|
||||
return TS_PARSER_NAMES.includes(JSON.parse(fs.readFileSync(pkgPath, "utf-8"))?.name);
|
||||
}
|
||||
catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
const parent = path.dirname(targetPath);
|
||||
if (targetPath === parent) {
|
||||
break;
|
||||
}
|
||||
targetPath = parent;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
/**
|
||||
* Remove typing-related options from parser options.
|
||||
*
|
||||
* Allows the typescript-eslint parser to parse a file without
|
||||
* trying to collect typing information from TypeScript.
|
||||
*
|
||||
* See https://typescript-eslint.io/packages/parser#withoutprojectparseroptionsparseroptions
|
||||
*/
|
||||
export function withoutProjectParserOptions(options) {
|
||||
const { project: _strippedProject, programs: _strippedPrograms, projectService: _strippedProjectService, EXPERIMENTAL_useProjectService: _strippedExperimentalUseProjectService, ...result } = options;
|
||||
return result;
|
||||
}
|
||||
6
node_modules/svelte-eslint-parser/lib/parser/resolve-parser.d.ts
generated
vendored
Normal file
6
node_modules/svelte-eslint-parser/lib/parser/resolve-parser.d.ts
generated
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
import type { ParserObject } from "./parser-object.js";
|
||||
export type UserOptionParser = string | ParserObject | Record<string, string | ParserObject | undefined> | undefined;
|
||||
/** Get parser for script lang */
|
||||
export declare function getParserForLang(lang: string | undefined | null, parser: UserOptionParser): string | ParserObject;
|
||||
/** Get parser */
|
||||
export declare function getParser(attrs: Record<string, string | undefined>, parser: UserOptionParser): ParserObject;
|
||||
30
node_modules/svelte-eslint-parser/lib/parser/resolve-parser.js
generated
vendored
Normal file
30
node_modules/svelte-eslint-parser/lib/parser/resolve-parser.js
generated
vendored
Normal file
@@ -0,0 +1,30 @@
|
||||
import { getEspree } from "./espree.js";
|
||||
import { isParserObject } from "./parser-object.js";
|
||||
import Module from "module";
|
||||
/** Get parser for script lang */
|
||||
export function getParserForLang(lang, parser) {
|
||||
if (parser) {
|
||||
if (typeof parser === "string" || isParserObject(parser)) {
|
||||
return parser;
|
||||
}
|
||||
if (typeof parser === "object") {
|
||||
const value = parser[lang || "js"];
|
||||
if (typeof value === "string" || isParserObject(value)) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
}
|
||||
return "espree";
|
||||
}
|
||||
/** Get parser */
|
||||
export function getParser(attrs, parser) {
|
||||
const parserValue = getParserForLang(attrs.lang, parser);
|
||||
if (isParserObject(parserValue)) {
|
||||
return parserValue;
|
||||
}
|
||||
if (parserValue !== "espree") {
|
||||
const require = Module.createRequire(import.meta.url);
|
||||
return require(parserValue);
|
||||
}
|
||||
return getEspree();
|
||||
}
|
||||
14
node_modules/svelte-eslint-parser/lib/parser/script.d.ts
generated
vendored
Normal file
14
node_modules/svelte-eslint-parser/lib/parser/script.d.ts
generated
vendored
Normal file
@@ -0,0 +1,14 @@
|
||||
import type { ESLintExtendedProgram } from "./index.js";
|
||||
import type { NormalizedParserOptions } from "./parser-options.js";
|
||||
/**
|
||||
* Parse for <script>
|
||||
*/
|
||||
export declare function parseScriptInSvelte(code: string, attrs: Record<string, string | undefined>, parserOptions: NormalizedParserOptions): ESLintExtendedProgram;
|
||||
/**
|
||||
* Parse for script
|
||||
*/
|
||||
export declare function parseScript(code: string, attrs: Record<string, string | undefined>, parserOptions: NormalizedParserOptions): ESLintExtendedProgram;
|
||||
/**
|
||||
* Parse for script without analyze scope
|
||||
*/
|
||||
export declare function parseScriptWithoutAnalyzeScope(code: string, attrs: Record<string, string | undefined>, options: NormalizedParserOptions): ESLintExtendedProgram;
|
||||
58
node_modules/svelte-eslint-parser/lib/parser/script.js
generated
vendored
Normal file
58
node_modules/svelte-eslint-parser/lib/parser/script.js
generated
vendored
Normal file
@@ -0,0 +1,58 @@
|
||||
import { analyzeScope } from "./analyze-scope.js";
|
||||
import { traverseNodes } from "../traverse.js";
|
||||
import { getParser } from "./resolve-parser.js";
|
||||
import { isEnhancedParserObject } from "./parser-object.js";
|
||||
/**
|
||||
* Parse for <script>
|
||||
*/
|
||||
export function parseScriptInSvelte(code, attrs, parserOptions) {
|
||||
const result = parseScript(code, attrs, parserOptions);
|
||||
traverseNodes(result.ast, {
|
||||
visitorKeys: result.visitorKeys,
|
||||
enterNode(node, parent) {
|
||||
node.parent = parent;
|
||||
if (node.type === "LabeledStatement" && node.label.name === "$") {
|
||||
if (parent?.type === "Program") {
|
||||
// Transform node type
|
||||
node.type = "SvelteReactiveStatement";
|
||||
}
|
||||
}
|
||||
},
|
||||
leaveNode() {
|
||||
//
|
||||
},
|
||||
});
|
||||
return result;
|
||||
}
|
||||
/**
|
||||
* Parse for script
|
||||
*/
|
||||
export function parseScript(code, attrs, parserOptions) {
|
||||
const result = parseScriptWithoutAnalyzeScopeFromVCode(code, attrs, parserOptions);
|
||||
if (!result.scopeManager) {
|
||||
const scopeManager = analyzeScope(result.ast, parserOptions);
|
||||
result.scopeManager = scopeManager;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
/**
|
||||
* Parse for script without analyze scope
|
||||
*/
|
||||
export function parseScriptWithoutAnalyzeScope(code, attrs, options) {
|
||||
const parser = getParser(attrs, options.parser);
|
||||
const result = isEnhancedParserObject(parser)
|
||||
? parser.parseForESLint(code, options)
|
||||
: parser.parse(code, options);
|
||||
if ("ast" in result && result.ast != null) {
|
||||
return result;
|
||||
}
|
||||
return { ast: result };
|
||||
}
|
||||
/**
|
||||
* Parse for script without analyze scope
|
||||
*/
|
||||
function parseScriptWithoutAnalyzeScopeFromVCode(code, attrs, options) {
|
||||
const result = parseScriptWithoutAnalyzeScope(code, attrs, options);
|
||||
result._virtualScriptCode = code;
|
||||
return result;
|
||||
}
|
||||
6
node_modules/svelte-eslint-parser/lib/parser/sort.d.ts
generated
vendored
Normal file
6
node_modules/svelte-eslint-parser/lib/parser/sort.d.ts
generated
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
/**
|
||||
* Sort tokens
|
||||
*/
|
||||
export declare function sortNodes<T extends {
|
||||
range: [number, number];
|
||||
}>(tokens: T[] | null | undefined): T[];
|
||||
14
node_modules/svelte-eslint-parser/lib/parser/sort.js
generated
vendored
Normal file
14
node_modules/svelte-eslint-parser/lib/parser/sort.js
generated
vendored
Normal file
@@ -0,0 +1,14 @@
|
||||
/**
|
||||
* Sort tokens
|
||||
*/
|
||||
export function sortNodes(tokens) {
|
||||
if (!tokens) {
|
||||
return [];
|
||||
}
|
||||
return tokens.sort((a, b) => {
|
||||
if (a.range[0] !== b.range[0]) {
|
||||
return a.range[0] - b.range[0];
|
||||
}
|
||||
return a.range[1] - b.range[1];
|
||||
});
|
||||
}
|
||||
42
node_modules/svelte-eslint-parser/lib/parser/style-context.d.ts
generated
vendored
Normal file
42
node_modules/svelte-eslint-parser/lib/parser/style-context.d.ts
generated
vendored
Normal file
@@ -0,0 +1,42 @@
|
||||
import type { Node, Root, Rule } from "postcss";
|
||||
import { type Node as SelectorNode, type Root as SelectorRoot } from "postcss-selector-parser";
|
||||
import type { Context } from "../context/index.js";
|
||||
import type { SourceLocation, SvelteStyleElement } from "../ast/index.js";
|
||||
export type StyleContext = StyleContextNoStyleElement | StyleContextParseError | StyleContextSuccess | StyleContextUnknownLang;
|
||||
export interface StyleContextNoStyleElement {
|
||||
status: "no-style-element";
|
||||
}
|
||||
export interface StyleContextParseError {
|
||||
status: "parse-error";
|
||||
sourceLang: string;
|
||||
error: Error;
|
||||
}
|
||||
export interface StyleContextSuccess {
|
||||
status: "success";
|
||||
sourceLang: string;
|
||||
sourceAst: Root;
|
||||
}
|
||||
export interface StyleContextUnknownLang {
|
||||
status: "unknown-lang";
|
||||
sourceLang: string;
|
||||
}
|
||||
/**
|
||||
* Extracts style source from a SvelteStyleElement and parses it into a PostCSS AST.
|
||||
*/
|
||||
export declare function parseStyleContext(styleElement: SvelteStyleElement | undefined, ctx: Context): StyleContext;
|
||||
/**
|
||||
* Parses a PostCSS Rule node's selector and returns its AST.
|
||||
*/
|
||||
export declare function parseSelector(rule: Rule): SelectorRoot;
|
||||
/**
|
||||
* Extracts a node location (like that of any ESLint node) from a parsed svelte style node.
|
||||
*/
|
||||
export declare function styleNodeLoc(node: Node): Partial<SourceLocation>;
|
||||
/**
|
||||
* Extracts a node range (like that of any ESLint node) from a parsed svelte style node.
|
||||
*/
|
||||
export declare function styleNodeRange(node: Node): [number | undefined, number | undefined];
|
||||
/**
|
||||
* Extracts a node location (like that of any ESLint node) from a parsed svelte selector node.
|
||||
*/
|
||||
export declare function styleSelectorNodeLoc(node: SelectorNode): Partial<SourceLocation>;
|
||||
156
node_modules/svelte-eslint-parser/lib/parser/style-context.js
generated
vendored
Normal file
156
node_modules/svelte-eslint-parser/lib/parser/style-context.js
generated
vendored
Normal file
@@ -0,0 +1,156 @@
|
||||
import postcss from "postcss";
|
||||
import { parse as SCSSparse } from "postcss-scss";
|
||||
import { default as selectorParser, } from "postcss-selector-parser";
|
||||
/**
|
||||
* Extracts style source from a SvelteStyleElement and parses it into a PostCSS AST.
|
||||
*/
|
||||
export function parseStyleContext(styleElement, ctx) {
|
||||
if (!styleElement || !styleElement.endTag) {
|
||||
return { status: "no-style-element" };
|
||||
}
|
||||
let sourceLang = "css";
|
||||
for (const attribute of styleElement.startTag.attributes) {
|
||||
if (attribute.type === "SvelteAttribute" &&
|
||||
attribute.key.name === "lang" &&
|
||||
attribute.value.length > 0 &&
|
||||
attribute.value[0].type === "SvelteLiteral") {
|
||||
sourceLang = attribute.value[0].value;
|
||||
}
|
||||
}
|
||||
let parseFn, sourceAst;
|
||||
switch (sourceLang) {
|
||||
case "css":
|
||||
case "postcss":
|
||||
parseFn = postcss.parse;
|
||||
break;
|
||||
case "scss":
|
||||
parseFn = SCSSparse;
|
||||
break;
|
||||
default:
|
||||
return { status: "unknown-lang", sourceLang };
|
||||
}
|
||||
const styleCode = ctx.code.slice(styleElement.startTag.range[1], styleElement.endTag.range[0]);
|
||||
try {
|
||||
sourceAst = parseFn(styleCode, {
|
||||
from: ctx.parserOptions.filePath,
|
||||
});
|
||||
}
|
||||
catch (error) {
|
||||
return { status: "parse-error", sourceLang, error: error };
|
||||
}
|
||||
fixPostCSSNodeLocation(sourceAst, styleElement);
|
||||
sourceAst.walk((node) => {
|
||||
fixPostCSSNodeLocation(node, styleElement);
|
||||
});
|
||||
return { status: "success", sourceLang, sourceAst };
|
||||
}
|
||||
/**
|
||||
* Parses a PostCSS Rule node's selector and returns its AST.
|
||||
*/
|
||||
export function parseSelector(rule) {
|
||||
const processor = selectorParser();
|
||||
const root = processor.astSync(rule.selector);
|
||||
fixSelectorNodeLocation(root, rule);
|
||||
root.walk((node) => {
|
||||
fixSelectorNodeLocation(node, rule);
|
||||
});
|
||||
return root;
|
||||
}
|
||||
/**
|
||||
* Extracts a node location (like that of any ESLint node) from a parsed svelte style node.
|
||||
*/
|
||||
export function styleNodeLoc(node) {
|
||||
if (node.source === undefined) {
|
||||
return {};
|
||||
}
|
||||
return {
|
||||
start: node.source.start !== undefined
|
||||
? {
|
||||
line: node.source.start.line,
|
||||
column: node.source.start.column - 1,
|
||||
}
|
||||
: undefined,
|
||||
end: node.source.end !== undefined
|
||||
? {
|
||||
line: node.source.end.line,
|
||||
column: node.source.end.column,
|
||||
}
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Extracts a node range (like that of any ESLint node) from a parsed svelte style node.
|
||||
*/
|
||||
export function styleNodeRange(node) {
|
||||
if (node.source === undefined) {
|
||||
return [undefined, undefined];
|
||||
}
|
||||
return [
|
||||
node.source.start !== undefined ? node.source.start.offset : undefined,
|
||||
node.source.end !== undefined ? node.source.end.offset + 1 : undefined,
|
||||
];
|
||||
}
|
||||
/**
|
||||
* Extracts a node location (like that of any ESLint node) from a parsed svelte selector node.
|
||||
*/
|
||||
export function styleSelectorNodeLoc(node) {
|
||||
return {
|
||||
start: node.source?.start !== undefined
|
||||
? {
|
||||
line: node.source.start.line,
|
||||
column: node.source.start.column - 1,
|
||||
}
|
||||
: undefined,
|
||||
end: node.source?.end,
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Fixes PostCSS AST locations to be relative to the whole file instead of relative to the <style> element.
|
||||
*/
|
||||
function fixPostCSSNodeLocation(node, styleElement) {
|
||||
if (node.source?.start?.offset !== undefined) {
|
||||
node.source.start.offset += styleElement.startTag.range[1];
|
||||
}
|
||||
if (node.source?.start?.line !== undefined) {
|
||||
node.source.start.line += styleElement.loc.start.line - 1;
|
||||
}
|
||||
if (node.source?.end?.offset !== undefined) {
|
||||
node.source.end.offset += styleElement.startTag.range[1];
|
||||
}
|
||||
if (node.source?.end?.line !== undefined) {
|
||||
node.source.end.line += styleElement.loc.start.line - 1;
|
||||
}
|
||||
if (node.source?.start?.line === styleElement.loc.start.line) {
|
||||
node.source.start.column += styleElement.startTag.loc.end.column;
|
||||
}
|
||||
if (node.source?.end?.line === styleElement.loc.start.line) {
|
||||
node.source.end.column += styleElement.startTag.loc.end.column;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Fixes selector AST locations to be relative to the whole file instead of relative to their parent rule.
|
||||
*/
|
||||
function fixSelectorNodeLocation(node, rule) {
|
||||
if (node.source === undefined) {
|
||||
return;
|
||||
}
|
||||
const ruleLoc = styleNodeLoc(rule);
|
||||
if (node.source.start !== undefined && ruleLoc.start !== undefined) {
|
||||
if (node.source.start.line === 1) {
|
||||
node.source.start.column += ruleLoc.start.column;
|
||||
}
|
||||
node.source.start.line += ruleLoc.start.line - 1;
|
||||
}
|
||||
else {
|
||||
node.source.start = undefined;
|
||||
}
|
||||
if (node.source.end !== undefined && ruleLoc.start !== undefined) {
|
||||
if (node.source.end.line === 1) {
|
||||
node.source.end.column += ruleLoc.start.column;
|
||||
}
|
||||
node.source.end.line += ruleLoc.start.line - 1;
|
||||
}
|
||||
else {
|
||||
node.source.end = undefined;
|
||||
}
|
||||
}
|
||||
47
node_modules/svelte-eslint-parser/lib/parser/svelte-ast-types-for-v5.d.ts
generated
vendored
Normal file
47
node_modules/svelte-eslint-parser/lib/parser/svelte-ast-types-for-v5.d.ts
generated
vendored
Normal file
@@ -0,0 +1,47 @@
|
||||
import type { AST } from "svelte/compiler";
|
||||
export type Root = AST.Root;
|
||||
export type Fragment = AST.Fragment;
|
||||
export type SvelteOptions = AST.SvelteOptions;
|
||||
export type Script = AST.Script;
|
||||
export type Text = AST.Text;
|
||||
export type ExpressionTag = AST.ExpressionTag;
|
||||
export type HtmlTag = AST.HtmlTag;
|
||||
export type ConstTag = AST.ConstTag;
|
||||
export type DeclarationTag = AST.DeclarationTag;
|
||||
export type DebugTag = AST.DebugTag;
|
||||
export type RenderTag = AST.RenderTag;
|
||||
export type Component = AST.Component;
|
||||
export type TitleElement = AST.TitleElement;
|
||||
export type SlotElement = AST.SlotElement;
|
||||
export type RegularElement = AST.RegularElement;
|
||||
export type SvelteBody = AST.SvelteBody;
|
||||
export type SvelteComponent = AST.SvelteComponent;
|
||||
export type SvelteDocument = AST.SvelteDocument;
|
||||
export type SvelteElement = AST.SvelteElement;
|
||||
export type SvelteFragment = AST.SvelteFragment;
|
||||
export type SvelteHead = AST.SvelteHead;
|
||||
export type SvelteOptionsRaw = AST.SvelteOptionsRaw;
|
||||
export type SvelteSelf = AST.SvelteSelf;
|
||||
export type SvelteWindow = AST.SvelteWindow;
|
||||
export type SvelteBoundary = AST.SvelteBoundary;
|
||||
export type IfBlock = AST.IfBlock;
|
||||
export type EachBlock = AST.EachBlock;
|
||||
export type AwaitBlock = AST.AwaitBlock;
|
||||
export type KeyBlock = AST.KeyBlock;
|
||||
export type SnippetBlock = AST.SnippetBlock;
|
||||
export type Comment = AST.Comment;
|
||||
export type Attribute = AST.Attribute;
|
||||
export type SpreadAttribute = AST.SpreadAttribute;
|
||||
export type AttachTag = AST.AttachTag;
|
||||
export type AnimateDirective = AST.AnimateDirective;
|
||||
export type BindDirective = AST.BindDirective;
|
||||
export type ClassDirective = AST.ClassDirective;
|
||||
export type LetDirective = AST.LetDirective;
|
||||
export type OnDirective = AST.OnDirective;
|
||||
export type StyleDirective = AST.StyleDirective;
|
||||
export type TransitionDirective = AST.TransitionDirective;
|
||||
export type UseDirective = AST.UseDirective;
|
||||
export type Tag = ExpressionTag | HtmlTag | ConstTag | DeclarationTag | DebugTag | RenderTag;
|
||||
export type ElementLike = Component | TitleElement | SlotElement | RegularElement | SvelteBody | SvelteComponent | SvelteDocument | SvelteElement | SvelteFragment | SvelteHead | SvelteOptionsRaw | SvelteSelf | SvelteWindow | SvelteBoundary;
|
||||
export type Block = EachBlock | IfBlock | AwaitBlock | KeyBlock | SnippetBlock;
|
||||
export type Directive = AnimateDirective | BindDirective | ClassDirective | LetDirective | OnDirective | StyleDirective | TransitionDirective | UseDirective;
|
||||
1
node_modules/svelte-eslint-parser/lib/parser/svelte-ast-types-for-v5.js
generated
vendored
Normal file
1
node_modules/svelte-eslint-parser/lib/parser/svelte-ast-types-for-v5.js
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
export {};
|
||||
213
node_modules/svelte-eslint-parser/lib/parser/svelte-ast-types.d.ts
generated
vendored
Normal file
213
node_modules/svelte-eslint-parser/lib/parser/svelte-ast-types.d.ts
generated
vendored
Normal file
@@ -0,0 +1,213 @@
|
||||
import type ESTree from "estree";
|
||||
interface BaseNode {
|
||||
start: number;
|
||||
end: number;
|
||||
}
|
||||
export interface AstLegacy {
|
||||
html?: Fragment;
|
||||
css?: Style;
|
||||
instance?: Script;
|
||||
module?: Script;
|
||||
}
|
||||
export declare type TemplateNode = Text | MustacheTag | RawMustacheTag | DebugTag | ConstTag | Directive | StyleDirective | Element | InlineComponent | Window | Document | Body | Head | Title | Options | SlotTemplate | Slot | Comment | IfBlock | EachBlock | AwaitBlock | KeyBlock;
|
||||
export interface Fragment extends BaseNode {
|
||||
type: "Fragment";
|
||||
children: TemplateNode[];
|
||||
}
|
||||
export interface Text extends BaseNode {
|
||||
type: "Text";
|
||||
data: string;
|
||||
}
|
||||
export interface MustacheTag extends BaseNode {
|
||||
type: "MustacheTag";
|
||||
expression: ESTree.Expression;
|
||||
}
|
||||
export interface RawMustacheTag extends BaseNode {
|
||||
type: "RawMustacheTag";
|
||||
expression: ESTree.Expression;
|
||||
}
|
||||
export interface DebugTag extends BaseNode {
|
||||
type: "DebugTag";
|
||||
identifiers: ESTree.Identifier[];
|
||||
}
|
||||
export interface ConstTag extends BaseNode {
|
||||
type: "ConstTag";
|
||||
expression: ESTree.AssignmentExpression;
|
||||
}
|
||||
export interface IfBlock extends BaseNode {
|
||||
type: "IfBlock";
|
||||
expression: ESTree.Expression;
|
||||
children: TemplateNode[];
|
||||
else: ElseBlock | undefined;
|
||||
elseif: true | undefined;
|
||||
}
|
||||
export interface ElseBlock extends BaseNode {
|
||||
type: "ElseBlock";
|
||||
children: TemplateNode[] | [IfBlock & {
|
||||
elseif: true;
|
||||
}];
|
||||
}
|
||||
export interface EachBlock extends BaseNode {
|
||||
type: "EachBlock";
|
||||
expression: ESTree.Expression;
|
||||
context: ESTree.Pattern;
|
||||
index?: string;
|
||||
key: ESTree.Expression | undefined;
|
||||
children: TemplateNode[];
|
||||
else: ElseBlock | undefined;
|
||||
}
|
||||
export interface AwaitBlock extends BaseNode {
|
||||
type: "AwaitBlock";
|
||||
expression: ESTree.Expression;
|
||||
pending: PendingBlock;
|
||||
value: ESTree.Pattern | null;
|
||||
then: ThenBlock;
|
||||
error: ESTree.Pattern | null;
|
||||
catch: CatchBlock;
|
||||
}
|
||||
export interface PendingBlock extends BaseNode {
|
||||
type: "PendingBlock";
|
||||
skip: boolean;
|
||||
children: TemplateNode[];
|
||||
}
|
||||
export interface ThenBlock extends BaseNode {
|
||||
type: "ThenBlock";
|
||||
skip: boolean;
|
||||
children: TemplateNode[];
|
||||
}
|
||||
export interface CatchBlock extends BaseNode {
|
||||
type: "CatchBlock";
|
||||
skip: boolean;
|
||||
children: TemplateNode[];
|
||||
}
|
||||
export interface KeyBlock extends BaseNode {
|
||||
type: "KeyBlock";
|
||||
expression: ESTree.Expression;
|
||||
children: TemplateNode[];
|
||||
}
|
||||
export interface BaseElement extends BaseNode {
|
||||
type: "Element";
|
||||
name: string;
|
||||
children: TemplateNode[];
|
||||
attributes: AttributeOrDirective[];
|
||||
}
|
||||
export interface BasicElement extends BaseElement {
|
||||
tag?: undefined;
|
||||
}
|
||||
export interface SvelteElement extends BaseElement {
|
||||
name: "svelte:element";
|
||||
tag: ESTree.Expression | string;
|
||||
}
|
||||
export type Element = BasicElement | SvelteElement;
|
||||
export interface BaseInlineComponent extends BaseNode {
|
||||
type: "InlineComponent";
|
||||
name: string;
|
||||
children: TemplateNode[];
|
||||
attributes: AttributeOrDirective[];
|
||||
}
|
||||
export interface Window extends BaseNode {
|
||||
type: "Window";
|
||||
name: "svelte:window";
|
||||
children: TemplateNode[];
|
||||
attributes: AttributeOrDirective[];
|
||||
}
|
||||
export interface Document extends BaseNode {
|
||||
type: "Document";
|
||||
name: "svelte:document";
|
||||
children: TemplateNode[];
|
||||
attributes: AttributeOrDirective[];
|
||||
}
|
||||
export interface Body extends BaseNode {
|
||||
type: "Body";
|
||||
name: "svelte:body";
|
||||
children: TemplateNode[];
|
||||
attributes: AttributeOrDirective[];
|
||||
}
|
||||
export interface Head extends BaseNode {
|
||||
type: "Head";
|
||||
name: "svelte:head";
|
||||
children: TemplateNode[];
|
||||
attributes: AttributeOrDirective[];
|
||||
}
|
||||
export interface Title extends BaseNode {
|
||||
type: "Title";
|
||||
name: "title";
|
||||
children: TemplateNode[];
|
||||
attributes: AttributeOrDirective[];
|
||||
}
|
||||
export interface Options extends BaseNode {
|
||||
type: "Options";
|
||||
name: "svelte:options";
|
||||
children?: TemplateNode[];
|
||||
attributes: AttributeOrDirective[];
|
||||
}
|
||||
export interface SlotTemplate extends BaseNode {
|
||||
type: "SlotTemplate";
|
||||
name: "svelte:fragment";
|
||||
children: TemplateNode[];
|
||||
attributes: AttributeOrDirective[];
|
||||
}
|
||||
export interface BasicInlineComponent extends BaseInlineComponent {
|
||||
expression?: undefined;
|
||||
}
|
||||
export interface InlineSvelteComponent extends BaseInlineComponent {
|
||||
name: "svelte:component";
|
||||
expression: ESTree.Expression;
|
||||
}
|
||||
export type InlineComponent = BasicInlineComponent | InlineSvelteComponent;
|
||||
export interface Slot extends BaseNode {
|
||||
type: "Slot";
|
||||
name: "slot";
|
||||
children: TemplateNode[];
|
||||
attributes: AttributeOrDirective[];
|
||||
}
|
||||
export interface Comment extends BaseNode {
|
||||
type: "Comment";
|
||||
data: string;
|
||||
}
|
||||
export interface Attribute extends BaseNode {
|
||||
type: "Attribute";
|
||||
name: string;
|
||||
value: (Text | MustacheTag)[] | [AttributeShorthand] | true;
|
||||
}
|
||||
export interface Spread extends BaseNode {
|
||||
type: "Spread";
|
||||
expression: ESTree.Expression;
|
||||
}
|
||||
export interface AttributeShorthand extends BaseNode {
|
||||
type: "AttributeShorthand";
|
||||
expression: ESTree.Identifier;
|
||||
}
|
||||
export type AttributeOrDirective = Attribute | Spread | Directive | StyleDirective;
|
||||
interface BaseDirective extends BaseNode {
|
||||
name: string;
|
||||
modifiers: string[];
|
||||
}
|
||||
export interface DirectiveForExpression extends BaseDirective {
|
||||
type: "Action" | "Animation" | "Binding" | "Class" | "EventHandler" | "Ref";
|
||||
expression: null | ESTree.Expression;
|
||||
}
|
||||
export interface LetDirective extends BaseDirective {
|
||||
type: "Let";
|
||||
expression: null | ESTree.Pattern;
|
||||
}
|
||||
export interface TransitionDirective extends BaseDirective {
|
||||
type: "Transition";
|
||||
intro: boolean;
|
||||
outro: boolean;
|
||||
expression: null | ESTree.Expression;
|
||||
}
|
||||
export interface StyleDirective extends BaseDirective {
|
||||
type: "StyleDirective";
|
||||
value: (Text | MustacheTag)[] | true;
|
||||
}
|
||||
export type Directive = DirectiveForExpression | TransitionDirective | LetDirective;
|
||||
export interface Script extends BaseNode {
|
||||
type: "Script";
|
||||
context: string;
|
||||
children: TemplateNode[];
|
||||
}
|
||||
export interface Style extends BaseNode {
|
||||
type: "Style";
|
||||
}
|
||||
export {};
|
||||
1
node_modules/svelte-eslint-parser/lib/parser/svelte-ast-types.js
generated
vendored
Normal file
1
node_modules/svelte-eslint-parser/lib/parser/svelte-ast-types.js
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
export {};
|
||||
26
node_modules/svelte-eslint-parser/lib/parser/svelte-parse-context.d.ts
generated
vendored
Normal file
26
node_modules/svelte-eslint-parser/lib/parser/svelte-parse-context.d.ts
generated
vendored
Normal file
@@ -0,0 +1,26 @@
|
||||
import type * as Compiler from "./svelte-ast-types-for-v5.js";
|
||||
import type * as SvAST from "./svelte-ast-types.js";
|
||||
import type { NormalizedParserOptions } from "./parser-options.js";
|
||||
import type { SvelteConfig } from "../svelte-config/index.js";
|
||||
import type { ESLintProgram } from "./index.js";
|
||||
/** The context for parsing. */
|
||||
export type SvelteParseContext = {
|
||||
/**
|
||||
* Determines if the file is in Runes mode.
|
||||
*
|
||||
* - Svelte 3/4 does not support Runes mode.
|
||||
* - Checks if `runes` configuration exists in:
|
||||
* - `parserOptions`
|
||||
* - `svelte.config.js`
|
||||
* - `<svelte:options>` in the Svelte file.
|
||||
* - Returns `true` if the `runes` symbol is present in the Svelte file.
|
||||
*/
|
||||
runes?: boolean;
|
||||
/** The version of "svelte/compiler". */
|
||||
compilerVersion: string;
|
||||
/** The result of static analysis of `svelte.config.js`. */
|
||||
svelteConfig: SvelteConfig | null;
|
||||
};
|
||||
export declare function resolveSvelteParseContextForSvelte(svelteConfig: SvelteConfig | null, parserOptions: NormalizedParserOptions, svelteAst: Compiler.Root | SvAST.AstLegacy): SvelteParseContext;
|
||||
export declare function resolveSvelteParseContextForSvelteScript(svelteConfig: SvelteConfig | null): SvelteParseContext;
|
||||
export declare function hasRunesSymbol(ast: ESLintProgram): boolean;
|
||||
66
node_modules/svelte-eslint-parser/lib/parser/svelte-parse-context.js
generated
vendored
Normal file
66
node_modules/svelte-eslint-parser/lib/parser/svelte-parse-context.js
generated
vendored
Normal file
@@ -0,0 +1,66 @@
|
||||
import { compilerVersion, svelteVersion } from "./svelte-version.js";
|
||||
import { traverseNodes } from "../traverse.js";
|
||||
const runeSymbols = [
|
||||
"$state",
|
||||
"$derived",
|
||||
"$effect",
|
||||
"$props",
|
||||
"$bindable",
|
||||
"$inspect",
|
||||
"$host",
|
||||
];
|
||||
export function resolveSvelteParseContextForSvelte(svelteConfig, parserOptions, svelteAst) {
|
||||
return {
|
||||
runes: isRunesAsParseContext(svelteConfig, parserOptions, svelteAst),
|
||||
compilerVersion,
|
||||
svelteConfig,
|
||||
};
|
||||
}
|
||||
export function resolveSvelteParseContextForSvelteScript(svelteConfig) {
|
||||
return {
|
||||
// .svelte.js files are always in Runes mode for Svelte 5.
|
||||
runes: svelteVersion.gte(5),
|
||||
compilerVersion,
|
||||
svelteConfig,
|
||||
};
|
||||
}
|
||||
function isRunesAsParseContext(svelteConfig, parserOptions, svelteAst) {
|
||||
// Svelte 3/4 does not support Runes mode.
|
||||
if (!svelteVersion.gte(5)) {
|
||||
return false;
|
||||
}
|
||||
// Compiler option.
|
||||
if (parserOptions.svelteFeatures?.runes != null) {
|
||||
return parserOptions.svelteFeatures?.runes;
|
||||
}
|
||||
if (svelteConfig?.compilerOptions?.runes != null) {
|
||||
return typeof svelteConfig.compilerOptions?.runes === "function"
|
||||
? svelteConfig.compilerOptions.runes({
|
||||
filename: parserOptions.filePath ?? "",
|
||||
})
|
||||
: svelteConfig.compilerOptions?.runes;
|
||||
}
|
||||
// `<svelte:options>`.
|
||||
const svelteOptions = svelteAst.options;
|
||||
if (svelteOptions?.runes != null) {
|
||||
return svelteOptions?.runes;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
export function hasRunesSymbol(ast) {
|
||||
let hasRuneSymbol = false;
|
||||
traverseNodes(ast, {
|
||||
enterNode(node) {
|
||||
if (hasRuneSymbol) {
|
||||
return;
|
||||
}
|
||||
if (node.type === "Identifier" && runeSymbols.includes(node.name)) {
|
||||
hasRuneSymbol = true;
|
||||
}
|
||||
},
|
||||
leaveNode() {
|
||||
// do nothing
|
||||
},
|
||||
});
|
||||
return hasRuneSymbol;
|
||||
}
|
||||
6
node_modules/svelte-eslint-parser/lib/parser/svelte-to-virtual-ts.d.ts
generated
vendored
Normal file
6
node_modules/svelte-eslint-parser/lib/parser/svelte-to-virtual-ts.d.ts
generated
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
import type { NormalizedParserOptions } from "./parser-options.js";
|
||||
/**
|
||||
* Translate a Svelte component to the virtual TypeScript shim. Returns
|
||||
* `null` if the configured script parser is not TypeScript or parsing fails.
|
||||
*/
|
||||
export declare function svelteToVirtualTypeScript(filePath: string, content: string, parserOptions: NormalizedParserOptions): string | null;
|
||||
43
node_modules/svelte-eslint-parser/lib/parser/svelte-to-virtual-ts.js
generated
vendored
Normal file
43
node_modules/svelte-eslint-parser/lib/parser/svelte-to-virtual-ts.js
generated
vendored
Normal file
@@ -0,0 +1,43 @@
|
||||
import { Context } from "../context/index.js";
|
||||
import { resolveSvelteConfigFromOption } from "../svelte-config/index.js";
|
||||
import { parseTemplate } from "./template.js";
|
||||
import { analyzeTypeScriptInSvelte } from "./typescript/analyze/index.js";
|
||||
import { resolveSvelteParseContextForSvelte } from "./svelte-parse-context.js";
|
||||
import { getInstanceScriptRange } from "./compat.js";
|
||||
/**
|
||||
* Translate a Svelte component to the virtual TypeScript shim. Returns
|
||||
* `null` if the configured script parser is not TypeScript or parsing fails.
|
||||
*/
|
||||
export function svelteToVirtualTypeScript(filePath, content, parserOptions) {
|
||||
try {
|
||||
// Drop `project` / `projectService`: we're already inside
|
||||
// `@typescript-eslint/parser`'s stack via the `ts.sys` hook, and a nested
|
||||
// analyzer trying to spin up its own program would deadlock or recurse.
|
||||
const inner = {
|
||||
...parserOptions,
|
||||
filePath,
|
||||
project: null,
|
||||
projectService: undefined,
|
||||
EXPERIMENTAL_useProjectService: undefined,
|
||||
};
|
||||
const ctx = new Context(content, inner);
|
||||
if (!ctx.isTypeScript())
|
||||
return null;
|
||||
const template = parseTemplate(ctx.sourceCode.template, ctx, inner);
|
||||
const svelteConfig = resolveSvelteConfigFromOption({
|
||||
...parserOptions,
|
||||
filePath,
|
||||
});
|
||||
const svelteParseContext = resolveSvelteParseContextForSvelte(svelteConfig, inner, template.svelteAst);
|
||||
const scripts = ctx.sourceCode.scripts;
|
||||
const tsCtx = analyzeTypeScriptInSvelte(scripts.getCurrentVirtualCodeInfo(), scripts.attrs, inner, {
|
||||
slots: ctx.slots,
|
||||
svelteParseContext,
|
||||
instanceScriptRange: getInstanceScriptRange(template.svelteAst),
|
||||
});
|
||||
return tsCtx.script;
|
||||
}
|
||||
catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
5
node_modules/svelte-eslint-parser/lib/parser/svelte-version.d.ts
generated
vendored
Normal file
5
node_modules/svelte-eslint-parser/lib/parser/svelte-version.d.ts
generated
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
import { VERSION as compilerVersion } from "svelte/compiler";
|
||||
export { compilerVersion };
|
||||
export declare const svelteVersion: {
|
||||
gte(v: number): boolean;
|
||||
};
|
||||
8
node_modules/svelte-eslint-parser/lib/parser/svelte-version.js
generated
vendored
Normal file
8
node_modules/svelte-eslint-parser/lib/parser/svelte-version.js
generated
vendored
Normal file
@@ -0,0 +1,8 @@
|
||||
import { VERSION as compilerVersion } from "svelte/compiler";
|
||||
export { compilerVersion };
|
||||
const verStrings = compilerVersion.split(".");
|
||||
export const svelteVersion = {
|
||||
gte(v) {
|
||||
return Number(verStrings[0]) >= v;
|
||||
},
|
||||
};
|
||||
12
node_modules/svelte-eslint-parser/lib/parser/template.d.ts
generated
vendored
Normal file
12
node_modules/svelte-eslint-parser/lib/parser/template.d.ts
generated
vendored
Normal file
@@ -0,0 +1,12 @@
|
||||
import type * as Compiler from "./svelte-ast-types-for-v5.js";
|
||||
import type * as SvAST from "./svelte-ast-types.js";
|
||||
import type { Context } from "../context/index.js";
|
||||
import type { SvelteProgram } from "../ast/index.js";
|
||||
import type { NormalizedParserOptions } from "./parser-options.js";
|
||||
/**
|
||||
* Parse for template
|
||||
*/
|
||||
export declare function parseTemplate(code: string, ctx: Context, parserOptions: NormalizedParserOptions): {
|
||||
ast: SvelteProgram;
|
||||
svelteAst: Compiler.Root | SvAST.AstLegacy;
|
||||
};
|
||||
34
node_modules/svelte-eslint-parser/lib/parser/template.js
generated
vendored
Normal file
34
node_modules/svelte-eslint-parser/lib/parser/template.js
generated
vendored
Normal file
@@ -0,0 +1,34 @@
|
||||
import { parse } from "svelte/compiler";
|
||||
import { convertSvelteRoot } from "./converts/index.js";
|
||||
import { ParseError } from "../errors.js";
|
||||
import { svelteVersion } from "./svelte-version.js";
|
||||
/**
|
||||
* Parse for template
|
||||
*/
|
||||
export function parseTemplate(code, ctx, parserOptions) {
|
||||
try {
|
||||
const options = {
|
||||
filename: parserOptions.filePath,
|
||||
...(svelteVersion.gte(5) ? { modern: true } : {}),
|
||||
};
|
||||
const svelteAst = parse(code, options);
|
||||
const ast = convertSvelteRoot(svelteAst, ctx);
|
||||
return {
|
||||
ast,
|
||||
svelteAst,
|
||||
};
|
||||
}
|
||||
catch (e) {
|
||||
if (typeof e.pos === "number") {
|
||||
const err = new ParseError(e.message, e.pos, ctx);
|
||||
err.svelteCompilerError = e;
|
||||
throw err;
|
||||
}
|
||||
if (Array.isArray(e.position) && typeof e.position[0] === "number") {
|
||||
const err = new ParseError(e.message, e.position[0], ctx);
|
||||
err.svelteCompilerError = e;
|
||||
throw err;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
13
node_modules/svelte-eslint-parser/lib/parser/typescript/analyze/component.d.ts
generated
vendored
Normal file
13
node_modules/svelte-eslint-parser/lib/parser/typescript/analyze/component.d.ts
generated
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
import type { VirtualTypeScriptContext } from "../context.js";
|
||||
import type { TSESParseForESLintResult } from "../types.js";
|
||||
import type { SvelteParseContext } from "../../svelte-parse-context.js";
|
||||
/**
|
||||
* Append a synthetic component `export default` so importers can resolve the
|
||||
* component's prop, event, and slot types.
|
||||
*
|
||||
* The export must carry both a value and a type meaning: `ComponentProps<typeof
|
||||
* Foo>` uses the value, while `ComponentEvents<Foo>` and Svelte-4-style
|
||||
* `ComponentProps<Foo>` use `Foo` as a type. A bare `export default <expr>` only
|
||||
* provides the value, so emit a value/type pair re-exported as default.
|
||||
*/
|
||||
export declare function appendComponentDefaultExport(result: TSESParseForESLintResult, source: string, ctx: VirtualTypeScriptContext, svelteParseContext: SvelteParseContext, instanceScriptRange: [number, number] | null): void;
|
||||
545
node_modules/svelte-eslint-parser/lib/parser/typescript/analyze/component.js
generated
vendored
Normal file
545
node_modules/svelte-eslint-parser/lib/parser/typescript/analyze/component.js
generated
vendored
Normal file
@@ -0,0 +1,545 @@
|
||||
import { removeAllScopeAndVariableAndReference } from "../../../scope/index.js";
|
||||
import { setParent } from "../set-parent.js";
|
||||
import { svelteVersion } from "../../svelte-version.js";
|
||||
/**
|
||||
* Append a synthetic component `export default` so importers can resolve the
|
||||
* component's prop, event, and slot types.
|
||||
*
|
||||
* The export must carry both a value and a type meaning: `ComponentProps<typeof
|
||||
* Foo>` uses the value, while `ComponentEvents<Foo>` and Svelte-4-style
|
||||
* `ComponentProps<Foo>` use `Foo` as a type. A bare `export default <expr>` only
|
||||
* provides the value, so emit a value/type pair re-exported as default.
|
||||
*/
|
||||
export function appendComponentDefaultExport(result, source, ctx, svelteParseContext, instanceScriptRange) {
|
||||
if (hasDefaultExport(result.ast)) {
|
||||
return;
|
||||
}
|
||||
// Legacy recovery must only look at the instance script: a module-context
|
||||
// `export let` is not a prop, and `$$Props`/`$$Events`/`$$Slots` are only
|
||||
// meaningful in the instance script.
|
||||
const instanceStatements = getInstanceStatements(result, instanceScriptRange);
|
||||
const names = [];
|
||||
// Lead with a newline so a trailing line comment can't swallow the statement.
|
||||
let code = "\n";
|
||||
// Runes `$props()` takes precedence over legacy recovery; the last fallback
|
||||
// stays permissive so `typeof Foo` still resolves.
|
||||
let propsType;
|
||||
const runesProps = recoverRunesProps(result, source, svelteParseContext, instanceScriptRange);
|
||||
if (runesProps?.kind === "explicit") {
|
||||
propsType = runesProps.type;
|
||||
}
|
||||
else if (runesProps != null) {
|
||||
const parts = [];
|
||||
if (runesProps.probe != null) {
|
||||
// Let TS infer the default value types via `typeof` of a probe object.
|
||||
const probeName = ctx.generateUniqueId("propsProbe");
|
||||
names.push(probeName);
|
||||
code += `const ${probeName} = ${runesProps.probe};`;
|
||||
parts.push(`{ [K in keyof typeof ${probeName}]?: (typeof ${probeName})[K] }`);
|
||||
}
|
||||
if (runesProps.members != null) {
|
||||
parts.push(runesProps.members);
|
||||
}
|
||||
if (runesProps.open) {
|
||||
parts.push("{ [key: string]: any }");
|
||||
}
|
||||
// An empty destructuring declares no props at all, so nothing is accepted.
|
||||
propsType = parts.length ? parts.join(" & ") : "{ [key: string]: never }";
|
||||
}
|
||||
else {
|
||||
// A component reading `$$props`/`$$restProps` accepts arbitrary attributes,
|
||||
// so the synthesized (closed) type is opened with an index signature to
|
||||
// avoid spurious excess-property errors. `$$Props` is exempt: there the user
|
||||
// owns the open/closed decision.
|
||||
const dollarPropsType = getDollarDollarPropsType(instanceStatements, svelteParseContext);
|
||||
if (dollarPropsType != null) {
|
||||
propsType = dollarPropsType;
|
||||
}
|
||||
else {
|
||||
const inferredBindings = new Set();
|
||||
const probeName = ctx.generateUniqueId("legacyPropsProbe");
|
||||
const exportLetType = getLegacyExportLetPropsType(instanceStatements, source, svelteParseContext, (name) => {
|
||||
inferredBindings.add(name);
|
||||
return `(typeof ${probeName} extends () => infer P ? P : never)[${JSON.stringify(name)}]`;
|
||||
});
|
||||
if (inferredBindings.size) {
|
||||
names.push(probeName);
|
||||
// A function avoids control-flow narrowing at the end of the script;
|
||||
// its object return also widens inferred boolean literal values.
|
||||
code += `const ${probeName} = () => ({ ${[...inferredBindings].join(", ")} });`;
|
||||
}
|
||||
if (exportLetType != null && referencesOpenProps(result)) {
|
||||
propsType = `${exportLetType} & { [key: string]: any }`;
|
||||
}
|
||||
else {
|
||||
propsType = exportLetType ?? "{ [key: string]: any }";
|
||||
}
|
||||
}
|
||||
}
|
||||
// Stay permissive without `$$Events`/`$$Slots` so `on:` and slots don't get
|
||||
// spurious errors.
|
||||
const eventsType = hasNamedTypeDeclaration(instanceStatements, "$$Events")
|
||||
? "$$Events"
|
||||
: "{ [key: string]: any }";
|
||||
const slotsType = hasNamedTypeDeclaration(instanceStatements, "$$Slots")
|
||||
? "$$Slots"
|
||||
: "{ [key: string]: any }";
|
||||
const name = ctx.generateUniqueId("svelteComponent");
|
||||
names.push(name);
|
||||
const { valueType, typeType } = componentTypeText(propsType, eventsType, slotsType, getInstanceExportsType(instanceStatements, svelteParseContext));
|
||||
code += `declare const ${name}: ${valueType};type ${name} = ${typeType};export { ${name} as default };`;
|
||||
ctx.appendVirtualScript(code);
|
||||
// `export { <name> as default }`.
|
||||
registerRemoval(ctx, (node) => node.type === "ExportNamedDeclaration" &&
|
||||
node.declaration == null &&
|
||||
node.specifiers.length === 1 &&
|
||||
node.specifiers[0].local.type === "Identifier" &&
|
||||
node.specifiers[0].local.name === name);
|
||||
// `type <name> = ...`.
|
||||
registerRemoval(ctx, (node) => node.type === "TSTypeAliasDeclaration" && node.id.name === name);
|
||||
// The `declare const <name>` and any props probe const.
|
||||
for (const nm of names) {
|
||||
registerRemoval(ctx, (node) => node.type === "VariableDeclaration" &&
|
||||
node.declarations[0]?.id.type === "Identifier" &&
|
||||
node.declarations[0].id.name === nm);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Value-side and type-side text of the synthetic default export, chosen by the
|
||||
* *installed* Svelte version rather than the component mode: Svelte 3/4 typings
|
||||
* have no `Component`, and Svelte 3's `SvelteComponent` is not generic.
|
||||
*/
|
||||
function componentTypeText(propsType, eventsType, slotsType, exportsType) {
|
||||
const typeArgs = `<${propsType}, ${eventsType}, ${slotsType}>`;
|
||||
// Instance exports are what `bind:this` hands back, so the instance type
|
||||
// carries them alongside the component class.
|
||||
function withExports(type) {
|
||||
return exportsType == null ? type : `${type} & ${exportsType}`;
|
||||
}
|
||||
if (svelteVersion.gte(5)) {
|
||||
// The value is Svelte 5's `Component` so `typeof Foo` matches modern usage;
|
||||
// the same-named legacy `SvelteComponent` type keeps `ComponentEvents<Foo>`
|
||||
// resolving.
|
||||
return {
|
||||
valueType: exportsType == null
|
||||
? `import('svelte').Component<${propsType}>`
|
||||
: `import('svelte').Component<${propsType}, ${exportsType}>`,
|
||||
typeType: withExports(`import('svelte').SvelteComponent${typeArgs}`),
|
||||
};
|
||||
}
|
||||
const className = svelteVersion.gte(4)
|
||||
? "SvelteComponent"
|
||||
: "SvelteComponentTyped";
|
||||
const instanceType = withExports(`import('svelte').${className}${typeArgs}`);
|
||||
// A constructor value so `new Foo(...)` works and `typeof Foo` resolves; the
|
||||
// same-named type is the instance for `ComponentProps<Foo>` /
|
||||
// `ComponentEvents<Foo>`. `ComponentConstructorOptions` (present in Svelte 3
|
||||
// and 4) validates `new Foo({ props: … })` instead of accepting anything.
|
||||
return {
|
||||
valueType: `new (options: import('svelte').ComponentConstructorOptions<${propsType}>) => ${instanceType}`,
|
||||
typeType: instanceType,
|
||||
};
|
||||
}
|
||||
/** Register a restore process that splices a matching statement and cleans scope. */
|
||||
function registerRemoval(ctx, match) {
|
||||
ctx.restoreContext.addRestoreStatementProcess((node, result) => {
|
||||
if (!match(node)) {
|
||||
return false;
|
||||
}
|
||||
result.ast.body.splice(result.ast.body.indexOf(node), 1);
|
||||
removeAllScopeAndVariableAndReference(node, {
|
||||
visitorKeys: result.visitorKeys,
|
||||
scopeManager: result.scopeManager,
|
||||
});
|
||||
return true;
|
||||
});
|
||||
}
|
||||
function hasDefaultExport(ast) {
|
||||
return ast.body.some((node) => {
|
||||
if (node.type === "ExportDefaultDeclaration") {
|
||||
return true;
|
||||
}
|
||||
// `export { x as default }` counts as a user-authored default export too.
|
||||
if (node.type === "ExportNamedDeclaration") {
|
||||
return (node.exportKind !== "type" &&
|
||||
node.specifiers.some((specifier) => specifier.exportKind !== "type" &&
|
||||
exportName(specifier.exported) === "default"));
|
||||
}
|
||||
return (node.type === "ExportAllDeclaration" &&
|
||||
node.exportKind !== "type" &&
|
||||
node.exported != null &&
|
||||
exportName(node.exported) === "default");
|
||||
});
|
||||
}
|
||||
/** Get either spelling of an ES module export name. */
|
||||
function exportName(node) {
|
||||
return node.type === "Identifier" ? node.name : node.value;
|
||||
}
|
||||
/** Top-level statements of the instance `<script>`, filtered out of the concatenated body by source range. */
|
||||
function getInstanceStatements(result, instanceScriptRange) {
|
||||
if (!instanceScriptRange) {
|
||||
return [];
|
||||
}
|
||||
const [start, end] = instanceScriptRange;
|
||||
return result.ast.body.filter((node) => start <= node.range[0] && node.range[1] <= end);
|
||||
}
|
||||
function hasNamedTypeDeclaration(statements, name) {
|
||||
return statements.some((statement) => {
|
||||
const node = statement.type === "ExportNamedDeclaration"
|
||||
? statement.declaration
|
||||
: statement;
|
||||
return (node != null &&
|
||||
(node.type === "TSInterfaceDeclaration" ||
|
||||
node.type === "TSTypeAliasDeclaration") &&
|
||||
node.id.name === name);
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Svelte treats `$$Props` as the authoritative prop typing, so it takes priority
|
||||
* over `export let` inference. Referenced by name, since the declaration itself
|
||||
* stays in the virtual code.
|
||||
*/
|
||||
function getDollarDollarPropsType(instanceStatements, svelteParseContext) {
|
||||
if (svelteParseContext.runes === true) {
|
||||
return null;
|
||||
}
|
||||
return hasNamedTypeDeclaration(instanceStatements, "$$Props")
|
||||
? "$$Props"
|
||||
: null;
|
||||
}
|
||||
/**
|
||||
* Synthesize a props object type from legacy prop declarations, mirroring
|
||||
* svelte2tsx: a default value makes the prop optional, an explicit annotation is
|
||||
* used as-is, otherwise the type is inferred via `typeof`. Renamed exports whose
|
||||
* local is a top-level `let` (`export { className as class }`) are props too.
|
||||
*/
|
||||
function getLegacyExportLetPropsType(instanceStatements, source, svelteParseContext, inferBinding) {
|
||||
// `export let` is only a prop declaration in legacy (non-runes) mode.
|
||||
if (svelteParseContext.runes === true) {
|
||||
return null;
|
||||
}
|
||||
const members = [];
|
||||
function pushMember(exportedName, declarator) {
|
||||
const optional = declarator.init != null;
|
||||
const typeAnnotation = declarator.id.type === "Identifier"
|
||||
? declarator.id.typeAnnotation
|
||||
: undefined;
|
||||
const localName = declarator.id.type === "Identifier" ? declarator.id.name : null;
|
||||
const typeText = typeAnnotation
|
||||
? source.slice(typeAnnotation.typeAnnotation.range[0], typeAnnotation.typeAnnotation.range[1])
|
||||
: localName != null
|
||||
? (declarator.init &&
|
||||
degenerateDefaultType(stripAsConst(declarator.init))) ||
|
||||
inferBinding(localName)
|
||||
: "any";
|
||||
members.push(`${propKey(exportedName)}${optional ? "?" : ""}: ${typeText}`);
|
||||
}
|
||||
// Indexed by binding name so a renamed export can resolve its local `let`.
|
||||
const letDeclarators = new Map();
|
||||
for (const node of instanceStatements) {
|
||||
const decl = node.type === "ExportNamedDeclaration" ? node.declaration : node;
|
||||
if (decl?.type !== "VariableDeclaration" || decl.kind !== "let") {
|
||||
continue;
|
||||
}
|
||||
for (const declarator of decl.declarations) {
|
||||
if (declarator.id.type === "Identifier") {
|
||||
letDeclarators.set(declarator.id.name, declarator);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const node of instanceStatements) {
|
||||
if (node.type !== "ExportNamedDeclaration" || node.exportKind === "type") {
|
||||
continue;
|
||||
}
|
||||
if (node.declaration?.type === "VariableDeclaration" &&
|
||||
node.declaration.kind === "let") {
|
||||
for (const declarator of node.declaration.declarations) {
|
||||
if (declarator.id.type !== "Identifier") {
|
||||
continue;
|
||||
}
|
||||
pushMember(declarator.id.name, declarator);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// A renamed (or same-name) export of a top-level `let` binding is a prop.
|
||||
// Skip re-exports (`export … from '…'`) and `default` (handled elsewhere).
|
||||
if (node.declaration == null && node.source == null) {
|
||||
for (const specifier of node.specifiers) {
|
||||
if (specifier.local.type !== "Identifier" ||
|
||||
specifier.exportKind === "type" ||
|
||||
exportName(specifier.exported) === "default") {
|
||||
continue;
|
||||
}
|
||||
const declarator = letDeclarators.get(specifier.local.name);
|
||||
if (!declarator) {
|
||||
continue;
|
||||
}
|
||||
pushMember(exportName(specifier.exported), declarator);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!members.length) {
|
||||
return null;
|
||||
}
|
||||
return `{ ${members.join("; ")} }`;
|
||||
}
|
||||
/**
|
||||
* Collect the instance script's component exports (`export const`, `export
|
||||
* function`, `export class`, and `export { x }`) as a type literal, mirroring
|
||||
* svelte2tsx. In legacy mode an exported `let` is a prop rather than an export.
|
||||
*/
|
||||
function getInstanceExportsType(instanceStatements, svelteParseContext) {
|
||||
const legacy = svelteParseContext.runes !== true;
|
||||
const letBindings = new Set();
|
||||
for (const node of instanceStatements) {
|
||||
const decl = node.type === "ExportNamedDeclaration" ? node.declaration : node;
|
||||
if (decl?.type !== "VariableDeclaration" || decl.kind !== "let") {
|
||||
continue;
|
||||
}
|
||||
for (const declarator of decl.declarations) {
|
||||
if (declarator.id.type === "Identifier") {
|
||||
letBindings.add(declarator.id.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
const members = new Map();
|
||||
for (const node of instanceStatements) {
|
||||
if (node.type !== "ExportNamedDeclaration" || node.exportKind === "type") {
|
||||
continue;
|
||||
}
|
||||
const decl = node.declaration;
|
||||
if (decl?.type === "VariableDeclaration") {
|
||||
if (legacy && decl.kind === "let") {
|
||||
continue;
|
||||
}
|
||||
for (const declarator of decl.declarations) {
|
||||
if (declarator.id.type === "Identifier") {
|
||||
members.set(declarator.id.name, declarator.id.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
else if ((decl?.type === "FunctionDeclaration" ||
|
||||
decl?.type === "ClassDeclaration") &&
|
||||
decl.id != null) {
|
||||
members.set(decl.id.name, decl.id.name);
|
||||
}
|
||||
else if (decl == null && node.source == null) {
|
||||
for (const specifier of node.specifiers) {
|
||||
if (specifier.local.type !== "Identifier" ||
|
||||
specifier.exportKind === "type") {
|
||||
continue;
|
||||
}
|
||||
const exported = exportName(specifier.exported);
|
||||
if (exported === "default" ||
|
||||
(legacy && letBindings.has(specifier.local.name))) {
|
||||
continue;
|
||||
}
|
||||
members.set(exported, specifier.local.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!members.size) {
|
||||
return null;
|
||||
}
|
||||
return `{ ${[...members]
|
||||
.map(([exported, local]) => `${propKey(exported)}: typeof ${local}`)
|
||||
.join("; ")} }`;
|
||||
}
|
||||
/** Quote non-identifier keys so reserved-word prop names like `class` are emitted safely. */
|
||||
function propKey(name) {
|
||||
return /^[$A-Z_a-z][\w$]*$/u.test(name) ? name : JSON.stringify(name);
|
||||
}
|
||||
/** Unresolved prop globals in either the instance script or template open the props. */
|
||||
function referencesOpenProps(result) {
|
||||
return result.scopeManager.globalScope.through.some(({ identifier }) => identifier.name === "$$props" || identifier.name === "$$restProps");
|
||||
}
|
||||
/**
|
||||
* Recover props from a runes `$props()` declaration. An explicit annotation,
|
||||
* `as`, or `satisfies` type is used as-is; otherwise the type is inferred from
|
||||
* the destructuring.
|
||||
*
|
||||
* Only a top-level instance-script declaration counts, since that is the only
|
||||
* place Svelte accepts `$props()`; a `<script module>` call must not hijack the
|
||||
* real declaration.
|
||||
*/
|
||||
function recoverRunesProps(result, source, svelteParseContext, instanceScriptRange) {
|
||||
if (svelteParseContext.runes === false || !instanceScriptRange) {
|
||||
return null;
|
||||
}
|
||||
const [instanceStart, instanceEnd] = instanceScriptRange;
|
||||
const propsReferences = result.scopeManager.globalScope.through.filter((reference) => {
|
||||
const { name, range } = reference.identifier;
|
||||
return (name === "$props" &&
|
||||
range != null &&
|
||||
instanceStart <= range[0] &&
|
||||
range[1] <= instanceEnd);
|
||||
});
|
||||
if (!propsReferences.length) {
|
||||
return null;
|
||||
}
|
||||
setParent(result);
|
||||
for (const reference of propsReferences) {
|
||||
const id = reference.identifier;
|
||||
const call = id.parent;
|
||||
if (call?.type !== "CallExpression" || call.callee !== id) {
|
||||
continue;
|
||||
}
|
||||
// Trailing `as`/`satisfies`/`!` operators sit between the call and the
|
||||
// declarator and can be stacked. The outermost annotation is the effective
|
||||
// type, so keep overwriting; `!` only unwraps.
|
||||
let valueNode = call;
|
||||
let castType = null;
|
||||
for (;;) {
|
||||
const parent = valueNode.parent;
|
||||
if (parent?.type === "TSAsExpression" ||
|
||||
parent?.type === "TSSatisfiesExpression") {
|
||||
castType = parent.typeAnnotation;
|
||||
valueNode = parent;
|
||||
}
|
||||
else if (parent?.type === "TSNonNullExpression") {
|
||||
valueNode = parent;
|
||||
}
|
||||
else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (valueNode.parent?.type !== "VariableDeclarator" ||
|
||||
valueNode.parent.init !== valueNode ||
|
||||
!isTopLevelDeclarator(valueNode.parent)) {
|
||||
continue;
|
||||
}
|
||||
const declId = valueNode.parent.id;
|
||||
// The binding annotation is the public contract, even when the initializer
|
||||
// is asserted to a narrower type.
|
||||
const type = declId.typeAnnotation?.typeAnnotation ?? castType;
|
||||
if (type) {
|
||||
return {
|
||||
kind: "explicit",
|
||||
type: source.slice(type.range[0], type.range[1]),
|
||||
};
|
||||
}
|
||||
if (declId.type === "ObjectPattern") {
|
||||
return inferPropsFromObjectPattern(declId, source);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function isTopLevelDeclarator(declarator) {
|
||||
const declaration = declarator.parent;
|
||||
const statement = declaration.parent?.type === "ExportNamedDeclaration"
|
||||
? declaration.parent
|
||||
: declaration;
|
||||
return statement.parent?.type === "Program";
|
||||
}
|
||||
/**
|
||||
* Defaults go through a probe object because only TS can type the default
|
||||
* expression; a prop with no default has no type source at all, so it stays a
|
||||
* required `any`, as in svelte2tsx.
|
||||
*/
|
||||
function inferPropsFromObjectPattern(pattern, source) {
|
||||
const members = [];
|
||||
const defaulted = [];
|
||||
// A prop can be destructured twice (`{ a, a: b }`, `{ 1e3: p, 1_000: q }`);
|
||||
// emitting the key twice would be a TS2300 duplicate identifier.
|
||||
const seen = new Set();
|
||||
let open = false;
|
||||
for (const prop of pattern.properties) {
|
||||
if (prop.type !== "Property") {
|
||||
open = true;
|
||||
continue;
|
||||
}
|
||||
// Keys are taken raw so a string key keeps its quotes. A literal key is
|
||||
// resolvable even when computed (`["a"]`), unlike an identifier one (`[k]`).
|
||||
// Bigint keys are excluded: `0n` is not a valid type-literal key.
|
||||
let key, normalized;
|
||||
if (!prop.computed && prop.key.type === "Identifier") {
|
||||
key = prop.key.name;
|
||||
normalized = prop.key.name;
|
||||
}
|
||||
else if (prop.key.type === "Literal" &&
|
||||
(typeof prop.key.value === "string" || typeof prop.key.value === "number")) {
|
||||
key = prop.key.raw;
|
||||
// `String` matches `ToPropertyKey`, so `1e3`, `1_000` and `"1000"` agree.
|
||||
normalized = String(prop.key.value);
|
||||
}
|
||||
else {
|
||||
open = true;
|
||||
continue;
|
||||
}
|
||||
if (seen.has(normalized)) {
|
||||
continue;
|
||||
}
|
||||
seen.add(normalized);
|
||||
if (prop.value.type === "AssignmentPattern") {
|
||||
let def = stripAsConst(prop.value.right);
|
||||
// $bindable is a marker, not the default's type. Unwrap its fallback so
|
||||
// null/undefined/empty arrays receive the same widening as plain defaults.
|
||||
if (def.type === "CallExpression" &&
|
||||
def.callee.type === "Identifier" &&
|
||||
def.callee.name === "$bindable" &&
|
||||
!def.typeArguments) {
|
||||
const fallback = def.arguments[0];
|
||||
if (!fallback) {
|
||||
members.push(`${key}?: any`);
|
||||
continue;
|
||||
}
|
||||
if (fallback.type !== "SpreadElement")
|
||||
def = stripAsConst(fallback);
|
||||
}
|
||||
const degraded = degenerateDefaultType(def);
|
||||
if (degraded != null) {
|
||||
members.push(`${key}?: ${degraded}`);
|
||||
continue;
|
||||
}
|
||||
// ESTree ranges exclude wrapping parens, so a sequence expression default
|
||||
// would slice to `1, 2` and make the probe object literal invalid.
|
||||
defaulted.push(`${key}: (${source.slice(def.range[0], def.range[1])})`);
|
||||
}
|
||||
else {
|
||||
members.push(`${key}: any`);
|
||||
}
|
||||
}
|
||||
return {
|
||||
kind: "inferred",
|
||||
members: members.length ? `{ ${members.join("; ")} }` : null,
|
||||
probe: defaulted.length ? `{ ${defaulted.join(", ")} }` : null,
|
||||
open,
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Unwrap `X as const`, whose `const` parses as a type reference rather than a
|
||||
* keyword. The frozen literal type it produces would reject every other value an
|
||||
* importer passes; an author who wants that narrowing writes an explicit
|
||||
* annotation, which takes precedence anyway.
|
||||
*/
|
||||
function stripAsConst(node) {
|
||||
if (node.type === "TSAsExpression" &&
|
||||
node.typeAnnotation.type === "TSTypeReference" &&
|
||||
node.typeAnnotation.typeName.type === "Identifier" &&
|
||||
node.typeAnnotation.typeName.name === "const") {
|
||||
return node.expression;
|
||||
}
|
||||
return node;
|
||||
}
|
||||
/**
|
||||
* Defaults that TS can only infer as an uninhabitable type (`never[]`, `null`,
|
||||
* `undefined`), which would reject every value an importer can pass. svelte2tsx
|
||||
* degrades them to `any` for the same reason.
|
||||
*/
|
||||
function degenerateDefaultType(node) {
|
||||
if (node.type === "ArrayExpression" && node.elements.length === 0) {
|
||||
return "any[]";
|
||||
}
|
||||
// `raw` distinguishes the null literal from a regex literal, whose `value` is
|
||||
// also null when the environment cannot build the `RegExp`.
|
||||
if (node.type === "Literal" && node.raw === "null") {
|
||||
return "any";
|
||||
}
|
||||
if (node.type === "Identifier" && node.name === "undefined") {
|
||||
return "any";
|
||||
}
|
||||
if (node.type === "UnaryExpression" && node.operator === "void") {
|
||||
return "any";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
56
node_modules/svelte-eslint-parser/lib/parser/typescript/analyze/index.d.ts
generated
vendored
Normal file
56
node_modules/svelte-eslint-parser/lib/parser/typescript/analyze/index.d.ts
generated
vendored
Normal file
@@ -0,0 +1,56 @@
|
||||
import { VirtualTypeScriptContext } from "../context.js";
|
||||
import type { SvelteHTMLElement } from "../../../ast/index.js";
|
||||
import type { NormalizedParserOptions } from "../../parser-options.js";
|
||||
import type { SvelteParseContext } from "../../svelte-parse-context.js";
|
||||
export type AnalyzeTypeScriptContext = {
|
||||
slots: Set<SvelteHTMLElement>;
|
||||
svelteParseContext: SvelteParseContext;
|
||||
/** Source range of the instance `<script>` content; the virtual code concatenates both scripts. */
|
||||
instanceScriptRange?: [number, number] | null;
|
||||
};
|
||||
type SvelteTypeScriptCode = {
|
||||
/**
|
||||
* User-authored <script> content.
|
||||
*
|
||||
* Example:
|
||||
* <script lang="ts">
|
||||
* const x = $derived(0);
|
||||
* </script>
|
||||
*/
|
||||
script: string;
|
||||
/**
|
||||
* Template code that is wrapped in the synthetic render function, where
|
||||
* template scopes are modeled.
|
||||
*
|
||||
* Example:
|
||||
* {#if ok}
|
||||
* {const x = $derived(0)}
|
||||
* {/if}
|
||||
*/
|
||||
render: string;
|
||||
/**
|
||||
* Template-generated code that must stay outside the render wrapper, such as
|
||||
* top-level snippets.
|
||||
*
|
||||
* Example:
|
||||
* {#snippet s()}
|
||||
* {const x = $derived(0)}
|
||||
* {/snippet}
|
||||
*/
|
||||
rootScope: string;
|
||||
};
|
||||
/**
|
||||
* Analyze TypeScript source code in Svelte.
|
||||
* Generate virtual code to provide correct type information for Svelte store reference names, scopes, and runes.
|
||||
* See https://github.com/sveltejs/svelte-eslint-parser/blob/main/docs/internal-mechanism.md#scope-types
|
||||
*/
|
||||
export declare function analyzeTypeScriptInSvelte(
|
||||
/** Split virtual code generated from the Svelte component. */
|
||||
code: SvelteTypeScriptCode, attrs: Record<string, string | undefined>, parserOptions: NormalizedParserOptions, context: AnalyzeTypeScriptContext): VirtualTypeScriptContext;
|
||||
/**
|
||||
* Analyze TypeScript source code.
|
||||
* Generate virtual code to provide correct type information for Svelte runes.
|
||||
* See https://github.com/sveltejs/svelte-eslint-parser/blob/main/docs/internal-mechanism.md#scope-types
|
||||
*/
|
||||
export declare function analyzeTypeScript(code: string, attrs: Record<string, string | undefined>, parserOptions: NormalizedParserOptions, svelteParseContext: SvelteParseContext): VirtualTypeScriptContext;
|
||||
export {};
|
||||
840
node_modules/svelte-eslint-parser/lib/parser/typescript/analyze/index.js
generated
vendored
Normal file
840
node_modules/svelte-eslint-parser/lib/parser/typescript/analyze/index.js
generated
vendored
Normal file
@@ -0,0 +1,840 @@
|
||||
import { addAllReferences, addVariable, getAllReferences, getProgramScope, removeAllScopeAndVariableAndReference, removeIdentifierReference, removeIdentifierVariable, replaceScope, } from "../../../scope/index.js";
|
||||
import { addElementsToSortedArray, sortedLastIndex, } from "../../../utils/index.js";
|
||||
import { parseScriptWithoutAnalyzeScope } from "../../script.js";
|
||||
import { VirtualTypeScriptContext } from "../context.js";
|
||||
import { setParent } from "../set-parent.js";
|
||||
import { getGlobalsForSvelte, globalsForRunes } from "../../globals.js";
|
||||
import { withoutProjectParserOptions } from "../../parser-options.js";
|
||||
import { appendComponentDefaultExport } from "./component.js";
|
||||
/**
|
||||
* Analyze TypeScript source code in Svelte.
|
||||
* Generate virtual code to provide correct type information for Svelte store reference names, scopes, and runes.
|
||||
* See https://github.com/sveltejs/svelte-eslint-parser/blob/main/docs/internal-mechanism.md#scope-types
|
||||
*/
|
||||
export function analyzeTypeScriptInSvelte(
|
||||
/** Split virtual code generated from the Svelte component. */
|
||||
code, attrs, parserOptions, context) {
|
||||
const ctx = new VirtualTypeScriptContext(code.script + code.render + code.rootScope);
|
||||
ctx.appendOriginal(/^\s*/u.exec(code.script)[0].length);
|
||||
const result = parseScriptWithoutAnalyzeScope(code.script + code.render + code.rootScope, attrs, withoutProjectParserOptions(parserOptions));
|
||||
ctx._beforeResult = result;
|
||||
analyzeStoreReferenceNames(result, context.svelteParseContext, ctx);
|
||||
analyzeDollarDollarVariables(result, ctx, context.svelteParseContext, context.slots);
|
||||
analyzeRuneVariables(result, ctx, context.svelteParseContext);
|
||||
if (!attrs.lang || attrs.lang === "js" || attrs.lang === "javascript") {
|
||||
// Keep leading JSDoc attached to the user's declaration, not to the last
|
||||
// synthetic declaration inserted above it.
|
||||
ctx.appendVirtualScript("\n");
|
||||
}
|
||||
const scriptTransformers = [
|
||||
...analyzeReactiveScopes(result),
|
||||
];
|
||||
const renderTransformers = [];
|
||||
const rootScopeTransformers = [];
|
||||
const renderStart = code.script.length;
|
||||
const rootScopeStart = code.script.length + code.render.length;
|
||||
for (const transform of analyzeDollarDerivedScopes(result, context.svelteParseContext)) {
|
||||
if (transform.node.range[0] < renderStart) {
|
||||
scriptTransformers.push(transform);
|
||||
}
|
||||
else if (transform.node.range[0] < rootScopeStart) {
|
||||
renderTransformers.push(transform);
|
||||
}
|
||||
else {
|
||||
rootScopeTransformers.push(transform);
|
||||
}
|
||||
}
|
||||
applyTransforms(scriptTransformers, ctx);
|
||||
analyzeRenderScopes(code, ctx, () => applyTransforms(renderTransformers, ctx));
|
||||
// Type checking non-module TypeScript code can report
|
||||
// `Cannot redeclare block-scoped variable 'xxx'`, so add a dummy export.
|
||||
// Keep it before consuming `rootScope` so it remains a standalone statement
|
||||
// at the render/rootScope boundary instead of splitting transformed rootScope
|
||||
// expressions such as `{#snippet s()}{const x = $derived(0)}{/snippet}`.
|
||||
// See https://github.com/sveltejs/svelte-eslint-parser/issues/557
|
||||
if (!hasExportDeclaration(result.ast)) {
|
||||
appendDummyExport(ctx);
|
||||
}
|
||||
// This starts consuming `rootScope`. Keep it after `analyzeRenderScopes()` so
|
||||
// top-level snippet code is emitted outside the synthetic render function:
|
||||
// {#snippet s()}
|
||||
// {const x = $derived(0)}
|
||||
// {/snippet}
|
||||
// Keep it after the dummy export above so the export can stay at the
|
||||
// render/rootScope boundary.
|
||||
applyTransforms(rootScopeTransformers, ctx);
|
||||
ctx.appendOriginalToEnd();
|
||||
// Emitted last so it lands as a standalone top-level statement.
|
||||
appendComponentDefaultExport(result, code.script + code.render + code.rootScope, ctx, context.svelteParseContext, context.instanceScriptRange ?? null);
|
||||
return ctx;
|
||||
}
|
||||
/**
|
||||
* Analyze TypeScript source code.
|
||||
* Generate virtual code to provide correct type information for Svelte runes.
|
||||
* See https://github.com/sveltejs/svelte-eslint-parser/blob/main/docs/internal-mechanism.md#scope-types
|
||||
*/
|
||||
export function analyzeTypeScript(code, attrs, parserOptions, svelteParseContext) {
|
||||
const ctx = new VirtualTypeScriptContext(code);
|
||||
ctx.appendOriginal(/^\s*/u.exec(code)[0].length);
|
||||
const result = parseScriptWithoutAnalyzeScope(code, attrs, withoutProjectParserOptions(parserOptions));
|
||||
ctx._beforeResult = result;
|
||||
analyzeRuneVariables(result, ctx, svelteParseContext);
|
||||
if (!attrs.lang || attrs.lang === "js" || attrs.lang === "javascript") {
|
||||
ctx.appendVirtualScript("\n");
|
||||
}
|
||||
applyTransforms([...analyzeDollarDerivedScopes(result, svelteParseContext)], ctx);
|
||||
ctx.appendOriginalToEnd();
|
||||
return ctx;
|
||||
}
|
||||
function hasExportDeclaration(ast) {
|
||||
for (const node of ast.body) {
|
||||
if (node.type === "ExportNamedDeclaration" ||
|
||||
node.type === "ExportDefaultDeclaration") {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
/**
|
||||
* Analyze the store reference names.
|
||||
* Insert type definitions code to provide correct type information for variables that begin with `$`.
|
||||
*/
|
||||
function analyzeStoreReferenceNames(result, svelteParseContext, ctx) {
|
||||
const globals = getGlobalsForSvelte(svelteParseContext);
|
||||
const scopeManager = result.scopeManager;
|
||||
const programScope = getProgramScope(scopeManager);
|
||||
const maybeStoreRefNames = new Set();
|
||||
for (const reference of scopeManager.globalScope.through) {
|
||||
if (
|
||||
// Begin with `$`.
|
||||
reference.identifier.name.startsWith("$") &&
|
||||
// Ignore globals
|
||||
!globals.includes(reference.identifier.name) &&
|
||||
// Ignore if it is already defined.
|
||||
!programScope.set.has(reference.identifier.name)) {
|
||||
maybeStoreRefNames.add(reference.identifier.name);
|
||||
}
|
||||
}
|
||||
if (maybeStoreRefNames.size) {
|
||||
const storeValueTypeName = ctx.generateUniqueId("StoreValueType");
|
||||
ctx.appendVirtualScript(`type ${storeValueTypeName}<T> = T extends null | undefined
|
||||
? T
|
||||
: T extends object & { subscribe(run: infer F, ...args: any): any }
|
||||
? F extends (value: infer V, ...args: any) => any
|
||||
? V
|
||||
: never
|
||||
: T;`);
|
||||
ctx.restoreContext.addRestoreStatementProcess((node, result) => {
|
||||
if (node.type !== "TSTypeAliasDeclaration" ||
|
||||
node.id.name !== storeValueTypeName) {
|
||||
return false;
|
||||
}
|
||||
const program = result.ast;
|
||||
program.body.splice(program.body.indexOf(node), 1);
|
||||
const scopeManager = result.scopeManager;
|
||||
// Remove `type` scope
|
||||
removeAllScopeAndVariableAndReference(node, {
|
||||
visitorKeys: result.visitorKeys,
|
||||
scopeManager,
|
||||
});
|
||||
return true;
|
||||
});
|
||||
for (const nm of maybeStoreRefNames) {
|
||||
const realName = nm.slice(1);
|
||||
ctx.appendVirtualScript(`declare let ${nm}: ${storeValueTypeName}<typeof ${realName}>;`);
|
||||
ctx.restoreContext.addRestoreStatementProcess((node, result) => {
|
||||
if (node.type !== "VariableDeclaration" ||
|
||||
!node.declare ||
|
||||
node.declarations.length !== 1 ||
|
||||
node.declarations[0].id.type !== "Identifier" ||
|
||||
node.declarations[0].id.name !== nm) {
|
||||
return false;
|
||||
}
|
||||
const program = result.ast;
|
||||
program.body.splice(program.body.indexOf(node), 1);
|
||||
const scopeManager = result.scopeManager;
|
||||
// Remove `declare` variable
|
||||
removeAllScopeAndVariableAndReference(node, {
|
||||
visitorKeys: result.visitorKeys,
|
||||
scopeManager,
|
||||
});
|
||||
return true;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Analyze `$$slots`, `$$props`, and `$$restProps` .
|
||||
* Insert type definitions code to provide correct type information for `$$slots`, `$$props`, and `$$restProps`.
|
||||
*/
|
||||
function analyzeDollarDollarVariables(result, ctx, svelteParseContext, slots) {
|
||||
const globals = getGlobalsForSvelte(svelteParseContext);
|
||||
const scopeManager = result.scopeManager;
|
||||
for (const globalName of globals) {
|
||||
if (!scopeManager.globalScope.through.some((reference) => reference.identifier.name === globalName)) {
|
||||
continue;
|
||||
}
|
||||
switch (globalName) {
|
||||
case "$$props":
|
||||
appendDeclareVirtualScript(globalName, `{ [index: string]: any }`);
|
||||
break;
|
||||
case "$$restProps":
|
||||
appendDeclareVirtualScript(globalName, `{ [index: string]: any }`);
|
||||
break;
|
||||
case "$$slots": {
|
||||
const nameTypes = new Set();
|
||||
for (const slot of slots) {
|
||||
const nameAttr = slot.startTag.attributes.find((attr) => attr.type === "SvelteAttribute" && attr.key.name === "name");
|
||||
if (!nameAttr || nameAttr.value.length === 0) {
|
||||
nameTypes.add('"default"');
|
||||
continue;
|
||||
}
|
||||
if (nameAttr.value.length === 1) {
|
||||
const value = nameAttr.value[0];
|
||||
if (value.type === "SvelteLiteral") {
|
||||
nameTypes.add(JSON.stringify(value.value));
|
||||
}
|
||||
else {
|
||||
nameTypes.add("string");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
nameTypes.add(`\`${nameAttr.value
|
||||
.map((value) => value.type === "SvelteLiteral"
|
||||
? value.value.replace(/([$`])/gu, "\\$1")
|
||||
: "${string}")
|
||||
.join("")}\``);
|
||||
}
|
||||
appendDeclareVirtualScript(globalName, `Record<${nameTypes.size > 0 ? [...nameTypes].join(" | ") : "any"}, boolean>`);
|
||||
break;
|
||||
}
|
||||
case "$state":
|
||||
case "$derived":
|
||||
case "$effect":
|
||||
case "$props":
|
||||
case "$bindable":
|
||||
case "$inspect":
|
||||
case "$host":
|
||||
// Processed by `analyzeRuneVariables`.
|
||||
break;
|
||||
default: {
|
||||
const _ = globalName;
|
||||
throw Error(`Unknown global: ${_}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
/** Append declare virtual script */
|
||||
function appendDeclareVirtualScript(name, type) {
|
||||
ctx.appendVirtualScript(`declare let ${name}: ${type};`);
|
||||
ctx.restoreContext.addRestoreStatementProcess((node, result) => {
|
||||
if (node.type !== "VariableDeclaration" ||
|
||||
!node.declare ||
|
||||
node.declarations.length !== 1 ||
|
||||
node.declarations[0].id.type !== "Identifier" ||
|
||||
node.declarations[0].id.name !== name) {
|
||||
return false;
|
||||
}
|
||||
const program = result.ast;
|
||||
program.body.splice(program.body.indexOf(node), 1);
|
||||
const scopeManager = result.scopeManager;
|
||||
// Remove `declare` variable
|
||||
removeAllScopeAndVariableAndReference(node, {
|
||||
visitorKeys: result.visitorKeys,
|
||||
scopeManager,
|
||||
});
|
||||
return true;
|
||||
});
|
||||
}
|
||||
}
|
||||
/** Append dummy export */
|
||||
function appendDummyExport(ctx) {
|
||||
ctx.appendVirtualScript(`export namespace SvelteEslintParserModuleMarker {}`);
|
||||
ctx.restoreContext.addRestoreStatementProcess((node, result) => {
|
||||
if (node.type !== "ExportNamedDeclaration" ||
|
||||
node.declaration?.type !== "TSModuleDeclaration" ||
|
||||
node.declaration.kind !== "namespace" ||
|
||||
node.declaration.id.type !== "Identifier" ||
|
||||
node.declaration.id.name !== "SvelteEslintParserModuleMarker") {
|
||||
return false;
|
||||
}
|
||||
const program = result.ast;
|
||||
program.body.splice(program.body.indexOf(node), 1);
|
||||
const scopeManager = result.scopeManager;
|
||||
// Remove `declare` variable
|
||||
removeAllScopeAndVariableAndReference(node, {
|
||||
visitorKeys: result.visitorKeys,
|
||||
scopeManager,
|
||||
});
|
||||
return true;
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Analyze Runes.
|
||||
* Insert type definitions code to provide correct type information for Runes.
|
||||
*/
|
||||
function analyzeRuneVariables(result, ctx, svelteParseContext) {
|
||||
// No processing is needed if the user is determined not to be in Runes mode.
|
||||
if (svelteParseContext.runes === false) {
|
||||
return;
|
||||
}
|
||||
const scopeManager = result.scopeManager;
|
||||
for (const globalName of globalsForRunes) {
|
||||
if (!scopeManager.globalScope.through.some((reference) => reference.identifier.name === globalName)) {
|
||||
continue;
|
||||
}
|
||||
switch (globalName) {
|
||||
// See https://github.com/sveltejs/svelte/blob/bd2d3db6d0d7a931c2e84c38a5c537e30dda1dbe/packages/svelte/types/index.d.ts#L3124
|
||||
case "$state": {
|
||||
appendDeclareFunctionVirtualScripts(globalName, [
|
||||
"<T>(initial: T): T",
|
||||
"<T>(): T | undefined",
|
||||
]);
|
||||
appendDeclareNamespaceVirtualScripts(globalName, [
|
||||
"export function eager<T>(value: T): T",
|
||||
]);
|
||||
appendDeclareNamespaceVirtualScripts(globalName, [
|
||||
"export function raw<T>(initial: T): T;",
|
||||
"export function raw<T>(): T | undefined;",
|
||||
]);
|
||||
appendDeclareNamespaceVirtualScripts(globalName, [
|
||||
"export function snapshot<T>(state: T): T;",
|
||||
]);
|
||||
break;
|
||||
}
|
||||
// See https://github.com/sveltejs/svelte/blob/3fa3dd78a1cbaa88a1571977b76bf6f02ed4231d/packages/svelte/types/index.d.ts#L3247
|
||||
case "$derived": {
|
||||
appendDeclareFunctionVirtualScripts(globalName, [
|
||||
"<T>(expression: T): T",
|
||||
]);
|
||||
appendDeclareNamespaceVirtualScripts(globalName, [
|
||||
"export function by<T>(fn: () => T): T;",
|
||||
]);
|
||||
break;
|
||||
}
|
||||
// See https://github.com/sveltejs/svelte/blob/3fa3dd78a1cbaa88a1571977b76bf6f02ed4231d/packages/svelte/types/index.d.ts#L3307
|
||||
case "$effect": {
|
||||
appendDeclareFunctionVirtualScripts(globalName, [
|
||||
"(fn: () => void | (() => void)): void",
|
||||
]);
|
||||
appendDeclareNamespaceVirtualScripts(globalName, [
|
||||
"export function pre(fn: () => void | (() => void)): void;",
|
||||
"export function pending(): number;",
|
||||
"export function tracking(): boolean;",
|
||||
"export function root(fn: () => void | (() => void)): () => void;",
|
||||
]);
|
||||
break;
|
||||
}
|
||||
// See https://github.com/sveltejs/svelte/blob/3fa3dd78a1cbaa88a1571977b76bf6f02ed4231d/packages/svelte/types/index.d.ts#L3416
|
||||
case "$props": {
|
||||
// NOTE: In the Svelte repository's `index.d.ts`, the return type is any, but that triggers `@typescript-eslint/no-unsafe-assignment`. To avoid this, use generics here.
|
||||
appendDeclareFunctionVirtualScripts(globalName, ["<T>(): T"]);
|
||||
appendDeclareNamespaceVirtualScripts(globalName, [
|
||||
"export function id(): string;",
|
||||
]);
|
||||
break;
|
||||
}
|
||||
// See https://github.com/sveltejs/svelte/blob/3fa3dd78a1cbaa88a1571977b76bf6f02ed4231d/packages/svelte/types/index.d.ts#L3459
|
||||
case "$bindable": {
|
||||
appendDeclareFunctionVirtualScripts(globalName, [
|
||||
"<T>(fallback?: T): T",
|
||||
]);
|
||||
break;
|
||||
}
|
||||
// See https://github.com/sveltejs/svelte/blob/3fa3dd78a1cbaa88a1571977b76bf6f02ed4231d/packages/svelte/types/index.d.ts#L3502
|
||||
case "$inspect": {
|
||||
appendDeclareFunctionVirtualScripts(globalName, [
|
||||
`<T extends any[]>(...values: T): { with: (fn: (type: 'init' | 'update', ...values: T) => void) => void }`,
|
||||
]);
|
||||
appendDeclareNamespaceVirtualScripts(globalName, [
|
||||
"export function trace(name?: string): void;",
|
||||
]);
|
||||
break;
|
||||
}
|
||||
// See https://github.com/sveltejs/svelte/blob/3fa3dd78a1cbaa88a1571977b76bf6f02ed4231d/packages/svelte/types/index.d.ts#L3565
|
||||
case "$host": {
|
||||
appendDeclareFunctionVirtualScripts(globalName, [
|
||||
`<El extends HTMLElement = HTMLElement>(): El`,
|
||||
]);
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
const _ = globalName;
|
||||
throw Error(`Unknown global: ${_}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
/** Append declare virtual script */
|
||||
function appendDeclareFunctionVirtualScripts(name, types) {
|
||||
for (const type of types) {
|
||||
ctx.appendVirtualScript(`declare function ${name}${type};`);
|
||||
ctx.restoreContext.addRestoreStatementProcess((node, result) => {
|
||||
if (node.type !== "TSDeclareFunction" ||
|
||||
!node.declare ||
|
||||
node.id?.type !== "Identifier" ||
|
||||
node.id.name !== name) {
|
||||
return false;
|
||||
}
|
||||
const program = result.ast;
|
||||
program.body.splice(program.body.indexOf(node), 1);
|
||||
const scopeManager = result.scopeManager;
|
||||
// Remove `declare` variable
|
||||
removeAllScopeAndVariableAndReference(node, {
|
||||
visitorKeys: result.visitorKeys,
|
||||
scopeManager,
|
||||
});
|
||||
return true;
|
||||
});
|
||||
}
|
||||
}
|
||||
function appendDeclareNamespaceVirtualScripts(name, scripts) {
|
||||
for (const script of scripts) {
|
||||
ctx.appendVirtualScript(`declare namespace ${name} { ${script} }`);
|
||||
ctx.restoreContext.addRestoreStatementProcess((node, result) => {
|
||||
if (node.type !== "TSModuleDeclaration" ||
|
||||
!node.declare ||
|
||||
node.id?.type !== "Identifier" ||
|
||||
node.id.name !== name) {
|
||||
return false;
|
||||
}
|
||||
const program = result.ast;
|
||||
program.body.splice(program.body.indexOf(node), 1);
|
||||
const scopeManager = result.scopeManager;
|
||||
// Remove `declare` variable
|
||||
removeAllScopeAndVariableAndReference(node, {
|
||||
visitorKeys: result.visitorKeys,
|
||||
scopeManager,
|
||||
});
|
||||
return true;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Analyze the reactive scopes.
|
||||
* Transform source code to provide the correct type information in the `$:` statements.
|
||||
*/
|
||||
function* analyzeReactiveScopes(result) {
|
||||
const scopeManager = result.scopeManager;
|
||||
const throughIds = scopeManager.globalScope.through.map((reference) => reference.identifier);
|
||||
for (const statement of result.ast.body) {
|
||||
if (statement.type === "LabeledStatement" && statement.label.name === "$") {
|
||||
if (statement.body.type === "ExpressionStatement" &&
|
||||
statement.body.expression.type === "AssignmentExpression" &&
|
||||
statement.body.expression.operator === "=" &&
|
||||
// Must be a pattern that can be used in the LHS of variable declarations.
|
||||
// https://github.com/sveltejs/svelte-eslint-parser/issues/213
|
||||
(statement.body.expression.left.type === "Identifier" ||
|
||||
statement.body.expression.left.type === "ArrayPattern" ||
|
||||
statement.body.expression.left.type === "ObjectPattern")) {
|
||||
const left = statement.body.expression.left;
|
||||
if (throughIds.some((id) => left.range[0] <= id.range[0] && id.range[1] <= left.range[1])) {
|
||||
const node = statement;
|
||||
const expression = statement.body.expression;
|
||||
yield {
|
||||
node,
|
||||
transform: (ctx) => transformForDeclareReactiveVar(node, left, expression, result.ast.tokens, ctx),
|
||||
};
|
||||
continue;
|
||||
}
|
||||
}
|
||||
yield {
|
||||
node: statement,
|
||||
transform: (ctx) => transformForReactiveStatement(statement, ctx),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Analyze the $derived scopes.
|
||||
* Transform source code to provide the correct type information in the `$derived(...)` expression.
|
||||
*/
|
||||
function* analyzeDollarDerivedScopes(result, svelteParseContext) {
|
||||
// No processing is needed if the user is determined not to be in Runes mode.
|
||||
if (svelteParseContext.runes === false)
|
||||
return;
|
||||
const scopeManager = result.scopeManager;
|
||||
const derivedReferences = scopeManager.globalScope.through.filter((reference) => reference.identifier.name === "$derived");
|
||||
if (!derivedReferences.length) {
|
||||
return;
|
||||
}
|
||||
setParent(result);
|
||||
for (const ref of derivedReferences) {
|
||||
const derived = ref.identifier;
|
||||
if (derived.parent.type === "CallExpression" &&
|
||||
derived.parent.callee === derived &&
|
||||
derived.parent.arguments[0]?.type !== "SpreadElement") {
|
||||
const node = derived.parent;
|
||||
yield {
|
||||
node,
|
||||
transform: (ctx) => transformForDollarDerived(node, ctx),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Analyze the render scopes.
|
||||
* Transform source code to provide the correct type information in the HTML templates.
|
||||
*/
|
||||
function analyzeRenderScopes(code, ctx, analyzeInTemplate) {
|
||||
ctx.appendOriginal(code.script.length);
|
||||
const renderFunctionName = ctx.generateUniqueId("render");
|
||||
ctx.appendVirtualScript(`export function ${renderFunctionName}(){`);
|
||||
analyzeInTemplate();
|
||||
ctx.appendOriginal(code.script.length + code.render.length);
|
||||
ctx.appendVirtualScript(`}`);
|
||||
ctx.restoreContext.addRestoreStatementProcess((node, result) => {
|
||||
if (node.type !== "ExportNamedDeclaration" ||
|
||||
node.declaration?.type !== "FunctionDeclaration" ||
|
||||
node.declaration?.id?.name !== renderFunctionName) {
|
||||
return false;
|
||||
}
|
||||
const program = result.ast;
|
||||
program.body.splice(program.body.indexOf(node), 1, ...node.declaration.body.body);
|
||||
for (const body of node.declaration.body.body) {
|
||||
body.parent = program;
|
||||
}
|
||||
const scopeManager = result.scopeManager;
|
||||
removeFunctionScope(node.declaration, scopeManager);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Applies the given transforms.
|
||||
* Note that intersecting transformations are not applied.
|
||||
*/
|
||||
function applyTransforms(transforms, ctx) {
|
||||
transforms.sort((a, b) => a.node.range[0] - b.node.range[0]);
|
||||
let offset = 0;
|
||||
for (const transform of transforms) {
|
||||
const range = transform.node.range;
|
||||
if (offset <= range[0]) {
|
||||
transform.transform(ctx);
|
||||
}
|
||||
offset = range[1];
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Transform for `$: id = ...` to `$: let id = ...`
|
||||
*/
|
||||
function transformForDeclareReactiveVar(statement, id, expression, tokens, ctx) {
|
||||
// e.g.
|
||||
// From:
|
||||
// $: id = x + y;
|
||||
//
|
||||
// To:
|
||||
// $: let id = fn()
|
||||
// function fn () { let tmp; return (tmp = x + y); }
|
||||
//
|
||||
//
|
||||
// From:
|
||||
// $: ({id} = foo);
|
||||
//
|
||||
// To:
|
||||
// $: let {id} = fn()
|
||||
// function fn () { let tmp; return (tmp = foo); }
|
||||
/**
|
||||
* The opening paren tokens for
|
||||
* `$: ({id} = foo);`
|
||||
* ^
|
||||
*/
|
||||
const openParens = [];
|
||||
/**
|
||||
* The equal token for
|
||||
* `$: ({id} = foo);`
|
||||
* ^
|
||||
*/
|
||||
let eq = null;
|
||||
/**
|
||||
* The closing paren tokens for
|
||||
* `$: ({id} = foo);`
|
||||
* ^
|
||||
*/
|
||||
const closeParens = [];
|
||||
/**
|
||||
* The closing paren token for
|
||||
* `$: id = (foo);`
|
||||
* ^
|
||||
*/
|
||||
let expressionCloseParen = null;
|
||||
const startIndex = sortedLastIndex(tokens, (target) => target.range[0] - statement.range[0]);
|
||||
for (let index = startIndex; index < tokens.length; index++) {
|
||||
const token = tokens[index];
|
||||
if (statement.range[1] <= token.range[0]) {
|
||||
break;
|
||||
}
|
||||
if (token.range[1] <= statement.range[0]) {
|
||||
continue;
|
||||
}
|
||||
if (token.value === "(" && token.range[1] <= expression.range[0]) {
|
||||
openParens.push(token);
|
||||
}
|
||||
if (token.value === "=" &&
|
||||
expression.left.range[1] <= token.range[0] &&
|
||||
token.range[1] <= expression.right.range[0]) {
|
||||
eq = token;
|
||||
}
|
||||
if (token.value === ")") {
|
||||
if (expression.range[1] <= token.range[0]) {
|
||||
closeParens.push(token);
|
||||
}
|
||||
else if (expression.right.range[1] <= token.range[0]) {
|
||||
expressionCloseParen = token;
|
||||
}
|
||||
}
|
||||
}
|
||||
const functionId = ctx.generateUniqueId("reactiveVariableScopeFunction");
|
||||
const tmpVarId = ctx.generateUniqueId("tmpVar");
|
||||
for (const token of openParens) {
|
||||
ctx.appendOriginal(token.range[0]);
|
||||
ctx.skipOriginalOffset(token.range[1] - token.range[0]);
|
||||
}
|
||||
ctx.appendOriginal(expression.range[0]);
|
||||
ctx.skipUntilOriginalOffset(id.range[0]);
|
||||
ctx.appendVirtualScript("let ");
|
||||
ctx.appendOriginal(eq ? eq.range[1] : expression.right.range[0]);
|
||||
ctx.appendVirtualScript(`${functionId}();\nfunction ${functionId}(){let ${tmpVarId};return (${tmpVarId} = `);
|
||||
ctx.appendOriginal(expression.right.range[1]);
|
||||
ctx.appendVirtualScript(`)`);
|
||||
for (const token of closeParens) {
|
||||
ctx.appendOriginal(token.range[0]);
|
||||
ctx.skipOriginalOffset(token.range[1] - token.range[0]);
|
||||
}
|
||||
ctx.appendOriginal(statement.range[1]);
|
||||
ctx.appendVirtualScript(`}`);
|
||||
ctx.restoreContext.addRestoreStatementProcess((node, result) => {
|
||||
if (node.type !== "SvelteReactiveStatement") {
|
||||
return false;
|
||||
}
|
||||
const reactiveStatement = node;
|
||||
if (reactiveStatement.body.type !== "VariableDeclaration" ||
|
||||
reactiveStatement.body.kind !== "let" ||
|
||||
reactiveStatement.body.declarations.length !== 1) {
|
||||
return false;
|
||||
}
|
||||
const [idDecl] = reactiveStatement.body.declarations;
|
||||
if (idDecl.type !== "VariableDeclarator" ||
|
||||
idDecl.id.type !== id.type ||
|
||||
idDecl.init?.type !== "CallExpression" ||
|
||||
idDecl.init.callee.type !== "Identifier" ||
|
||||
idDecl.init.callee.name !== functionId) {
|
||||
return false;
|
||||
}
|
||||
const program = result.ast;
|
||||
const nextIndex = program.body.indexOf(reactiveStatement) + 1;
|
||||
const fnDecl = program.body[nextIndex];
|
||||
if (!fnDecl ||
|
||||
fnDecl.type !== "FunctionDeclaration" ||
|
||||
fnDecl.id.name !== functionId ||
|
||||
fnDecl.body.body.length !== 2 ||
|
||||
fnDecl.body.body[0].type !== "VariableDeclaration" ||
|
||||
fnDecl.body.body[1].type !== "ReturnStatement") {
|
||||
return false;
|
||||
}
|
||||
const tmpVarDeclaration = fnDecl.body.body[0];
|
||||
if (tmpVarDeclaration.declarations.length !== 1 ||
|
||||
tmpVarDeclaration.declarations[0].type !== "VariableDeclarator") {
|
||||
return false;
|
||||
}
|
||||
const tempVarDeclId = tmpVarDeclaration.declarations[0].id;
|
||||
if (tempVarDeclId.type !== "Identifier" ||
|
||||
tempVarDeclId.name !== tmpVarId) {
|
||||
return false;
|
||||
}
|
||||
const returnStatement = fnDecl.body.body[1];
|
||||
const assignment = returnStatement.argument;
|
||||
if (assignment?.type !== "AssignmentExpression" ||
|
||||
assignment.left.type !== "Identifier" ||
|
||||
assignment.right.type !== expression.right.type) {
|
||||
return false;
|
||||
}
|
||||
const tempLeft = assignment.left;
|
||||
// Remove function declaration
|
||||
program.body.splice(nextIndex, 1);
|
||||
// Restore expression statement
|
||||
assignment.left = idDecl.id;
|
||||
assignment.loc = {
|
||||
start: idDecl.id.loc.start,
|
||||
end: expressionCloseParen
|
||||
? expressionCloseParen.loc.end
|
||||
: assignment.right.loc.end,
|
||||
};
|
||||
assignment.range = [
|
||||
idDecl.id.range[0],
|
||||
expressionCloseParen
|
||||
? expressionCloseParen.range[1]
|
||||
: assignment.right.range[1],
|
||||
];
|
||||
idDecl.id.parent = assignment;
|
||||
const newBody = {
|
||||
type: "ExpressionStatement",
|
||||
expression: assignment,
|
||||
directive: undefined,
|
||||
loc: statement.body.loc,
|
||||
range: statement.body.range,
|
||||
parent: reactiveStatement,
|
||||
};
|
||||
assignment.parent = newBody;
|
||||
reactiveStatement.body = newBody;
|
||||
// Restore statement end location
|
||||
reactiveStatement.range[1] = returnStatement.range[1];
|
||||
reactiveStatement.loc.end.line = returnStatement.loc.end.line;
|
||||
reactiveStatement.loc.end.column = returnStatement.loc.end.column;
|
||||
// Restore tokens
|
||||
addElementsToSortedArray(program.tokens, [...openParens, ...closeParens], (a, b) => a.range[0] - b.range[0]);
|
||||
const scopeManager = result.scopeManager;
|
||||
removeAllScopeAndVariableAndReference(tmpVarDeclaration, {
|
||||
visitorKeys: result.visitorKeys,
|
||||
scopeManager,
|
||||
});
|
||||
removeFunctionScope(fnDecl, scopeManager);
|
||||
const scope = getProgramScope(scopeManager);
|
||||
for (const reference of getAllReferences(idDecl.id, scope)) {
|
||||
reference.writeExpr = assignment.right;
|
||||
}
|
||||
removeIdentifierReference(tempLeft, scope);
|
||||
removeIdentifierVariable(tempVarDeclId, scope);
|
||||
removeIdentifierReference(idDecl.init.callee, scope);
|
||||
removeIdentifierVariable(idDecl.id, scope);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Transform for `$: ...` to `$: function foo(){...}`
|
||||
*/
|
||||
function transformForReactiveStatement(statement, ctx) {
|
||||
const functionId = ctx.generateUniqueId("reactiveStatementScopeFunction");
|
||||
const originalBody = statement.body;
|
||||
ctx.appendOriginal(originalBody.range[0]);
|
||||
ctx.appendVirtualScript(`export function ${functionId}(){`);
|
||||
ctx.appendOriginal(originalBody.range[1]);
|
||||
ctx.appendVirtualScript(`}`);
|
||||
ctx.appendOriginal(statement.range[1]);
|
||||
ctx.restoreContext.addRestoreStatementProcess((node, result) => {
|
||||
if (node.type !== "SvelteReactiveStatement") {
|
||||
return false;
|
||||
}
|
||||
const reactiveStatement = node;
|
||||
const body = reactiveStatement.body;
|
||||
if (body.type !== "ExportNamedDeclaration" ||
|
||||
body.declaration?.type !== "FunctionDeclaration" ||
|
||||
body.declaration?.id?.name !== functionId) {
|
||||
return false;
|
||||
}
|
||||
reactiveStatement.body = body.declaration.body.body[0];
|
||||
reactiveStatement.body.parent = reactiveStatement;
|
||||
const scopeManager = result.scopeManager;
|
||||
removeFunctionScope(body.declaration, scopeManager);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Transform for `$derived(expr)` to `$derived((()=>{ type This = typeof this; return fn(); function fn (this: This) { return expr } })())`
|
||||
*/
|
||||
function transformForDollarDerived(derivedCall, ctx) {
|
||||
const functionId = ctx.generateUniqueId("$derivedArgument");
|
||||
const thisTypeId = ctx.generateUniqueId("$This");
|
||||
const expression = derivedCall.arguments[0];
|
||||
ctx.appendOriginal(expression.range[0]);
|
||||
ctx.appendVirtualScript(`(()=>{type ${thisTypeId} = typeof this; return ${functionId}();function ${functionId}(this: ${thisTypeId}){return `);
|
||||
ctx.appendOriginal(expression.range[1]);
|
||||
ctx.appendVirtualScript(`}})()`);
|
||||
ctx.restoreContext.addRestoreExpressionProcess({
|
||||
target: "CallExpression",
|
||||
restore: (node, result) => {
|
||||
if (node.callee.type !== "Identifier" ||
|
||||
node.callee.name !== "$derived") {
|
||||
return false;
|
||||
}
|
||||
const arg = node.arguments[0];
|
||||
if (!arg ||
|
||||
arg.type !== "CallExpression" ||
|
||||
arg.arguments.length !== 0 ||
|
||||
arg.callee.type !== "ArrowFunctionExpression" ||
|
||||
arg.callee.body.type !== "BlockStatement" ||
|
||||
arg.callee.body.body.length !== 3) {
|
||||
return false;
|
||||
}
|
||||
const thisTypeNode = arg.callee.body.body[0];
|
||||
if (thisTypeNode.type !== "TSTypeAliasDeclaration" ||
|
||||
thisTypeNode.id.name !== thisTypeId) {
|
||||
return false;
|
||||
}
|
||||
const returnNode = arg.callee.body.body[1];
|
||||
if (returnNode.type !== "ReturnStatement" ||
|
||||
returnNode.argument?.type !== "CallExpression" ||
|
||||
returnNode.argument.callee.type !== "Identifier" ||
|
||||
returnNode.argument.callee.name !== functionId) {
|
||||
return false;
|
||||
}
|
||||
const fnNode = arg.callee.body.body[2];
|
||||
if (fnNode.type !== "FunctionDeclaration" ||
|
||||
fnNode.id.name !== functionId ||
|
||||
fnNode.body.body.length !== 1 ||
|
||||
fnNode.body.body[0].type !== "ReturnStatement" ||
|
||||
!fnNode.body.body[0].argument ||
|
||||
fnNode.params[0]?.type !== "Identifier" ||
|
||||
!fnNode.params[0].typeAnnotation ||
|
||||
fnNode.params[0].typeAnnotation.typeAnnotation.type !==
|
||||
"TSTypeReference" ||
|
||||
fnNode.params[0].typeAnnotation.typeAnnotation.typeName.type !==
|
||||
"Identifier") {
|
||||
return false;
|
||||
}
|
||||
const expr = fnNode.body.body[0].argument;
|
||||
node.arguments[0] = expr;
|
||||
expr.parent = node;
|
||||
const scopeManager = result.scopeManager;
|
||||
const fnScope = scopeManager.acquire(fnNode);
|
||||
removeIdentifierVariable(fnNode.params[0], fnScope);
|
||||
removeIdentifierReference(fnNode.params[0].typeAnnotation.typeAnnotation.typeName, fnScope);
|
||||
removeFunctionScope(fnNode, scopeManager);
|
||||
const scope = scopeManager.acquire(arg.callee);
|
||||
removeIdentifierVariable(thisTypeNode.id, scope);
|
||||
removeIdentifierReference(returnNode.argument.callee, scope);
|
||||
removeFunctionScope(arg.callee, scopeManager);
|
||||
return true;
|
||||
},
|
||||
});
|
||||
}
|
||||
/** Remove function scope and marge child scopes to upper scope */
|
||||
function removeFunctionScope(node, scopeManager) {
|
||||
const scope = scopeManager.acquire(node);
|
||||
const upper = scope.upper;
|
||||
// Remove render function variable
|
||||
if (node.id) {
|
||||
removeIdentifierVariable(node.id, upper);
|
||||
removeIdentifierReference(node.id, upper);
|
||||
}
|
||||
replaceScope(scopeManager, scope, scope.childScopes);
|
||||
// Marge scope
|
||||
// * marge variables
|
||||
for (const variable of scope.variables) {
|
||||
if (variable.name === "arguments" && variable.defs.length === 0) {
|
||||
continue;
|
||||
}
|
||||
const upperVariable = upper.set.get(variable.name);
|
||||
if (upperVariable) {
|
||||
addElementsToSortedArray(upperVariable.identifiers, variable.identifiers, (a, b) => a.range[0] - b.range[0]);
|
||||
addElementsToSortedArray(upperVariable.defs, variable.defs, (a, b) => a.node.range[0] - b.node.range[0]);
|
||||
addAllReferences(upperVariable.references, variable.references);
|
||||
}
|
||||
else {
|
||||
upper.set.set(variable.name, variable);
|
||||
addVariable(upper.variables, variable);
|
||||
variable.scope = upper;
|
||||
}
|
||||
for (const reference of variable.references) {
|
||||
if (reference.from === scope) {
|
||||
reference.from = upper;
|
||||
}
|
||||
reference.resolved = upperVariable || variable;
|
||||
}
|
||||
}
|
||||
// * marge references
|
||||
addAllReferences(upper.references, scope.references);
|
||||
for (const reference of scope.references) {
|
||||
if (reference.from === scope) {
|
||||
reference.from = upper;
|
||||
}
|
||||
}
|
||||
}
|
||||
21
node_modules/svelte-eslint-parser/lib/parser/typescript/context.d.ts
generated
vendored
Normal file
21
node_modules/svelte-eslint-parser/lib/parser/typescript/context.d.ts
generated
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
import { RestoreContext } from "./restore.js";
|
||||
import type { TSESParseForESLintResult } from "./types.js";
|
||||
/**
|
||||
* Context for virtual TypeScript code.
|
||||
* See https://github.com/sveltejs/svelte-eslint-parser/blob/main/docs/internal-mechanism.md#scope-types
|
||||
*/
|
||||
export declare class VirtualTypeScriptContext {
|
||||
private readonly originalCode;
|
||||
readonly restoreContext: RestoreContext;
|
||||
script: string;
|
||||
private consumedIndex;
|
||||
private readonly unique;
|
||||
_beforeResult: TSESParseForESLintResult | null;
|
||||
constructor(code: string);
|
||||
skipOriginalOffset(offset: number): void;
|
||||
skipUntilOriginalOffset(offset: number): void;
|
||||
appendOriginalToEnd(): void;
|
||||
appendOriginal(index: number): void;
|
||||
appendVirtualScript(virtualFragment: string): void;
|
||||
generateUniqueId(base: string): string;
|
||||
}
|
||||
44
node_modules/svelte-eslint-parser/lib/parser/typescript/context.js
generated
vendored
Normal file
44
node_modules/svelte-eslint-parser/lib/parser/typescript/context.js
generated
vendored
Normal file
@@ -0,0 +1,44 @@
|
||||
import { UniqueIdGenerator } from "../../context/unique.js";
|
||||
import { RestoreContext } from "./restore.js";
|
||||
/**
|
||||
* Context for virtual TypeScript code.
|
||||
* See https://github.com/sveltejs/svelte-eslint-parser/blob/main/docs/internal-mechanism.md#scope-types
|
||||
*/
|
||||
export class VirtualTypeScriptContext {
|
||||
constructor(code) {
|
||||
this.script = "";
|
||||
this.consumedIndex = 0;
|
||||
this.unique = new UniqueIdGenerator();
|
||||
this._beforeResult = null;
|
||||
this.originalCode = code;
|
||||
this.restoreContext = new RestoreContext(code);
|
||||
}
|
||||
skipOriginalOffset(offset) {
|
||||
this.consumedIndex += offset;
|
||||
}
|
||||
skipUntilOriginalOffset(offset) {
|
||||
this.consumedIndex = Math.max(offset, this.consumedIndex);
|
||||
}
|
||||
appendOriginalToEnd() {
|
||||
this.appendOriginal(this.originalCode.length);
|
||||
}
|
||||
appendOriginal(index) {
|
||||
if (this.consumedIndex >= index) {
|
||||
return;
|
||||
}
|
||||
this.restoreContext.addOffset({
|
||||
original: this.consumedIndex,
|
||||
dist: this.script.length,
|
||||
});
|
||||
this.script += this.originalCode.slice(this.consumedIndex, index);
|
||||
this.consumedIndex = index;
|
||||
}
|
||||
appendVirtualScript(virtualFragment) {
|
||||
const start = this.script.length;
|
||||
this.script += virtualFragment;
|
||||
this.restoreContext.addVirtualFragmentRange(start, this.script.length);
|
||||
}
|
||||
generateUniqueId(base) {
|
||||
return this.unique.generate(base, this.originalCode, this.script);
|
||||
}
|
||||
}
|
||||
16
node_modules/svelte-eslint-parser/lib/parser/typescript/index.d.ts
generated
vendored
Normal file
16
node_modules/svelte-eslint-parser/lib/parser/typescript/index.d.ts
generated
vendored
Normal file
@@ -0,0 +1,16 @@
|
||||
import type { ESLintExtendedProgram } from "../index.js";
|
||||
import type { NormalizedParserOptions } from "../parser-options.js";
|
||||
import type { SvelteParseContext } from "../svelte-parse-context.js";
|
||||
import type { AnalyzeTypeScriptContext } from "./analyze/index.js";
|
||||
/**
|
||||
* Parse for TypeScript in <script>
|
||||
*/
|
||||
export declare function parseTypeScriptInSvelte(code: {
|
||||
script: string;
|
||||
render: string;
|
||||
rootScope: string;
|
||||
}, attrs: Record<string, string | undefined>, parserOptions: NormalizedParserOptions, context: AnalyzeTypeScriptContext): ESLintExtendedProgram;
|
||||
/**
|
||||
* Parse for TypeScript
|
||||
*/
|
||||
export declare function parseTypeScript(code: string, attrs: Record<string, string | undefined>, parserOptions: NormalizedParserOptions, svelteParseContext: SvelteParseContext): ESLintExtendedProgram;
|
||||
79
node_modules/svelte-eslint-parser/lib/parser/typescript/index.js
generated
vendored
Normal file
79
node_modules/svelte-eslint-parser/lib/parser/typescript/index.js
generated
vendored
Normal file
@@ -0,0 +1,79 @@
|
||||
import { parseScript, parseScriptInSvelte, parseScriptWithoutAnalyzeScope, } from "../script.js";
|
||||
import { analyzeTypeScript, analyzeTypeScriptInSvelte, } from "./analyze/index.js";
|
||||
import { setParent } from "./set-parent.js";
|
||||
import { getCompanionToRefresh, primeTranslationCache, reloadCompanionInProjectServices, } from "../../ts-sys-hook.js";
|
||||
import { getJavaScriptParserOptions } from "./javascript.js";
|
||||
/**
|
||||
* Parse for TypeScript in <script>
|
||||
*/
|
||||
export function parseTypeScriptInSvelte(code, attrs, parserOptions, context) {
|
||||
const tsCtx = analyzeTypeScriptInSvelte(code, attrs, parserOptions, context);
|
||||
// Share the shim with the ts.sys hook so projectService reads hit a cache.
|
||||
if (parserOptions.filePath) {
|
||||
primeTranslationCache(parserOptions.filePath, tsCtx.script);
|
||||
// Before the component's own parse, so when the program already holds the
|
||||
// companion, the component's rules see it current too, as in a component
|
||||
// that imports itself.
|
||||
refreshCompanion(parserOptions.filePath, parserOptions);
|
||||
}
|
||||
// Virtual scripts can be parsed repeatedly for the same file. In single-run
|
||||
// mode, typescript-eslint falls back to an isolated program on later calls,
|
||||
// losing project imports and compiler options.
|
||||
let result = parseScriptInSvelte(tsCtx.script, attrs, {
|
||||
...parserOptions,
|
||||
disallowAutomaticSingleRunInference: true,
|
||||
});
|
||||
const jsOptions = getJavaScriptParserOptions(result, attrs, parserOptions);
|
||||
if (jsOptions) {
|
||||
result = parseScriptInSvelte(tsCtx.script, attrs, jsOptions);
|
||||
}
|
||||
tsCtx.restoreContext.restore(result);
|
||||
return result;
|
||||
}
|
||||
/**
|
||||
* Let the type-aware parser pick up the new content of the `X.svelte.ts`
|
||||
* companion that importers see. See `getCompanionToRefresh`.
|
||||
*/
|
||||
function refreshCompanion(filePath, parserOptions) {
|
||||
if (parserOptions.projectService != null ||
|
||||
parserOptions.EXPERIMENTAL_useProjectService != null) {
|
||||
const companion = getCompanionToRefresh(filePath);
|
||||
if (companion)
|
||||
reloadCompanionInProjectServices(companion.filePath);
|
||||
return;
|
||||
}
|
||||
if (parserOptions.project == null)
|
||||
return;
|
||||
const companion = getCompanionToRefresh(filePath);
|
||||
if (!companion)
|
||||
return;
|
||||
// Parsing the companion path makes typescript-eslint fire the companion's
|
||||
// file watcher, as it does for a linted file.
|
||||
try {
|
||||
parseScriptWithoutAnalyzeScope(companion.code, { lang: "ts" }, {
|
||||
...parserOptions,
|
||||
filePath: companion.filePath,
|
||||
disallowAutomaticSingleRunInference: true,
|
||||
});
|
||||
}
|
||||
catch {
|
||||
// The refresh is best effort. Linting the component itself has succeeded.
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Parse for TypeScript
|
||||
*/
|
||||
export function parseTypeScript(code, attrs, parserOptions, svelteParseContext) {
|
||||
const tsCtx = analyzeTypeScript(code, attrs, parserOptions, svelteParseContext);
|
||||
let result = parseScript(tsCtx.script, attrs, {
|
||||
...parserOptions,
|
||||
disallowAutomaticSingleRunInference: true,
|
||||
});
|
||||
const jsOptions = getJavaScriptParserOptions(result, attrs, parserOptions);
|
||||
if (jsOptions) {
|
||||
result = parseScript(tsCtx.script, attrs, jsOptions);
|
||||
}
|
||||
setParent(result);
|
||||
tsCtx.restoreContext.restore(result);
|
||||
return result;
|
||||
}
|
||||
9
node_modules/svelte-eslint-parser/lib/parser/typescript/javascript.d.ts
generated
vendored
Normal file
9
node_modules/svelte-eslint-parser/lib/parser/typescript/javascript.d.ts
generated
vendored
Normal file
@@ -0,0 +1,9 @@
|
||||
import type { ESLintExtendedProgram } from "../index.js";
|
||||
import type { NormalizedParserOptions } from "../parser-options.js";
|
||||
/**
|
||||
* TypeScript treats unknown extensions as TS, where JSDoc type annotations
|
||||
* are ignored. Use a JS source file for the virtual component instead.
|
||||
* Keep the original project intact: its source files and checker can be
|
||||
* shared by other lint calls, including calls using projectService.
|
||||
*/
|
||||
export declare function getJavaScriptParserOptions(result: ESLintExtendedProgram, attrs: Record<string, string | undefined>, parserOptions: NormalizedParserOptions): NormalizedParserOptions | null;
|
||||
48
node_modules/svelte-eslint-parser/lib/parser/typescript/javascript.js
generated
vendored
Normal file
48
node_modules/svelte-eslint-parser/lib/parser/typescript/javascript.js
generated
vendored
Normal file
@@ -0,0 +1,48 @@
|
||||
import { withoutProjectParserOptions } from "../parser-options.js";
|
||||
import { loadNewestModule } from "../../utils/cjs-module.js";
|
||||
/**
|
||||
* TypeScript treats unknown extensions as TS, where JSDoc type annotations
|
||||
* are ignored. Use a JS source file for the virtual component instead.
|
||||
* Keep the original project intact: its source files and checker can be
|
||||
* shared by other lint calls, including calls using projectService.
|
||||
*/
|
||||
export function getJavaScriptParserOptions(result, attrs, parserOptions) {
|
||||
if (attrs.lang && attrs.lang !== "js" && attrs.lang !== "javascript") {
|
||||
return null;
|
||||
}
|
||||
const originalProgram = result.services?.program;
|
||||
if (!originalProgram || !parserOptions.filePath)
|
||||
return null;
|
||||
const originalSource = originalProgram.getSourceFile(parserOptions.filePath);
|
||||
if (!originalSource)
|
||||
return null;
|
||||
const ts = loadNewestModule("typescript");
|
||||
if (originalSource.flags & ts.NodeFlags.JavaScriptFile)
|
||||
return null;
|
||||
const source = ts.createSourceFile(originalSource.fileName, originalSource.text, originalSource.languageVersion, true, ts.ScriptKind.JS);
|
||||
source.impliedNodeFormat = originalSource.impliedNodeFormat;
|
||||
const options = {
|
||||
...originalProgram.getCompilerOptions(),
|
||||
allowJs: true,
|
||||
allowNonTsExtensions: true,
|
||||
};
|
||||
const host = ts.createCompilerHost(options, true);
|
||||
const getSourceFile = host.getSourceFile.bind(host);
|
||||
host.getCurrentDirectory = () => originalProgram.getCurrentDirectory();
|
||||
host.getSourceFile = (fileName, ...args) => {
|
||||
const existing = originalProgram.getSourceFile(fileName);
|
||||
if (existing === originalSource)
|
||||
return source;
|
||||
return existing ?? getSourceFile(fileName, ...args);
|
||||
};
|
||||
const program = ts.createProgram({
|
||||
rootNames: originalProgram.getRootFileNames(),
|
||||
options,
|
||||
host,
|
||||
projectReferences: originalProgram.getProjectReferences(),
|
||||
});
|
||||
return {
|
||||
...withoutProjectParserOptions(parserOptions),
|
||||
programs: [program],
|
||||
};
|
||||
}
|
||||
50
node_modules/svelte-eslint-parser/lib/parser/typescript/restore.d.ts
generated
vendored
Normal file
50
node_modules/svelte-eslint-parser/lib/parser/typescript/restore.d.ts
generated
vendored
Normal file
@@ -0,0 +1,50 @@
|
||||
import type { TSESTree } from "@typescript-eslint/types";
|
||||
import type { TSESParseForESLintResult } from "./types.js";
|
||||
import type { SvelteReactiveStatement } from "../../ast/script.js";
|
||||
/**
|
||||
* A function that restores the statement.
|
||||
* @param node The node to restore.
|
||||
* @param result The result of parsing.
|
||||
* @returns
|
||||
* If `false`, it indicates that the specified node was not processed.
|
||||
*
|
||||
* If `true`, it indicates that the specified node was processed for processing.
|
||||
* This process will no longer be called.
|
||||
*/
|
||||
type RestoreStatementProcess = (node: TSESTree.Statement | SvelteReactiveStatement, result: TSESParseForESLintResult) => boolean;
|
||||
/**
|
||||
* A function that restores the expression.
|
||||
* @param node The node to restore.
|
||||
* @param result The result of parsing.
|
||||
* @returns
|
||||
* If `false`, it indicates that the specified node was not processed.
|
||||
*
|
||||
* If `true`, it indicates that the specified node was processed for processing.
|
||||
* This process will no longer be called.
|
||||
*/
|
||||
type RestoreExpressionProcess<T extends TSESTree.Expression> = {
|
||||
target: T["type"];
|
||||
restore: (node: T, result: TSESParseForESLintResult) => boolean;
|
||||
};
|
||||
export declare class RestoreContext {
|
||||
private readonly originalLocs;
|
||||
private readonly offsets;
|
||||
private readonly virtualFragments;
|
||||
private readonly restoreStatementProcesses;
|
||||
private readonly restoreExpressionProcesses;
|
||||
constructor(code: string);
|
||||
addRestoreStatementProcess(process: RestoreStatementProcess): void;
|
||||
addRestoreExpressionProcess<T extends TSESTree.Expression>(process: RestoreExpressionProcess<T>): void;
|
||||
addOffset(offset: {
|
||||
original: number;
|
||||
dist: number;
|
||||
}): void;
|
||||
addVirtualFragmentRange(start: number, end: number): void;
|
||||
/**
|
||||
* Restore AST nodes
|
||||
*/
|
||||
restore(result: TSESParseForESLintResult): void;
|
||||
private remapLocation;
|
||||
private getRemapRange;
|
||||
}
|
||||
export {};
|
||||
171
node_modules/svelte-eslint-parser/lib/parser/typescript/restore.js
generated
vendored
Normal file
171
node_modules/svelte-eslint-parser/lib/parser/typescript/restore.js
generated
vendored
Normal file
@@ -0,0 +1,171 @@
|
||||
import { traverseNodes } from "../../traverse.js";
|
||||
import { LinesAndColumns } from "../../context/index.js";
|
||||
export class RestoreContext {
|
||||
constructor(code) {
|
||||
this.offsets = [];
|
||||
this.virtualFragments = [];
|
||||
this.restoreStatementProcesses = [];
|
||||
this.restoreExpressionProcesses = [];
|
||||
this.originalLocs = new LinesAndColumns(code);
|
||||
}
|
||||
addRestoreStatementProcess(process) {
|
||||
this.restoreStatementProcesses.push(process);
|
||||
}
|
||||
addRestoreExpressionProcess(process) {
|
||||
this.restoreExpressionProcesses.push(process);
|
||||
}
|
||||
addOffset(offset) {
|
||||
this.offsets.push(offset);
|
||||
}
|
||||
addVirtualFragmentRange(start, end) {
|
||||
const peek = this.virtualFragments[this.virtualFragments.length - 1];
|
||||
if (peek && peek.end === start) {
|
||||
peek.end = end;
|
||||
return;
|
||||
}
|
||||
this.virtualFragments.push({ start, end });
|
||||
}
|
||||
/**
|
||||
* Restore AST nodes
|
||||
*/
|
||||
restore(result) {
|
||||
remapLocations(result, {
|
||||
remapLocation: (n) => this.remapLocation(n),
|
||||
removeToken: (token) => this.virtualFragments.some((f) => f.start <= token.range[0] && token.range[1] <= f.end),
|
||||
});
|
||||
restoreStatements(result, this.restoreStatementProcesses);
|
||||
restoreExpressions(result, this.restoreExpressionProcesses);
|
||||
// Adjust program node location
|
||||
const firstOffset = Math.min(...[result.ast.body[0], result.ast.tokens?.[0], result.ast.comments?.[0]]
|
||||
.filter((t) => Boolean(t))
|
||||
.map((t) => t.range[0]));
|
||||
if (firstOffset < result.ast.range[0]) {
|
||||
result.ast.range[0] = firstOffset;
|
||||
result.ast.loc.start = this.originalLocs.getLocFromIndex(firstOffset);
|
||||
}
|
||||
}
|
||||
remapLocation(node) {
|
||||
let [start, end] = node.range;
|
||||
const startFragment = this.virtualFragments.find((f) => f.start <= start && start < f.end);
|
||||
if (startFragment) {
|
||||
start = startFragment.end;
|
||||
}
|
||||
const endFragment = this.virtualFragments.find((f) => f.start < end && end <= f.end);
|
||||
if (endFragment) {
|
||||
end = endFragment.start;
|
||||
if (startFragment === endFragment) {
|
||||
start = startFragment.start;
|
||||
}
|
||||
}
|
||||
if (end < start) {
|
||||
const w = start;
|
||||
start = end;
|
||||
end = w;
|
||||
}
|
||||
const locs = this.originalLocs.getLocations(...this.getRemapRange(start, end));
|
||||
node.loc = locs.loc;
|
||||
node.range = locs.range;
|
||||
if (node.start != null) {
|
||||
delete node.start;
|
||||
}
|
||||
if (node.end != null) {
|
||||
delete node.end;
|
||||
}
|
||||
}
|
||||
getRemapRange(start, end) {
|
||||
if (!this.offsets.length) {
|
||||
return [start, end];
|
||||
}
|
||||
let lastStart = this.offsets[0];
|
||||
let lastEnd = this.offsets[0];
|
||||
for (const offset of this.offsets) {
|
||||
if (offset.dist <= start) {
|
||||
lastStart = offset;
|
||||
}
|
||||
if (offset.dist < end) {
|
||||
lastEnd = offset;
|
||||
}
|
||||
else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
const remapStart = lastStart.original + (start - lastStart.dist);
|
||||
const remapEnd = lastEnd.original + (end - lastEnd.dist);
|
||||
return [remapStart, remapEnd];
|
||||
}
|
||||
}
|
||||
/** Restore locations */
|
||||
function remapLocations(result, { remapLocation, removeToken, }) {
|
||||
const traversed = new Map();
|
||||
// remap locations
|
||||
traverseNodes(result.ast, {
|
||||
visitorKeys: result.visitorKeys,
|
||||
enterNode: (node, parent) => {
|
||||
node.parent = parent;
|
||||
if (!traversed.has(node)) {
|
||||
traversed.set(node, parent);
|
||||
remapLocation(node);
|
||||
}
|
||||
},
|
||||
leaveNode: (_node) => {
|
||||
// noop
|
||||
},
|
||||
});
|
||||
const tokens = [];
|
||||
for (const token of result.ast.tokens || []) {
|
||||
if (removeToken(token)) {
|
||||
continue;
|
||||
}
|
||||
remapLocation(token);
|
||||
tokens.push(token);
|
||||
}
|
||||
result.ast.tokens = tokens;
|
||||
// Virtual code can embed copies of user source (a `$props()` default, the
|
||||
// props type text), so comments inside those copies must be dropped too.
|
||||
const comments = [];
|
||||
for (const comment of result.ast.comments || []) {
|
||||
if (removeToken(comment)) {
|
||||
continue;
|
||||
}
|
||||
remapLocation(comment);
|
||||
comments.push(comment);
|
||||
}
|
||||
result.ast.comments = comments;
|
||||
}
|
||||
/** Restore statement nodes */
|
||||
function restoreStatements(result, restoreStatementProcesses) {
|
||||
const restoreStatementProcessesSet = new Set(restoreStatementProcesses);
|
||||
for (const node of [...result.ast.body]) {
|
||||
if (!restoreStatementProcessesSet.size) {
|
||||
break;
|
||||
}
|
||||
for (const proc of restoreStatementProcessesSet) {
|
||||
if (proc(node, result)) {
|
||||
restoreStatementProcessesSet.delete(proc);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/** Restore expression nodes */
|
||||
function restoreExpressions(result, restoreExpressionProcesses) {
|
||||
if (restoreExpressionProcesses.length === 0)
|
||||
return;
|
||||
const restoreExpressionProcessesSet = new Set(restoreExpressionProcesses);
|
||||
traverseNodes(result.ast, {
|
||||
visitorKeys: result.visitorKeys,
|
||||
enterNode(node) {
|
||||
for (const proc of restoreExpressionProcessesSet) {
|
||||
if (proc.target === node.type) {
|
||||
if (proc.restore(node, result)) {
|
||||
restoreExpressionProcessesSet.delete(proc);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
},
|
||||
leaveNode() {
|
||||
/* noop */
|
||||
},
|
||||
});
|
||||
}
|
||||
3
node_modules/svelte-eslint-parser/lib/parser/typescript/set-parent.d.ts
generated
vendored
Normal file
3
node_modules/svelte-eslint-parser/lib/parser/typescript/set-parent.d.ts
generated
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
import type { ESLintExtendedProgram } from "../index.js";
|
||||
import type { TSESParseForESLintResult } from "./types.js";
|
||||
export declare function setParent(result: ESLintExtendedProgram | TSESParseForESLintResult): void;
|
||||
15
node_modules/svelte-eslint-parser/lib/parser/typescript/set-parent.js
generated
vendored
Normal file
15
node_modules/svelte-eslint-parser/lib/parser/typescript/set-parent.js
generated
vendored
Normal file
@@ -0,0 +1,15 @@
|
||||
import { traverseNodes } from "../../index.js";
|
||||
export function setParent(result) {
|
||||
if (result.ast.body.some((node) => node.parent)) {
|
||||
return;
|
||||
}
|
||||
traverseNodes(result.ast, {
|
||||
visitorKeys: result.visitorKeys,
|
||||
enterNode(node, parent) {
|
||||
node.parent = parent;
|
||||
},
|
||||
leaveNode() {
|
||||
// noop
|
||||
},
|
||||
});
|
||||
}
|
||||
2
node_modules/svelte-eslint-parser/lib/parser/typescript/types.d.ts
generated
vendored
Normal file
2
node_modules/svelte-eslint-parser/lib/parser/typescript/types.d.ts
generated
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
import type { parseForESLint } from "@typescript-eslint/parser";
|
||||
export type TSESParseForESLintResult = ReturnType<typeof parseForESLint>;
|
||||
1
node_modules/svelte-eslint-parser/lib/parser/typescript/types.js
generated
vendored
Normal file
1
node_modules/svelte-eslint-parser/lib/parser/typescript/types.js
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
export {};
|
||||
Reference in New Issue
Block a user