first commit

This commit is contained in:
douboer
2026-01-14 13:05:57 +08:00
commit 0a7d2c5c20
1224 changed files with 1045848 additions and 0 deletions

21
node_modules/@vue/compiler-core/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2018-present, Yuxi (Evan) You
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

1
node_modules/@vue/compiler-core/README.md generated vendored Normal file
View File

@@ -0,0 +1 @@
# @vue/compiler-core

6888
node_modules/@vue/compiler-core/dist/compiler-core.cjs.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

1100
node_modules/@vue/compiler-core/dist/compiler-core.d.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

7
node_modules/@vue/compiler-core/index.js generated vendored Normal file
View File

@@ -0,0 +1,7 @@
'use strict'
if (process.env.NODE_ENV === 'production') {
module.exports = require('./dist/compiler-core.cjs.prod.js')
} else {
module.exports = require('./dist/compiler-core.cjs.js')
}

58
node_modules/@vue/compiler-core/package.json generated vendored Normal file
View File

@@ -0,0 +1,58 @@
{
"name": "@vue/compiler-core",
"version": "3.5.26",
"description": "@vue/compiler-core",
"main": "index.js",
"module": "dist/compiler-core.esm-bundler.js",
"types": "dist/compiler-core.d.ts",
"files": [
"index.js",
"dist"
],
"exports": {
".": {
"types": "./dist/compiler-core.d.ts",
"node": {
"production": "./dist/compiler-core.cjs.prod.js",
"development": "./dist/compiler-core.cjs.js",
"default": "./index.js"
},
"module": "./dist/compiler-core.esm-bundler.js",
"import": "./dist/compiler-core.esm-bundler.js",
"require": "./index.js"
},
"./*": "./*"
},
"buildOptions": {
"name": "VueCompilerCore",
"compat": true,
"formats": [
"esm-bundler",
"cjs"
]
},
"repository": {
"type": "git",
"url": "git+https://github.com/vuejs/core.git",
"directory": "packages/compiler-core"
},
"keywords": [
"vue"
],
"author": "Evan You",
"license": "MIT",
"bugs": {
"url": "https://github.com/vuejs/core/issues"
},
"homepage": "https://github.com/vuejs/core/tree/main/packages/compiler-core#readme",
"dependencies": {
"@babel/parser": "^7.28.5",
"entities": "^7.0.0",
"estree-walker": "^2.0.2",
"source-map-js": "^1.2.1",
"@vue/shared": "3.5.26"
},
"devDependencies": {
"@babel/types": "^7.28.5"
}
}

21
node_modules/@vue/compiler-dom/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2018-present, Yuxi (Evan) You
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

1
node_modules/@vue/compiler-dom/README.md generated vendored Normal file
View File

@@ -0,0 +1 @@
# @vue/compiler-dom

934
node_modules/@vue/compiler-dom/dist/compiler-dom.cjs.js generated vendored Normal file
View File

@@ -0,0 +1,934 @@
/**
* @vue/compiler-dom v3.5.26
* (c) 2018-present Yuxi (Evan) You and Vue contributors
* @license MIT
**/
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var compilerCore = require('@vue/compiler-core');
var shared = require('@vue/shared');
const V_MODEL_RADIO = /* @__PURE__ */ Symbol(`vModelRadio` );
const V_MODEL_CHECKBOX = /* @__PURE__ */ Symbol(
`vModelCheckbox`
);
const V_MODEL_TEXT = /* @__PURE__ */ Symbol(`vModelText` );
const V_MODEL_SELECT = /* @__PURE__ */ Symbol(
`vModelSelect`
);
const V_MODEL_DYNAMIC = /* @__PURE__ */ Symbol(
`vModelDynamic`
);
const V_ON_WITH_MODIFIERS = /* @__PURE__ */ Symbol(
`vOnModifiersGuard`
);
const V_ON_WITH_KEYS = /* @__PURE__ */ Symbol(
`vOnKeysGuard`
);
const V_SHOW = /* @__PURE__ */ Symbol(`vShow` );
const TRANSITION = /* @__PURE__ */ Symbol(`Transition` );
const TRANSITION_GROUP = /* @__PURE__ */ Symbol(
`TransitionGroup`
);
compilerCore.registerRuntimeHelpers({
[V_MODEL_RADIO]: `vModelRadio`,
[V_MODEL_CHECKBOX]: `vModelCheckbox`,
[V_MODEL_TEXT]: `vModelText`,
[V_MODEL_SELECT]: `vModelSelect`,
[V_MODEL_DYNAMIC]: `vModelDynamic`,
[V_ON_WITH_MODIFIERS]: `withModifiers`,
[V_ON_WITH_KEYS]: `withKeys`,
[V_SHOW]: `vShow`,
[TRANSITION]: `Transition`,
[TRANSITION_GROUP]: `TransitionGroup`
});
const parserOptions = {
parseMode: "html",
isVoidTag: shared.isVoidTag,
isNativeTag: (tag) => shared.isHTMLTag(tag) || shared.isSVGTag(tag) || shared.isMathMLTag(tag),
isPreTag: (tag) => tag === "pre",
isIgnoreNewlineTag: (tag) => tag === "pre" || tag === "textarea",
decodeEntities: void 0,
isBuiltInComponent: (tag) => {
if (tag === "Transition" || tag === "transition") {
return TRANSITION;
} else if (tag === "TransitionGroup" || tag === "transition-group") {
return TRANSITION_GROUP;
}
},
// https://html.spec.whatwg.org/multipage/parsing.html#tree-construction-dispatcher
getNamespace(tag, parent, rootNamespace) {
let ns = parent ? parent.ns : rootNamespace;
if (parent && ns === 2) {
if (parent.tag === "annotation-xml") {
if (tag === "svg") {
return 1;
}
if (parent.props.some(
(a) => a.type === 6 && a.name === "encoding" && a.value != null && (a.value.content === "text/html" || a.value.content === "application/xhtml+xml")
)) {
ns = 0;
}
} else if (/^m(?:[ions]|text)$/.test(parent.tag) && tag !== "mglyph" && tag !== "malignmark") {
ns = 0;
}
} else if (parent && ns === 1) {
if (parent.tag === "foreignObject" || parent.tag === "desc" || parent.tag === "title") {
ns = 0;
}
}
if (ns === 0) {
if (tag === "svg") {
return 1;
}
if (tag === "math") {
return 2;
}
}
return ns;
}
};
const transformStyle = (node) => {
if (node.type === 1) {
node.props.forEach((p, i) => {
if (p.type === 6 && p.name === "style" && p.value) {
node.props[i] = {
type: 7,
name: `bind`,
arg: compilerCore.createSimpleExpression(`style`, true, p.loc),
exp: parseInlineCSS(p.value.content, p.loc),
modifiers: [],
loc: p.loc
};
}
});
}
};
const parseInlineCSS = (cssText, loc) => {
const normalized = shared.parseStringStyle(cssText);
return compilerCore.createSimpleExpression(
JSON.stringify(normalized),
false,
loc,
3
);
};
function createDOMCompilerError(code, loc) {
return compilerCore.createCompilerError(
code,
loc,
DOMErrorMessages
);
}
const DOMErrorCodes = {
"X_V_HTML_NO_EXPRESSION": 54,
"54": "X_V_HTML_NO_EXPRESSION",
"X_V_HTML_WITH_CHILDREN": 55,
"55": "X_V_HTML_WITH_CHILDREN",
"X_V_TEXT_NO_EXPRESSION": 56,
"56": "X_V_TEXT_NO_EXPRESSION",
"X_V_TEXT_WITH_CHILDREN": 57,
"57": "X_V_TEXT_WITH_CHILDREN",
"X_V_MODEL_ON_INVALID_ELEMENT": 58,
"58": "X_V_MODEL_ON_INVALID_ELEMENT",
"X_V_MODEL_ARG_ON_ELEMENT": 59,
"59": "X_V_MODEL_ARG_ON_ELEMENT",
"X_V_MODEL_ON_FILE_INPUT_ELEMENT": 60,
"60": "X_V_MODEL_ON_FILE_INPUT_ELEMENT",
"X_V_MODEL_UNNECESSARY_VALUE": 61,
"61": "X_V_MODEL_UNNECESSARY_VALUE",
"X_V_SHOW_NO_EXPRESSION": 62,
"62": "X_V_SHOW_NO_EXPRESSION",
"X_TRANSITION_INVALID_CHILDREN": 63,
"63": "X_TRANSITION_INVALID_CHILDREN",
"X_IGNORED_SIDE_EFFECT_TAG": 64,
"64": "X_IGNORED_SIDE_EFFECT_TAG",
"__EXTEND_POINT__": 65,
"65": "__EXTEND_POINT__"
};
const DOMErrorMessages = {
[54]: `v-html is missing expression.`,
[55]: `v-html will override element children.`,
[56]: `v-text is missing expression.`,
[57]: `v-text will override element children.`,
[58]: `v-model can only be used on <input>, <textarea> and <select> elements.`,
[59]: `v-model argument is not supported on plain elements.`,
[60]: `v-model cannot be used on file inputs since they are read-only. Use a v-on:change listener instead.`,
[61]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`,
[62]: `v-show is missing expression.`,
[63]: `<Transition> expects exactly one child element or component.`,
[64]: `Tags with side effect (<script> and <style>) are ignored in client component templates.`
};
const transformVHtml = (dir, node, context) => {
const { exp, loc } = dir;
if (!exp) {
context.onError(
createDOMCompilerError(54, loc)
);
}
if (node.children.length) {
context.onError(
createDOMCompilerError(55, loc)
);
node.children.length = 0;
}
return {
props: [
compilerCore.createObjectProperty(
compilerCore.createSimpleExpression(`innerHTML`, true, loc),
exp || compilerCore.createSimpleExpression("", true)
)
]
};
};
const transformVText = (dir, node, context) => {
const { exp, loc } = dir;
if (!exp) {
context.onError(
createDOMCompilerError(56, loc)
);
}
if (node.children.length) {
context.onError(
createDOMCompilerError(57, loc)
);
node.children.length = 0;
}
return {
props: [
compilerCore.createObjectProperty(
compilerCore.createSimpleExpression(`textContent`, true),
exp ? compilerCore.getConstantType(exp, context) > 0 ? exp : compilerCore.createCallExpression(
context.helperString(compilerCore.TO_DISPLAY_STRING),
[exp],
loc
) : compilerCore.createSimpleExpression("", true)
)
]
};
};
const transformModel = (dir, node, context) => {
const baseResult = compilerCore.transformModel(dir, node, context);
if (!baseResult.props.length || node.tagType === 1) {
return baseResult;
}
if (dir.arg) {
context.onError(
createDOMCompilerError(
59,
dir.arg.loc
)
);
}
function checkDuplicatedValue() {
const value = compilerCore.findDir(node, "bind");
if (value && compilerCore.isStaticArgOf(value.arg, "value")) {
context.onError(
createDOMCompilerError(
61,
value.loc
)
);
}
}
const { tag } = node;
const isCustomElement = context.isCustomElement(tag);
if (tag === "input" || tag === "textarea" || tag === "select" || isCustomElement) {
let directiveToUse = V_MODEL_TEXT;
let isInvalidType = false;
if (tag === "input" || isCustomElement) {
const type = compilerCore.findProp(node, `type`);
if (type) {
if (type.type === 7) {
directiveToUse = V_MODEL_DYNAMIC;
} else if (type.value) {
switch (type.value.content) {
case "radio":
directiveToUse = V_MODEL_RADIO;
break;
case "checkbox":
directiveToUse = V_MODEL_CHECKBOX;
break;
case "file":
isInvalidType = true;
context.onError(
createDOMCompilerError(
60,
dir.loc
)
);
break;
default:
checkDuplicatedValue();
break;
}
}
} else if (compilerCore.hasDynamicKeyVBind(node)) {
directiveToUse = V_MODEL_DYNAMIC;
} else {
checkDuplicatedValue();
}
} else if (tag === "select") {
directiveToUse = V_MODEL_SELECT;
} else {
checkDuplicatedValue();
}
if (!isInvalidType) {
baseResult.needRuntime = context.helper(directiveToUse);
}
} else {
context.onError(
createDOMCompilerError(
58,
dir.loc
)
);
}
baseResult.props = baseResult.props.filter(
(p) => !(p.key.type === 4 && p.key.content === "modelValue")
);
return baseResult;
};
const isEventOptionModifier = /* @__PURE__ */ shared.makeMap(`passive,once,capture`);
const isNonKeyModifier = /* @__PURE__ */ shared.makeMap(
// event propagation management
`stop,prevent,self,ctrl,shift,alt,meta,exact,middle`
);
const maybeKeyModifier = /* @__PURE__ */ shared.makeMap("left,right");
const isKeyboardEvent = /* @__PURE__ */ shared.makeMap(`onkeyup,onkeydown,onkeypress`);
const resolveModifiers = (key, modifiers, context, loc) => {
const keyModifiers = [];
const nonKeyModifiers = [];
const eventOptionModifiers = [];
for (let i = 0; i < modifiers.length; i++) {
const modifier = modifiers[i].content;
if (modifier === "native" && compilerCore.checkCompatEnabled(
"COMPILER_V_ON_NATIVE",
context,
loc
)) {
eventOptionModifiers.push(modifier);
} else if (isEventOptionModifier(modifier)) {
eventOptionModifiers.push(modifier);
} else {
if (maybeKeyModifier(modifier)) {
if (compilerCore.isStaticExp(key)) {
if (isKeyboardEvent(key.content.toLowerCase())) {
keyModifiers.push(modifier);
} else {
nonKeyModifiers.push(modifier);
}
} else {
keyModifiers.push(modifier);
nonKeyModifiers.push(modifier);
}
} else {
if (isNonKeyModifier(modifier)) {
nonKeyModifiers.push(modifier);
} else {
keyModifiers.push(modifier);
}
}
}
}
return {
keyModifiers,
nonKeyModifiers,
eventOptionModifiers
};
};
const transformClick = (key, event) => {
const isStaticClick = compilerCore.isStaticExp(key) && key.content.toLowerCase() === "onclick";
return isStaticClick ? compilerCore.createSimpleExpression(event, true) : key.type !== 4 ? compilerCore.createCompoundExpression([
`(`,
key,
`) === "onClick" ? "${event}" : (`,
key,
`)`
]) : key;
};
const transformOn = (dir, node, context) => {
return compilerCore.transformOn(dir, node, context, (baseResult) => {
const { modifiers } = dir;
if (!modifiers.length) return baseResult;
let { key, value: handlerExp } = baseResult.props[0];
const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers, context, dir.loc);
if (nonKeyModifiers.includes("right")) {
key = transformClick(key, `onContextmenu`);
}
if (nonKeyModifiers.includes("middle")) {
key = transformClick(key, `onMouseup`);
}
if (nonKeyModifiers.length) {
handlerExp = compilerCore.createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [
handlerExp,
JSON.stringify(nonKeyModifiers)
]);
}
if (keyModifiers.length && // if event name is dynamic, always wrap with keys guard
(!compilerCore.isStaticExp(key) || isKeyboardEvent(key.content.toLowerCase()))) {
handlerExp = compilerCore.createCallExpression(context.helper(V_ON_WITH_KEYS), [
handlerExp,
JSON.stringify(keyModifiers)
]);
}
if (eventOptionModifiers.length) {
const modifierPostfix = eventOptionModifiers.map(shared.capitalize).join("");
key = compilerCore.isStaticExp(key) ? compilerCore.createSimpleExpression(`${key.content}${modifierPostfix}`, true) : compilerCore.createCompoundExpression([`(`, key, `) + "${modifierPostfix}"`]);
}
return {
props: [compilerCore.createObjectProperty(key, handlerExp)]
};
});
};
const transformShow = (dir, node, context) => {
const { exp, loc } = dir;
if (!exp) {
context.onError(
createDOMCompilerError(62, loc)
);
}
return {
props: [],
needRuntime: context.helper(V_SHOW)
};
};
const transformTransition = (node, context) => {
if (node.type === 1 && node.tagType === 1) {
const component = context.isBuiltInComponent(node.tag);
if (component === TRANSITION) {
return () => {
if (!node.children.length) {
return;
}
if (hasMultipleChildren(node)) {
context.onError(
createDOMCompilerError(
63,
{
start: node.children[0].loc.start,
end: node.children[node.children.length - 1].loc.end,
source: ""
}
)
);
}
const child = node.children[0];
if (child.type === 1) {
for (const p of child.props) {
if (p.type === 7 && p.name === "show") {
node.props.push({
type: 6,
name: "persisted",
nameLoc: node.loc,
value: void 0,
loc: node.loc
});
}
}
}
};
}
}
};
function hasMultipleChildren(node) {
const children = node.children = node.children.filter(
(c) => !compilerCore.isCommentOrWhitespace(c)
);
const child = children[0];
return children.length !== 1 || child.type === 11 || child.type === 9 && child.branches.some(hasMultipleChildren);
}
const expReplaceRE = /__VUE_EXP_START__(.*?)__VUE_EXP_END__/g;
const stringifyStatic = (children, context, parent) => {
if (context.scopes.vSlot > 0) {
return;
}
const isParentCached = parent.type === 1 && parent.codegenNode && parent.codegenNode.type === 13 && parent.codegenNode.children && !shared.isArray(parent.codegenNode.children) && parent.codegenNode.children.type === 20;
let nc = 0;
let ec = 0;
const currentChunk = [];
const stringifyCurrentChunk = (currentIndex) => {
if (nc >= 20 || ec >= 5) {
const staticCall = compilerCore.createCallExpression(context.helper(compilerCore.CREATE_STATIC), [
JSON.stringify(
currentChunk.map((node) => stringifyNode(node, context)).join("")
).replace(expReplaceRE, `" + $1 + "`),
// the 2nd argument indicates the number of DOM nodes this static vnode
// will insert / hydrate
String(currentChunk.length)
]);
const deleteCount = currentChunk.length - 1;
if (isParentCached) {
children.splice(
currentIndex - currentChunk.length,
currentChunk.length,
// @ts-expect-error
staticCall
);
} else {
currentChunk[0].codegenNode.value = staticCall;
if (currentChunk.length > 1) {
children.splice(currentIndex - currentChunk.length + 1, deleteCount);
const cacheIndex = context.cached.indexOf(
currentChunk[currentChunk.length - 1].codegenNode
);
if (cacheIndex > -1) {
for (let i2 = cacheIndex; i2 < context.cached.length; i2++) {
const c = context.cached[i2];
if (c) c.index -= deleteCount;
}
context.cached.splice(cacheIndex - deleteCount + 1, deleteCount);
}
}
}
return deleteCount;
}
return 0;
};
let i = 0;
for (; i < children.length; i++) {
const child = children[i];
const isCached = isParentCached || getCachedNode(child);
if (isCached) {
const result = analyzeNode(child);
if (result) {
nc += result[0];
ec += result[1];
currentChunk.push(child);
continue;
}
}
i -= stringifyCurrentChunk(i);
nc = 0;
ec = 0;
currentChunk.length = 0;
}
stringifyCurrentChunk(i);
};
const getCachedNode = (node) => {
if ((node.type === 1 && node.tagType === 0 || node.type === 12) && node.codegenNode && node.codegenNode.type === 20) {
return node.codegenNode;
}
};
const dataAriaRE = /^(?:data|aria)-/;
const isStringifiableAttr = (name, ns) => {
return (ns === 0 ? shared.isKnownHtmlAttr(name) : ns === 1 ? shared.isKnownSvgAttr(name) : ns === 2 ? shared.isKnownMathMLAttr(name) : false) || dataAriaRE.test(name);
};
const isNonStringifiable = /* @__PURE__ */ shared.makeMap(
`caption,thead,tr,th,tbody,td,tfoot,colgroup,col`
);
function analyzeNode(node) {
if (node.type === 1 && isNonStringifiable(node.tag)) {
return false;
}
if (node.type === 1 && compilerCore.findDir(node, "once", true)) {
return false;
}
if (node.type === 12) {
return [1, 0];
}
let nc = 1;
let ec = node.props.length > 0 ? 1 : 0;
let bailed = false;
const bail = () => {
bailed = true;
return false;
};
function walk(node2) {
const isOptionTag = node2.tag === "option" && node2.ns === 0;
for (let i = 0; i < node2.props.length; i++) {
const p = node2.props[i];
if (p.type === 6 && !isStringifiableAttr(p.name, node2.ns)) {
return bail();
}
if (p.type === 7 && p.name === "bind") {
if (p.arg && (p.arg.type === 8 || p.arg.isStatic && !isStringifiableAttr(p.arg.content, node2.ns))) {
return bail();
}
if (p.exp && (p.exp.type === 8 || p.exp.constType < 3)) {
return bail();
}
if (isOptionTag && compilerCore.isStaticArgOf(p.arg, "value") && p.exp && !p.exp.isStatic) {
return bail();
}
}
}
for (let i = 0; i < node2.children.length; i++) {
nc++;
const child = node2.children[i];
if (child.type === 1) {
if (child.props.length > 0) {
ec++;
}
walk(child);
if (bailed) {
return false;
}
}
}
return true;
}
return walk(node) ? [nc, ec] : false;
}
function stringifyNode(node, context) {
if (shared.isString(node)) {
return node;
}
if (shared.isSymbol(node)) {
return ``;
}
switch (node.type) {
case 1:
return stringifyElement(node, context);
case 2:
return shared.escapeHtml(node.content);
case 3:
return `<!--${shared.escapeHtml(node.content)}-->`;
case 5:
return shared.escapeHtml(shared.toDisplayString(evaluateConstant(node.content)));
case 8:
return shared.escapeHtml(evaluateConstant(node));
case 12:
return stringifyNode(node.content, context);
default:
return "";
}
}
function stringifyElement(node, context) {
let res = `<${node.tag}`;
let innerHTML = "";
for (let i = 0; i < node.props.length; i++) {
const p = node.props[i];
if (p.type === 6) {
res += ` ${p.name}`;
if (p.value) {
res += `="${shared.escapeHtml(p.value.content)}"`;
}
} else if (p.type === 7) {
if (p.name === "bind") {
const exp = p.exp;
if (exp.content[0] === "_") {
res += ` ${p.arg.content}="__VUE_EXP_START__${exp.content}__VUE_EXP_END__"`;
continue;
}
if (shared.isBooleanAttr(p.arg.content) && exp.content === "false") {
continue;
}
let evaluated = evaluateConstant(exp);
if (evaluated != null) {
const arg = p.arg && p.arg.content;
if (arg === "class") {
evaluated = shared.normalizeClass(evaluated);
} else if (arg === "style") {
evaluated = shared.stringifyStyle(shared.normalizeStyle(evaluated));
}
res += ` ${p.arg.content}="${shared.escapeHtml(
evaluated
)}"`;
}
} else if (p.name === "html") {
innerHTML = evaluateConstant(p.exp);
} else if (p.name === "text") {
innerHTML = shared.escapeHtml(
shared.toDisplayString(evaluateConstant(p.exp))
);
}
}
}
if (context.scopeId) {
res += ` ${context.scopeId}`;
}
res += `>`;
if (innerHTML) {
res += innerHTML;
} else {
for (let i = 0; i < node.children.length; i++) {
res += stringifyNode(node.children[i], context);
}
}
if (!shared.isVoidTag(node.tag)) {
res += `</${node.tag}>`;
}
return res;
}
function evaluateConstant(exp) {
if (exp.type === 4) {
return new Function(`return (${exp.content})`)();
} else {
let res = ``;
exp.children.forEach((c) => {
if (shared.isString(c) || shared.isSymbol(c)) {
return;
}
if (c.type === 2) {
res += c.content;
} else if (c.type === 5) {
res += shared.toDisplayString(evaluateConstant(c.content));
} else {
res += evaluateConstant(c);
}
});
return res;
}
}
const ignoreSideEffectTags = (node, context) => {
if (node.type === 1 && node.tagType === 0 && (node.tag === "script" || node.tag === "style")) {
context.onError(
createDOMCompilerError(
64,
node.loc
)
);
context.removeNode();
}
};
function isValidHTMLNesting(parent, child) {
if (parent === "template") {
return true;
}
if (parent in onlyValidChildren) {
return onlyValidChildren[parent].has(child);
}
if (child in onlyValidParents) {
return onlyValidParents[child].has(parent);
}
if (parent in knownInvalidChildren) {
if (knownInvalidChildren[parent].has(child)) return false;
}
if (child in knownInvalidParents) {
if (knownInvalidParents[child].has(parent)) return false;
}
return true;
}
const headings = /* @__PURE__ */ new Set(["h1", "h2", "h3", "h4", "h5", "h6"]);
const emptySet = /* @__PURE__ */ new Set([]);
const onlyValidChildren = {
head: /* @__PURE__ */ new Set([
"base",
"basefront",
"bgsound",
"link",
"meta",
"title",
"noscript",
"noframes",
"style",
"script",
"template"
]),
optgroup: /* @__PURE__ */ new Set(["option"]),
select: /* @__PURE__ */ new Set(["optgroup", "option", "hr"]),
// table
table: /* @__PURE__ */ new Set(["caption", "colgroup", "tbody", "tfoot", "thead"]),
tr: /* @__PURE__ */ new Set(["td", "th"]),
colgroup: /* @__PURE__ */ new Set(["col"]),
tbody: /* @__PURE__ */ new Set(["tr"]),
thead: /* @__PURE__ */ new Set(["tr"]),
tfoot: /* @__PURE__ */ new Set(["tr"]),
// these elements can not have any children elements
script: emptySet,
iframe: emptySet,
option: emptySet,
textarea: emptySet,
style: emptySet,
title: emptySet
};
const onlyValidParents = {
// sections
html: emptySet,
body: /* @__PURE__ */ new Set(["html"]),
head: /* @__PURE__ */ new Set(["html"]),
// table
td: /* @__PURE__ */ new Set(["tr"]),
colgroup: /* @__PURE__ */ new Set(["table"]),
caption: /* @__PURE__ */ new Set(["table"]),
tbody: /* @__PURE__ */ new Set(["table"]),
tfoot: /* @__PURE__ */ new Set(["table"]),
col: /* @__PURE__ */ new Set(["colgroup"]),
th: /* @__PURE__ */ new Set(["tr"]),
thead: /* @__PURE__ */ new Set(["table"]),
tr: /* @__PURE__ */ new Set(["tbody", "thead", "tfoot"]),
// data list
dd: /* @__PURE__ */ new Set(["dl", "div"]),
dt: /* @__PURE__ */ new Set(["dl", "div"]),
// other
figcaption: /* @__PURE__ */ new Set(["figure"]),
// li: new Set(["ul", "ol"]),
summary: /* @__PURE__ */ new Set(["details"]),
area: /* @__PURE__ */ new Set(["map"])
};
const knownInvalidChildren = {
p: /* @__PURE__ */ new Set([
"address",
"article",
"aside",
"blockquote",
"center",
"details",
"dialog",
"dir",
"div",
"dl",
"fieldset",
"figure",
"footer",
"form",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"header",
"hgroup",
"hr",
"li",
"main",
"nav",
"menu",
"ol",
"p",
"pre",
"section",
"table",
"ul"
]),
svg: /* @__PURE__ */ new Set([
"b",
"blockquote",
"br",
"code",
"dd",
"div",
"dl",
"dt",
"em",
"embed",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"hr",
"i",
"img",
"li",
"menu",
"meta",
"ol",
"p",
"pre",
"ruby",
"s",
"small",
"span",
"strong",
"sub",
"sup",
"table",
"u",
"ul",
"var"
])
};
const knownInvalidParents = {
a: /* @__PURE__ */ new Set(["a"]),
button: /* @__PURE__ */ new Set(["button"]),
dd: /* @__PURE__ */ new Set(["dd", "dt"]),
dt: /* @__PURE__ */ new Set(["dd", "dt"]),
form: /* @__PURE__ */ new Set(["form"]),
li: /* @__PURE__ */ new Set(["li"]),
h1: headings,
h2: headings,
h3: headings,
h4: headings,
h5: headings,
h6: headings
};
const validateHtmlNesting = (node, context) => {
if (node.type === 1 && node.tagType === 0 && context.parent && context.parent.type === 1 && context.parent.tagType === 0 && !isValidHTMLNesting(context.parent.tag, node.tag)) {
const error = new SyntaxError(
`<${node.tag}> cannot be child of <${context.parent.tag}>, according to HTML specifications. This can cause hydration errors or potentially disrupt future functionality.`
);
error.loc = node.loc;
context.onWarn(error);
}
};
const DOMNodeTransforms = [
transformStyle,
...[transformTransition, validateHtmlNesting]
];
const DOMDirectiveTransforms = {
cloak: compilerCore.noopDirectiveTransform,
html: transformVHtml,
text: transformVText,
model: transformModel,
// override compiler-core
on: transformOn,
// override compiler-core
show: transformShow
};
function compile(src, options = {}) {
return compilerCore.baseCompile(
src,
shared.extend({}, parserOptions, options, {
nodeTransforms: [
// ignore <script> and <tag>
// this is not put inside DOMNodeTransforms because that list is used
// by compiler-ssr to generate vnode fallback branches
ignoreSideEffectTags,
...DOMNodeTransforms,
...options.nodeTransforms || []
],
directiveTransforms: shared.extend(
{},
DOMDirectiveTransforms,
options.directiveTransforms || {}
),
transformHoist: stringifyStatic
})
);
}
function parse(template, options = {}) {
return compilerCore.baseParse(template, shared.extend({}, parserOptions, options));
}
exports.DOMDirectiveTransforms = DOMDirectiveTransforms;
exports.DOMErrorCodes = DOMErrorCodes;
exports.DOMErrorMessages = DOMErrorMessages;
exports.DOMNodeTransforms = DOMNodeTransforms;
exports.TRANSITION = TRANSITION;
exports.TRANSITION_GROUP = TRANSITION_GROUP;
exports.V_MODEL_CHECKBOX = V_MODEL_CHECKBOX;
exports.V_MODEL_DYNAMIC = V_MODEL_DYNAMIC;
exports.V_MODEL_RADIO = V_MODEL_RADIO;
exports.V_MODEL_SELECT = V_MODEL_SELECT;
exports.V_MODEL_TEXT = V_MODEL_TEXT;
exports.V_ON_WITH_KEYS = V_ON_WITH_KEYS;
exports.V_ON_WITH_MODIFIERS = V_ON_WITH_MODIFIERS;
exports.V_SHOW = V_SHOW;
exports.compile = compile;
exports.createDOMCompilerError = createDOMCompilerError;
exports.parse = parse;
exports.parserOptions = parserOptions;
exports.transformStyle = transformStyle;
Object.keys(compilerCore).forEach(function (k) {
if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) exports[k] = compilerCore[k];
});

View File

@@ -0,0 +1,689 @@
/**
* @vue/compiler-dom v3.5.26
* (c) 2018-present Yuxi (Evan) You and Vue contributors
* @license MIT
**/
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var compilerCore = require('@vue/compiler-core');
var shared = require('@vue/shared');
const V_MODEL_RADIO = /* @__PURE__ */ Symbol(``);
const V_MODEL_CHECKBOX = /* @__PURE__ */ Symbol(
``
);
const V_MODEL_TEXT = /* @__PURE__ */ Symbol(``);
const V_MODEL_SELECT = /* @__PURE__ */ Symbol(
``
);
const V_MODEL_DYNAMIC = /* @__PURE__ */ Symbol(
``
);
const V_ON_WITH_MODIFIERS = /* @__PURE__ */ Symbol(
``
);
const V_ON_WITH_KEYS = /* @__PURE__ */ Symbol(
``
);
const V_SHOW = /* @__PURE__ */ Symbol(``);
const TRANSITION = /* @__PURE__ */ Symbol(``);
const TRANSITION_GROUP = /* @__PURE__ */ Symbol(
``
);
compilerCore.registerRuntimeHelpers({
[V_MODEL_RADIO]: `vModelRadio`,
[V_MODEL_CHECKBOX]: `vModelCheckbox`,
[V_MODEL_TEXT]: `vModelText`,
[V_MODEL_SELECT]: `vModelSelect`,
[V_MODEL_DYNAMIC]: `vModelDynamic`,
[V_ON_WITH_MODIFIERS]: `withModifiers`,
[V_ON_WITH_KEYS]: `withKeys`,
[V_SHOW]: `vShow`,
[TRANSITION]: `Transition`,
[TRANSITION_GROUP]: `TransitionGroup`
});
const parserOptions = {
parseMode: "html",
isVoidTag: shared.isVoidTag,
isNativeTag: (tag) => shared.isHTMLTag(tag) || shared.isSVGTag(tag) || shared.isMathMLTag(tag),
isPreTag: (tag) => tag === "pre",
isIgnoreNewlineTag: (tag) => tag === "pre" || tag === "textarea",
decodeEntities: void 0,
isBuiltInComponent: (tag) => {
if (tag === "Transition" || tag === "transition") {
return TRANSITION;
} else if (tag === "TransitionGroup" || tag === "transition-group") {
return TRANSITION_GROUP;
}
},
// https://html.spec.whatwg.org/multipage/parsing.html#tree-construction-dispatcher
getNamespace(tag, parent, rootNamespace) {
let ns = parent ? parent.ns : rootNamespace;
if (parent && ns === 2) {
if (parent.tag === "annotation-xml") {
if (tag === "svg") {
return 1;
}
if (parent.props.some(
(a) => a.type === 6 && a.name === "encoding" && a.value != null && (a.value.content === "text/html" || a.value.content === "application/xhtml+xml")
)) {
ns = 0;
}
} else if (/^m(?:[ions]|text)$/.test(parent.tag) && tag !== "mglyph" && tag !== "malignmark") {
ns = 0;
}
} else if (parent && ns === 1) {
if (parent.tag === "foreignObject" || parent.tag === "desc" || parent.tag === "title") {
ns = 0;
}
}
if (ns === 0) {
if (tag === "svg") {
return 1;
}
if (tag === "math") {
return 2;
}
}
return ns;
}
};
const transformStyle = (node) => {
if (node.type === 1) {
node.props.forEach((p, i) => {
if (p.type === 6 && p.name === "style" && p.value) {
node.props[i] = {
type: 7,
name: `bind`,
arg: compilerCore.createSimpleExpression(`style`, true, p.loc),
exp: parseInlineCSS(p.value.content, p.loc),
modifiers: [],
loc: p.loc
};
}
});
}
};
const parseInlineCSS = (cssText, loc) => {
const normalized = shared.parseStringStyle(cssText);
return compilerCore.createSimpleExpression(
JSON.stringify(normalized),
false,
loc,
3
);
};
function createDOMCompilerError(code, loc) {
return compilerCore.createCompilerError(
code,
loc,
DOMErrorMessages
);
}
const DOMErrorCodes = {
"X_V_HTML_NO_EXPRESSION": 54,
"54": "X_V_HTML_NO_EXPRESSION",
"X_V_HTML_WITH_CHILDREN": 55,
"55": "X_V_HTML_WITH_CHILDREN",
"X_V_TEXT_NO_EXPRESSION": 56,
"56": "X_V_TEXT_NO_EXPRESSION",
"X_V_TEXT_WITH_CHILDREN": 57,
"57": "X_V_TEXT_WITH_CHILDREN",
"X_V_MODEL_ON_INVALID_ELEMENT": 58,
"58": "X_V_MODEL_ON_INVALID_ELEMENT",
"X_V_MODEL_ARG_ON_ELEMENT": 59,
"59": "X_V_MODEL_ARG_ON_ELEMENT",
"X_V_MODEL_ON_FILE_INPUT_ELEMENT": 60,
"60": "X_V_MODEL_ON_FILE_INPUT_ELEMENT",
"X_V_MODEL_UNNECESSARY_VALUE": 61,
"61": "X_V_MODEL_UNNECESSARY_VALUE",
"X_V_SHOW_NO_EXPRESSION": 62,
"62": "X_V_SHOW_NO_EXPRESSION",
"X_TRANSITION_INVALID_CHILDREN": 63,
"63": "X_TRANSITION_INVALID_CHILDREN",
"X_IGNORED_SIDE_EFFECT_TAG": 64,
"64": "X_IGNORED_SIDE_EFFECT_TAG",
"__EXTEND_POINT__": 65,
"65": "__EXTEND_POINT__"
};
const DOMErrorMessages = {
[54]: `v-html is missing expression.`,
[55]: `v-html will override element children.`,
[56]: `v-text is missing expression.`,
[57]: `v-text will override element children.`,
[58]: `v-model can only be used on <input>, <textarea> and <select> elements.`,
[59]: `v-model argument is not supported on plain elements.`,
[60]: `v-model cannot be used on file inputs since they are read-only. Use a v-on:change listener instead.`,
[61]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`,
[62]: `v-show is missing expression.`,
[63]: `<Transition> expects exactly one child element or component.`,
[64]: `Tags with side effect (<script> and <style>) are ignored in client component templates.`
};
const transformVHtml = (dir, node, context) => {
const { exp, loc } = dir;
if (!exp) {
context.onError(
createDOMCompilerError(54, loc)
);
}
if (node.children.length) {
context.onError(
createDOMCompilerError(55, loc)
);
node.children.length = 0;
}
return {
props: [
compilerCore.createObjectProperty(
compilerCore.createSimpleExpression(`innerHTML`, true, loc),
exp || compilerCore.createSimpleExpression("", true)
)
]
};
};
const transformVText = (dir, node, context) => {
const { exp, loc } = dir;
if (!exp) {
context.onError(
createDOMCompilerError(56, loc)
);
}
if (node.children.length) {
context.onError(
createDOMCompilerError(57, loc)
);
node.children.length = 0;
}
return {
props: [
compilerCore.createObjectProperty(
compilerCore.createSimpleExpression(`textContent`, true),
exp ? compilerCore.getConstantType(exp, context) > 0 ? exp : compilerCore.createCallExpression(
context.helperString(compilerCore.TO_DISPLAY_STRING),
[exp],
loc
) : compilerCore.createSimpleExpression("", true)
)
]
};
};
const transformModel = (dir, node, context) => {
const baseResult = compilerCore.transformModel(dir, node, context);
if (!baseResult.props.length || node.tagType === 1) {
return baseResult;
}
if (dir.arg) {
context.onError(
createDOMCompilerError(
59,
dir.arg.loc
)
);
}
const { tag } = node;
const isCustomElement = context.isCustomElement(tag);
if (tag === "input" || tag === "textarea" || tag === "select" || isCustomElement) {
let directiveToUse = V_MODEL_TEXT;
let isInvalidType = false;
if (tag === "input" || isCustomElement) {
const type = compilerCore.findProp(node, `type`);
if (type) {
if (type.type === 7) {
directiveToUse = V_MODEL_DYNAMIC;
} else if (type.value) {
switch (type.value.content) {
case "radio":
directiveToUse = V_MODEL_RADIO;
break;
case "checkbox":
directiveToUse = V_MODEL_CHECKBOX;
break;
case "file":
isInvalidType = true;
context.onError(
createDOMCompilerError(
60,
dir.loc
)
);
break;
}
}
} else if (compilerCore.hasDynamicKeyVBind(node)) {
directiveToUse = V_MODEL_DYNAMIC;
} else ;
} else if (tag === "select") {
directiveToUse = V_MODEL_SELECT;
} else ;
if (!isInvalidType) {
baseResult.needRuntime = context.helper(directiveToUse);
}
} else {
context.onError(
createDOMCompilerError(
58,
dir.loc
)
);
}
baseResult.props = baseResult.props.filter(
(p) => !(p.key.type === 4 && p.key.content === "modelValue")
);
return baseResult;
};
const isEventOptionModifier = /* @__PURE__ */ shared.makeMap(`passive,once,capture`);
const isNonKeyModifier = /* @__PURE__ */ shared.makeMap(
// event propagation management
`stop,prevent,self,ctrl,shift,alt,meta,exact,middle`
);
const maybeKeyModifier = /* @__PURE__ */ shared.makeMap("left,right");
const isKeyboardEvent = /* @__PURE__ */ shared.makeMap(`onkeyup,onkeydown,onkeypress`);
const resolveModifiers = (key, modifiers, context, loc) => {
const keyModifiers = [];
const nonKeyModifiers = [];
const eventOptionModifiers = [];
for (let i = 0; i < modifiers.length; i++) {
const modifier = modifiers[i].content;
if (modifier === "native" && compilerCore.checkCompatEnabled(
"COMPILER_V_ON_NATIVE",
context,
loc
)) {
eventOptionModifiers.push(modifier);
} else if (isEventOptionModifier(modifier)) {
eventOptionModifiers.push(modifier);
} else {
if (maybeKeyModifier(modifier)) {
if (compilerCore.isStaticExp(key)) {
if (isKeyboardEvent(key.content.toLowerCase())) {
keyModifiers.push(modifier);
} else {
nonKeyModifiers.push(modifier);
}
} else {
keyModifiers.push(modifier);
nonKeyModifiers.push(modifier);
}
} else {
if (isNonKeyModifier(modifier)) {
nonKeyModifiers.push(modifier);
} else {
keyModifiers.push(modifier);
}
}
}
}
return {
keyModifiers,
nonKeyModifiers,
eventOptionModifiers
};
};
const transformClick = (key, event) => {
const isStaticClick = compilerCore.isStaticExp(key) && key.content.toLowerCase() === "onclick";
return isStaticClick ? compilerCore.createSimpleExpression(event, true) : key.type !== 4 ? compilerCore.createCompoundExpression([
`(`,
key,
`) === "onClick" ? "${event}" : (`,
key,
`)`
]) : key;
};
const transformOn = (dir, node, context) => {
return compilerCore.transformOn(dir, node, context, (baseResult) => {
const { modifiers } = dir;
if (!modifiers.length) return baseResult;
let { key, value: handlerExp } = baseResult.props[0];
const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers, context, dir.loc);
if (nonKeyModifiers.includes("right")) {
key = transformClick(key, `onContextmenu`);
}
if (nonKeyModifiers.includes("middle")) {
key = transformClick(key, `onMouseup`);
}
if (nonKeyModifiers.length) {
handlerExp = compilerCore.createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [
handlerExp,
JSON.stringify(nonKeyModifiers)
]);
}
if (keyModifiers.length && // if event name is dynamic, always wrap with keys guard
(!compilerCore.isStaticExp(key) || isKeyboardEvent(key.content.toLowerCase()))) {
handlerExp = compilerCore.createCallExpression(context.helper(V_ON_WITH_KEYS), [
handlerExp,
JSON.stringify(keyModifiers)
]);
}
if (eventOptionModifiers.length) {
const modifierPostfix = eventOptionModifiers.map(shared.capitalize).join("");
key = compilerCore.isStaticExp(key) ? compilerCore.createSimpleExpression(`${key.content}${modifierPostfix}`, true) : compilerCore.createCompoundExpression([`(`, key, `) + "${modifierPostfix}"`]);
}
return {
props: [compilerCore.createObjectProperty(key, handlerExp)]
};
});
};
const transformShow = (dir, node, context) => {
const { exp, loc } = dir;
if (!exp) {
context.onError(
createDOMCompilerError(62, loc)
);
}
return {
props: [],
needRuntime: context.helper(V_SHOW)
};
};
const expReplaceRE = /__VUE_EXP_START__(.*?)__VUE_EXP_END__/g;
const stringifyStatic = (children, context, parent) => {
if (context.scopes.vSlot > 0) {
return;
}
const isParentCached = parent.type === 1 && parent.codegenNode && parent.codegenNode.type === 13 && parent.codegenNode.children && !shared.isArray(parent.codegenNode.children) && parent.codegenNode.children.type === 20;
let nc = 0;
let ec = 0;
const currentChunk = [];
const stringifyCurrentChunk = (currentIndex) => {
if (nc >= 20 || ec >= 5) {
const staticCall = compilerCore.createCallExpression(context.helper(compilerCore.CREATE_STATIC), [
JSON.stringify(
currentChunk.map((node) => stringifyNode(node, context)).join("")
).replace(expReplaceRE, `" + $1 + "`),
// the 2nd argument indicates the number of DOM nodes this static vnode
// will insert / hydrate
String(currentChunk.length)
]);
const deleteCount = currentChunk.length - 1;
if (isParentCached) {
children.splice(
currentIndex - currentChunk.length,
currentChunk.length,
// @ts-expect-error
staticCall
);
} else {
currentChunk[0].codegenNode.value = staticCall;
if (currentChunk.length > 1) {
children.splice(currentIndex - currentChunk.length + 1, deleteCount);
const cacheIndex = context.cached.indexOf(
currentChunk[currentChunk.length - 1].codegenNode
);
if (cacheIndex > -1) {
for (let i2 = cacheIndex; i2 < context.cached.length; i2++) {
const c = context.cached[i2];
if (c) c.index -= deleteCount;
}
context.cached.splice(cacheIndex - deleteCount + 1, deleteCount);
}
}
}
return deleteCount;
}
return 0;
};
let i = 0;
for (; i < children.length; i++) {
const child = children[i];
const isCached = isParentCached || getCachedNode(child);
if (isCached) {
const result = analyzeNode(child);
if (result) {
nc += result[0];
ec += result[1];
currentChunk.push(child);
continue;
}
}
i -= stringifyCurrentChunk(i);
nc = 0;
ec = 0;
currentChunk.length = 0;
}
stringifyCurrentChunk(i);
};
const getCachedNode = (node) => {
if ((node.type === 1 && node.tagType === 0 || node.type === 12) && node.codegenNode && node.codegenNode.type === 20) {
return node.codegenNode;
}
};
const dataAriaRE = /^(?:data|aria)-/;
const isStringifiableAttr = (name, ns) => {
return (ns === 0 ? shared.isKnownHtmlAttr(name) : ns === 1 ? shared.isKnownSvgAttr(name) : ns === 2 ? shared.isKnownMathMLAttr(name) : false) || dataAriaRE.test(name);
};
const isNonStringifiable = /* @__PURE__ */ shared.makeMap(
`caption,thead,tr,th,tbody,td,tfoot,colgroup,col`
);
function analyzeNode(node) {
if (node.type === 1 && isNonStringifiable(node.tag)) {
return false;
}
if (node.type === 1 && compilerCore.findDir(node, "once", true)) {
return false;
}
if (node.type === 12) {
return [1, 0];
}
let nc = 1;
let ec = node.props.length > 0 ? 1 : 0;
let bailed = false;
const bail = () => {
bailed = true;
return false;
};
function walk(node2) {
const isOptionTag = node2.tag === "option" && node2.ns === 0;
for (let i = 0; i < node2.props.length; i++) {
const p = node2.props[i];
if (p.type === 6 && !isStringifiableAttr(p.name, node2.ns)) {
return bail();
}
if (p.type === 7 && p.name === "bind") {
if (p.arg && (p.arg.type === 8 || p.arg.isStatic && !isStringifiableAttr(p.arg.content, node2.ns))) {
return bail();
}
if (p.exp && (p.exp.type === 8 || p.exp.constType < 3)) {
return bail();
}
if (isOptionTag && compilerCore.isStaticArgOf(p.arg, "value") && p.exp && !p.exp.isStatic) {
return bail();
}
}
}
for (let i = 0; i < node2.children.length; i++) {
nc++;
const child = node2.children[i];
if (child.type === 1) {
if (child.props.length > 0) {
ec++;
}
walk(child);
if (bailed) {
return false;
}
}
}
return true;
}
return walk(node) ? [nc, ec] : false;
}
function stringifyNode(node, context) {
if (shared.isString(node)) {
return node;
}
if (shared.isSymbol(node)) {
return ``;
}
switch (node.type) {
case 1:
return stringifyElement(node, context);
case 2:
return shared.escapeHtml(node.content);
case 3:
return `<!--${shared.escapeHtml(node.content)}-->`;
case 5:
return shared.escapeHtml(shared.toDisplayString(evaluateConstant(node.content)));
case 8:
return shared.escapeHtml(evaluateConstant(node));
case 12:
return stringifyNode(node.content, context);
default:
return "";
}
}
function stringifyElement(node, context) {
let res = `<${node.tag}`;
let innerHTML = "";
for (let i = 0; i < node.props.length; i++) {
const p = node.props[i];
if (p.type === 6) {
res += ` ${p.name}`;
if (p.value) {
res += `="${shared.escapeHtml(p.value.content)}"`;
}
} else if (p.type === 7) {
if (p.name === "bind") {
const exp = p.exp;
if (exp.content[0] === "_") {
res += ` ${p.arg.content}="__VUE_EXP_START__${exp.content}__VUE_EXP_END__"`;
continue;
}
if (shared.isBooleanAttr(p.arg.content) && exp.content === "false") {
continue;
}
let evaluated = evaluateConstant(exp);
if (evaluated != null) {
const arg = p.arg && p.arg.content;
if (arg === "class") {
evaluated = shared.normalizeClass(evaluated);
} else if (arg === "style") {
evaluated = shared.stringifyStyle(shared.normalizeStyle(evaluated));
}
res += ` ${p.arg.content}="${shared.escapeHtml(
evaluated
)}"`;
}
} else if (p.name === "html") {
innerHTML = evaluateConstant(p.exp);
} else if (p.name === "text") {
innerHTML = shared.escapeHtml(
shared.toDisplayString(evaluateConstant(p.exp))
);
}
}
}
if (context.scopeId) {
res += ` ${context.scopeId}`;
}
res += `>`;
if (innerHTML) {
res += innerHTML;
} else {
for (let i = 0; i < node.children.length; i++) {
res += stringifyNode(node.children[i], context);
}
}
if (!shared.isVoidTag(node.tag)) {
res += `</${node.tag}>`;
}
return res;
}
function evaluateConstant(exp) {
if (exp.type === 4) {
return new Function(`return (${exp.content})`)();
} else {
let res = ``;
exp.children.forEach((c) => {
if (shared.isString(c) || shared.isSymbol(c)) {
return;
}
if (c.type === 2) {
res += c.content;
} else if (c.type === 5) {
res += shared.toDisplayString(evaluateConstant(c.content));
} else {
res += evaluateConstant(c);
}
});
return res;
}
}
const ignoreSideEffectTags = (node, context) => {
if (node.type === 1 && node.tagType === 0 && (node.tag === "script" || node.tag === "style")) {
context.removeNode();
}
};
const DOMNodeTransforms = [
transformStyle,
...[]
];
const DOMDirectiveTransforms = {
cloak: compilerCore.noopDirectiveTransform,
html: transformVHtml,
text: transformVText,
model: transformModel,
// override compiler-core
on: transformOn,
// override compiler-core
show: transformShow
};
function compile(src, options = {}) {
return compilerCore.baseCompile(
src,
shared.extend({}, parserOptions, options, {
nodeTransforms: [
// ignore <script> and <tag>
// this is not put inside DOMNodeTransforms because that list is used
// by compiler-ssr to generate vnode fallback branches
ignoreSideEffectTags,
...DOMNodeTransforms,
...options.nodeTransforms || []
],
directiveTransforms: shared.extend(
{},
DOMDirectiveTransforms,
options.directiveTransforms || {}
),
transformHoist: stringifyStatic
})
);
}
function parse(template, options = {}) {
return compilerCore.baseParse(template, shared.extend({}, parserOptions, options));
}
exports.DOMDirectiveTransforms = DOMDirectiveTransforms;
exports.DOMErrorCodes = DOMErrorCodes;
exports.DOMErrorMessages = DOMErrorMessages;
exports.DOMNodeTransforms = DOMNodeTransforms;
exports.TRANSITION = TRANSITION;
exports.TRANSITION_GROUP = TRANSITION_GROUP;
exports.V_MODEL_CHECKBOX = V_MODEL_CHECKBOX;
exports.V_MODEL_DYNAMIC = V_MODEL_DYNAMIC;
exports.V_MODEL_RADIO = V_MODEL_RADIO;
exports.V_MODEL_SELECT = V_MODEL_SELECT;
exports.V_MODEL_TEXT = V_MODEL_TEXT;
exports.V_ON_WITH_KEYS = V_ON_WITH_KEYS;
exports.V_ON_WITH_MODIFIERS = V_ON_WITH_MODIFIERS;
exports.V_SHOW = V_SHOW;
exports.compile = compile;
exports.createDOMCompilerError = createDOMCompilerError;
exports.parse = parse;
exports.parserOptions = parserOptions;
exports.transformStyle = transformStyle;
Object.keys(compilerCore).forEach(function (k) {
if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) exports[k] = compilerCore[k];
});

45
node_modules/@vue/compiler-dom/dist/compiler-dom.d.ts generated vendored Normal file
View File

@@ -0,0 +1,45 @@
import { ParserOptions, NodeTransform, SourceLocation, CompilerError, DirectiveTransform, RootNode, CompilerOptions, CodegenResult } from '@vue/compiler-core';
export * from '@vue/compiler-core';
export declare const parserOptions: ParserOptions;
export declare const V_MODEL_RADIO: unique symbol;
export declare const V_MODEL_CHECKBOX: unique symbol;
export declare const V_MODEL_TEXT: unique symbol;
export declare const V_MODEL_SELECT: unique symbol;
export declare const V_MODEL_DYNAMIC: unique symbol;
export declare const V_ON_WITH_MODIFIERS: unique symbol;
export declare const V_ON_WITH_KEYS: unique symbol;
export declare const V_SHOW: unique symbol;
export declare const TRANSITION: unique symbol;
export declare const TRANSITION_GROUP: unique symbol;
export declare const transformStyle: NodeTransform;
interface DOMCompilerError extends CompilerError {
code: DOMErrorCodes;
}
export declare function createDOMCompilerError(code: DOMErrorCodes, loc?: SourceLocation): DOMCompilerError;
export declare enum DOMErrorCodes {
X_V_HTML_NO_EXPRESSION = 54,
X_V_HTML_WITH_CHILDREN = 55,
X_V_TEXT_NO_EXPRESSION = 56,
X_V_TEXT_WITH_CHILDREN = 57,
X_V_MODEL_ON_INVALID_ELEMENT = 58,
X_V_MODEL_ARG_ON_ELEMENT = 59,
X_V_MODEL_ON_FILE_INPUT_ELEMENT = 60,
X_V_MODEL_UNNECESSARY_VALUE = 61,
X_V_SHOW_NO_EXPRESSION = 62,
X_TRANSITION_INVALID_CHILDREN = 63,
X_IGNORED_SIDE_EFFECT_TAG = 64,
__EXTEND_POINT__ = 65
}
export declare const DOMErrorMessages: {
[code: number]: string;
};
export declare const DOMNodeTransforms: NodeTransform[];
export declare const DOMDirectiveTransforms: Record<string, DirectiveTransform>;
export declare function compile(src: string | RootNode, options?: CompilerOptions): CodegenResult;
export declare function parse(template: string, options?: ParserOptions): RootNode;

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,690 @@
/**
* @vue/compiler-dom v3.5.26
* (c) 2018-present Yuxi (Evan) You and Vue contributors
* @license MIT
**/
import { registerRuntimeHelpers, createSimpleExpression, createCompilerError, createObjectProperty, createCallExpression, getConstantType, TO_DISPLAY_STRING, transformModel as transformModel$1, findProp, hasDynamicKeyVBind, findDir, isStaticArgOf, transformOn as transformOn$1, isStaticExp, createCompoundExpression, checkCompatEnabled, isCommentOrWhitespace, noopDirectiveTransform, baseCompile, baseParse } from '@vue/compiler-core';
export * from '@vue/compiler-core';
import { isHTMLTag, isSVGTag, isMathMLTag, isVoidTag, parseStringStyle, makeMap, capitalize, extend } from '@vue/shared';
const V_MODEL_RADIO = /* @__PURE__ */ Symbol(!!(process.env.NODE_ENV !== "production") ? `vModelRadio` : ``);
const V_MODEL_CHECKBOX = /* @__PURE__ */ Symbol(
!!(process.env.NODE_ENV !== "production") ? `vModelCheckbox` : ``
);
const V_MODEL_TEXT = /* @__PURE__ */ Symbol(!!(process.env.NODE_ENV !== "production") ? `vModelText` : ``);
const V_MODEL_SELECT = /* @__PURE__ */ Symbol(
!!(process.env.NODE_ENV !== "production") ? `vModelSelect` : ``
);
const V_MODEL_DYNAMIC = /* @__PURE__ */ Symbol(
!!(process.env.NODE_ENV !== "production") ? `vModelDynamic` : ``
);
const V_ON_WITH_MODIFIERS = /* @__PURE__ */ Symbol(
!!(process.env.NODE_ENV !== "production") ? `vOnModifiersGuard` : ``
);
const V_ON_WITH_KEYS = /* @__PURE__ */ Symbol(
!!(process.env.NODE_ENV !== "production") ? `vOnKeysGuard` : ``
);
const V_SHOW = /* @__PURE__ */ Symbol(!!(process.env.NODE_ENV !== "production") ? `vShow` : ``);
const TRANSITION = /* @__PURE__ */ Symbol(!!(process.env.NODE_ENV !== "production") ? `Transition` : ``);
const TRANSITION_GROUP = /* @__PURE__ */ Symbol(
!!(process.env.NODE_ENV !== "production") ? `TransitionGroup` : ``
);
registerRuntimeHelpers({
[V_MODEL_RADIO]: `vModelRadio`,
[V_MODEL_CHECKBOX]: `vModelCheckbox`,
[V_MODEL_TEXT]: `vModelText`,
[V_MODEL_SELECT]: `vModelSelect`,
[V_MODEL_DYNAMIC]: `vModelDynamic`,
[V_ON_WITH_MODIFIERS]: `withModifiers`,
[V_ON_WITH_KEYS]: `withKeys`,
[V_SHOW]: `vShow`,
[TRANSITION]: `Transition`,
[TRANSITION_GROUP]: `TransitionGroup`
});
let decoder;
function decodeHtmlBrowser(raw, asAttr = false) {
if (!decoder) {
decoder = document.createElement("div");
}
if (asAttr) {
decoder.innerHTML = `<div foo="${raw.replace(/"/g, "&quot;")}">`;
return decoder.children[0].getAttribute("foo");
} else {
decoder.innerHTML = raw;
return decoder.textContent;
}
}
const parserOptions = {
parseMode: "html",
isVoidTag,
isNativeTag: (tag) => isHTMLTag(tag) || isSVGTag(tag) || isMathMLTag(tag),
isPreTag: (tag) => tag === "pre",
isIgnoreNewlineTag: (tag) => tag === "pre" || tag === "textarea",
decodeEntities: decodeHtmlBrowser ,
isBuiltInComponent: (tag) => {
if (tag === "Transition" || tag === "transition") {
return TRANSITION;
} else if (tag === "TransitionGroup" || tag === "transition-group") {
return TRANSITION_GROUP;
}
},
// https://html.spec.whatwg.org/multipage/parsing.html#tree-construction-dispatcher
getNamespace(tag, parent, rootNamespace) {
let ns = parent ? parent.ns : rootNamespace;
if (parent && ns === 2) {
if (parent.tag === "annotation-xml") {
if (tag === "svg") {
return 1;
}
if (parent.props.some(
(a) => a.type === 6 && a.name === "encoding" && a.value != null && (a.value.content === "text/html" || a.value.content === "application/xhtml+xml")
)) {
ns = 0;
}
} else if (/^m(?:[ions]|text)$/.test(parent.tag) && tag !== "mglyph" && tag !== "malignmark") {
ns = 0;
}
} else if (parent && ns === 1) {
if (parent.tag === "foreignObject" || parent.tag === "desc" || parent.tag === "title") {
ns = 0;
}
}
if (ns === 0) {
if (tag === "svg") {
return 1;
}
if (tag === "math") {
return 2;
}
}
return ns;
}
};
const transformStyle = (node) => {
if (node.type === 1) {
node.props.forEach((p, i) => {
if (p.type === 6 && p.name === "style" && p.value) {
node.props[i] = {
type: 7,
name: `bind`,
arg: createSimpleExpression(`style`, true, p.loc),
exp: parseInlineCSS(p.value.content, p.loc),
modifiers: [],
loc: p.loc
};
}
});
}
};
const parseInlineCSS = (cssText, loc) => {
const normalized = parseStringStyle(cssText);
return createSimpleExpression(
JSON.stringify(normalized),
false,
loc,
3
);
};
function createDOMCompilerError(code, loc) {
return createCompilerError(
code,
loc,
!!(process.env.NODE_ENV !== "production") || false ? DOMErrorMessages : void 0
);
}
const DOMErrorCodes = {
"X_V_HTML_NO_EXPRESSION": 54,
"54": "X_V_HTML_NO_EXPRESSION",
"X_V_HTML_WITH_CHILDREN": 55,
"55": "X_V_HTML_WITH_CHILDREN",
"X_V_TEXT_NO_EXPRESSION": 56,
"56": "X_V_TEXT_NO_EXPRESSION",
"X_V_TEXT_WITH_CHILDREN": 57,
"57": "X_V_TEXT_WITH_CHILDREN",
"X_V_MODEL_ON_INVALID_ELEMENT": 58,
"58": "X_V_MODEL_ON_INVALID_ELEMENT",
"X_V_MODEL_ARG_ON_ELEMENT": 59,
"59": "X_V_MODEL_ARG_ON_ELEMENT",
"X_V_MODEL_ON_FILE_INPUT_ELEMENT": 60,
"60": "X_V_MODEL_ON_FILE_INPUT_ELEMENT",
"X_V_MODEL_UNNECESSARY_VALUE": 61,
"61": "X_V_MODEL_UNNECESSARY_VALUE",
"X_V_SHOW_NO_EXPRESSION": 62,
"62": "X_V_SHOW_NO_EXPRESSION",
"X_TRANSITION_INVALID_CHILDREN": 63,
"63": "X_TRANSITION_INVALID_CHILDREN",
"X_IGNORED_SIDE_EFFECT_TAG": 64,
"64": "X_IGNORED_SIDE_EFFECT_TAG",
"__EXTEND_POINT__": 65,
"65": "__EXTEND_POINT__"
};
const DOMErrorMessages = {
[54]: `v-html is missing expression.`,
[55]: `v-html will override element children.`,
[56]: `v-text is missing expression.`,
[57]: `v-text will override element children.`,
[58]: `v-model can only be used on <input>, <textarea> and <select> elements.`,
[59]: `v-model argument is not supported on plain elements.`,
[60]: `v-model cannot be used on file inputs since they are read-only. Use a v-on:change listener instead.`,
[61]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`,
[62]: `v-show is missing expression.`,
[63]: `<Transition> expects exactly one child element or component.`,
[64]: `Tags with side effect (<script> and <style>) are ignored in client component templates.`
};
const transformVHtml = (dir, node, context) => {
const { exp, loc } = dir;
if (!exp) {
context.onError(
createDOMCompilerError(54, loc)
);
}
if (node.children.length) {
context.onError(
createDOMCompilerError(55, loc)
);
node.children.length = 0;
}
return {
props: [
createObjectProperty(
createSimpleExpression(`innerHTML`, true, loc),
exp || createSimpleExpression("", true)
)
]
};
};
const transformVText = (dir, node, context) => {
const { exp, loc } = dir;
if (!exp) {
context.onError(
createDOMCompilerError(56, loc)
);
}
if (node.children.length) {
context.onError(
createDOMCompilerError(57, loc)
);
node.children.length = 0;
}
return {
props: [
createObjectProperty(
createSimpleExpression(`textContent`, true),
exp ? getConstantType(exp, context) > 0 ? exp : createCallExpression(
context.helperString(TO_DISPLAY_STRING),
[exp],
loc
) : createSimpleExpression("", true)
)
]
};
};
const transformModel = (dir, node, context) => {
const baseResult = transformModel$1(dir, node, context);
if (!baseResult.props.length || node.tagType === 1) {
return baseResult;
}
if (dir.arg) {
context.onError(
createDOMCompilerError(
59,
dir.arg.loc
)
);
}
function checkDuplicatedValue() {
const value = findDir(node, "bind");
if (value && isStaticArgOf(value.arg, "value")) {
context.onError(
createDOMCompilerError(
61,
value.loc
)
);
}
}
const { tag } = node;
const isCustomElement = context.isCustomElement(tag);
if (tag === "input" || tag === "textarea" || tag === "select" || isCustomElement) {
let directiveToUse = V_MODEL_TEXT;
let isInvalidType = false;
if (tag === "input" || isCustomElement) {
const type = findProp(node, `type`);
if (type) {
if (type.type === 7) {
directiveToUse = V_MODEL_DYNAMIC;
} else if (type.value) {
switch (type.value.content) {
case "radio":
directiveToUse = V_MODEL_RADIO;
break;
case "checkbox":
directiveToUse = V_MODEL_CHECKBOX;
break;
case "file":
isInvalidType = true;
context.onError(
createDOMCompilerError(
60,
dir.loc
)
);
break;
default:
!!(process.env.NODE_ENV !== "production") && checkDuplicatedValue();
break;
}
}
} else if (hasDynamicKeyVBind(node)) {
directiveToUse = V_MODEL_DYNAMIC;
} else {
!!(process.env.NODE_ENV !== "production") && checkDuplicatedValue();
}
} else if (tag === "select") {
directiveToUse = V_MODEL_SELECT;
} else {
!!(process.env.NODE_ENV !== "production") && checkDuplicatedValue();
}
if (!isInvalidType) {
baseResult.needRuntime = context.helper(directiveToUse);
}
} else {
context.onError(
createDOMCompilerError(
58,
dir.loc
)
);
}
baseResult.props = baseResult.props.filter(
(p) => !(p.key.type === 4 && p.key.content === "modelValue")
);
return baseResult;
};
const isEventOptionModifier = /* @__PURE__ */ makeMap(`passive,once,capture`);
const isNonKeyModifier = /* @__PURE__ */ makeMap(
// event propagation management
`stop,prevent,self,ctrl,shift,alt,meta,exact,middle`
);
const maybeKeyModifier = /* @__PURE__ */ makeMap("left,right");
const isKeyboardEvent = /* @__PURE__ */ makeMap(`onkeyup,onkeydown,onkeypress`);
const resolveModifiers = (key, modifiers, context, loc) => {
const keyModifiers = [];
const nonKeyModifiers = [];
const eventOptionModifiers = [];
for (let i = 0; i < modifiers.length; i++) {
const modifier = modifiers[i].content;
if (modifier === "native" && checkCompatEnabled(
"COMPILER_V_ON_NATIVE",
context,
loc
)) {
eventOptionModifiers.push(modifier);
} else if (isEventOptionModifier(modifier)) {
eventOptionModifiers.push(modifier);
} else {
if (maybeKeyModifier(modifier)) {
if (isStaticExp(key)) {
if (isKeyboardEvent(key.content.toLowerCase())) {
keyModifiers.push(modifier);
} else {
nonKeyModifiers.push(modifier);
}
} else {
keyModifiers.push(modifier);
nonKeyModifiers.push(modifier);
}
} else {
if (isNonKeyModifier(modifier)) {
nonKeyModifiers.push(modifier);
} else {
keyModifiers.push(modifier);
}
}
}
}
return {
keyModifiers,
nonKeyModifiers,
eventOptionModifiers
};
};
const transformClick = (key, event) => {
const isStaticClick = isStaticExp(key) && key.content.toLowerCase() === "onclick";
return isStaticClick ? createSimpleExpression(event, true) : key.type !== 4 ? createCompoundExpression([
`(`,
key,
`) === "onClick" ? "${event}" : (`,
key,
`)`
]) : key;
};
const transformOn = (dir, node, context) => {
return transformOn$1(dir, node, context, (baseResult) => {
const { modifiers } = dir;
if (!modifiers.length) return baseResult;
let { key, value: handlerExp } = baseResult.props[0];
const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers, context, dir.loc);
if (nonKeyModifiers.includes("right")) {
key = transformClick(key, `onContextmenu`);
}
if (nonKeyModifiers.includes("middle")) {
key = transformClick(key, `onMouseup`);
}
if (nonKeyModifiers.length) {
handlerExp = createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [
handlerExp,
JSON.stringify(nonKeyModifiers)
]);
}
if (keyModifiers.length && // if event name is dynamic, always wrap with keys guard
(!isStaticExp(key) || isKeyboardEvent(key.content.toLowerCase()))) {
handlerExp = createCallExpression(context.helper(V_ON_WITH_KEYS), [
handlerExp,
JSON.stringify(keyModifiers)
]);
}
if (eventOptionModifiers.length) {
const modifierPostfix = eventOptionModifiers.map(capitalize).join("");
key = isStaticExp(key) ? createSimpleExpression(`${key.content}${modifierPostfix}`, true) : createCompoundExpression([`(`, key, `) + "${modifierPostfix}"`]);
}
return {
props: [createObjectProperty(key, handlerExp)]
};
});
};
const transformShow = (dir, node, context) => {
const { exp, loc } = dir;
if (!exp) {
context.onError(
createDOMCompilerError(62, loc)
);
}
return {
props: [],
needRuntime: context.helper(V_SHOW)
};
};
const transformTransition = (node, context) => {
if (node.type === 1 && node.tagType === 1) {
const component = context.isBuiltInComponent(node.tag);
if (component === TRANSITION) {
return () => {
if (!node.children.length) {
return;
}
if (hasMultipleChildren(node)) {
context.onError(
createDOMCompilerError(
63,
{
start: node.children[0].loc.start,
end: node.children[node.children.length - 1].loc.end,
source: ""
}
)
);
}
const child = node.children[0];
if (child.type === 1) {
for (const p of child.props) {
if (p.type === 7 && p.name === "show") {
node.props.push({
type: 6,
name: "persisted",
nameLoc: node.loc,
value: void 0,
loc: node.loc
});
}
}
}
};
}
}
};
function hasMultipleChildren(node) {
const children = node.children = node.children.filter(
(c) => !isCommentOrWhitespace(c)
);
const child = children[0];
return children.length !== 1 || child.type === 11 || child.type === 9 && child.branches.some(hasMultipleChildren);
}
const ignoreSideEffectTags = (node, context) => {
if (node.type === 1 && node.tagType === 0 && (node.tag === "script" || node.tag === "style")) {
!!(process.env.NODE_ENV !== "production") && context.onError(
createDOMCompilerError(
64,
node.loc
)
);
context.removeNode();
}
};
function isValidHTMLNesting(parent, child) {
if (parent === "template") {
return true;
}
if (parent in onlyValidChildren) {
return onlyValidChildren[parent].has(child);
}
if (child in onlyValidParents) {
return onlyValidParents[child].has(parent);
}
if (parent in knownInvalidChildren) {
if (knownInvalidChildren[parent].has(child)) return false;
}
if (child in knownInvalidParents) {
if (knownInvalidParents[child].has(parent)) return false;
}
return true;
}
const headings = /* @__PURE__ */ new Set(["h1", "h2", "h3", "h4", "h5", "h6"]);
const emptySet = /* @__PURE__ */ new Set([]);
const onlyValidChildren = {
head: /* @__PURE__ */ new Set([
"base",
"basefront",
"bgsound",
"link",
"meta",
"title",
"noscript",
"noframes",
"style",
"script",
"template"
]),
optgroup: /* @__PURE__ */ new Set(["option"]),
select: /* @__PURE__ */ new Set(["optgroup", "option", "hr"]),
// table
table: /* @__PURE__ */ new Set(["caption", "colgroup", "tbody", "tfoot", "thead"]),
tr: /* @__PURE__ */ new Set(["td", "th"]),
colgroup: /* @__PURE__ */ new Set(["col"]),
tbody: /* @__PURE__ */ new Set(["tr"]),
thead: /* @__PURE__ */ new Set(["tr"]),
tfoot: /* @__PURE__ */ new Set(["tr"]),
// these elements can not have any children elements
script: emptySet,
iframe: emptySet,
option: emptySet,
textarea: emptySet,
style: emptySet,
title: emptySet
};
const onlyValidParents = {
// sections
html: emptySet,
body: /* @__PURE__ */ new Set(["html"]),
head: /* @__PURE__ */ new Set(["html"]),
// table
td: /* @__PURE__ */ new Set(["tr"]),
colgroup: /* @__PURE__ */ new Set(["table"]),
caption: /* @__PURE__ */ new Set(["table"]),
tbody: /* @__PURE__ */ new Set(["table"]),
tfoot: /* @__PURE__ */ new Set(["table"]),
col: /* @__PURE__ */ new Set(["colgroup"]),
th: /* @__PURE__ */ new Set(["tr"]),
thead: /* @__PURE__ */ new Set(["table"]),
tr: /* @__PURE__ */ new Set(["tbody", "thead", "tfoot"]),
// data list
dd: /* @__PURE__ */ new Set(["dl", "div"]),
dt: /* @__PURE__ */ new Set(["dl", "div"]),
// other
figcaption: /* @__PURE__ */ new Set(["figure"]),
// li: new Set(["ul", "ol"]),
summary: /* @__PURE__ */ new Set(["details"]),
area: /* @__PURE__ */ new Set(["map"])
};
const knownInvalidChildren = {
p: /* @__PURE__ */ new Set([
"address",
"article",
"aside",
"blockquote",
"center",
"details",
"dialog",
"dir",
"div",
"dl",
"fieldset",
"figure",
"footer",
"form",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"header",
"hgroup",
"hr",
"li",
"main",
"nav",
"menu",
"ol",
"p",
"pre",
"section",
"table",
"ul"
]),
svg: /* @__PURE__ */ new Set([
"b",
"blockquote",
"br",
"code",
"dd",
"div",
"dl",
"dt",
"em",
"embed",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"hr",
"i",
"img",
"li",
"menu",
"meta",
"ol",
"p",
"pre",
"ruby",
"s",
"small",
"span",
"strong",
"sub",
"sup",
"table",
"u",
"ul",
"var"
])
};
const knownInvalidParents = {
a: /* @__PURE__ */ new Set(["a"]),
button: /* @__PURE__ */ new Set(["button"]),
dd: /* @__PURE__ */ new Set(["dd", "dt"]),
dt: /* @__PURE__ */ new Set(["dd", "dt"]),
form: /* @__PURE__ */ new Set(["form"]),
li: /* @__PURE__ */ new Set(["li"]),
h1: headings,
h2: headings,
h3: headings,
h4: headings,
h5: headings,
h6: headings
};
const validateHtmlNesting = (node, context) => {
if (node.type === 1 && node.tagType === 0 && context.parent && context.parent.type === 1 && context.parent.tagType === 0 && !isValidHTMLNesting(context.parent.tag, node.tag)) {
const error = new SyntaxError(
`<${node.tag}> cannot be child of <${context.parent.tag}>, according to HTML specifications. This can cause hydration errors or potentially disrupt future functionality.`
);
error.loc = node.loc;
context.onWarn(error);
}
};
const DOMNodeTransforms = [
transformStyle,
...!!(process.env.NODE_ENV !== "production") ? [transformTransition, validateHtmlNesting] : []
];
const DOMDirectiveTransforms = {
cloak: noopDirectiveTransform,
html: transformVHtml,
text: transformVText,
model: transformModel,
// override compiler-core
on: transformOn,
// override compiler-core
show: transformShow
};
function compile(src, options = {}) {
return baseCompile(
src,
extend({}, parserOptions, options, {
nodeTransforms: [
// ignore <script> and <tag>
// this is not put inside DOMNodeTransforms because that list is used
// by compiler-ssr to generate vnode fallback branches
ignoreSideEffectTags,
...DOMNodeTransforms,
...options.nodeTransforms || []
],
directiveTransforms: extend(
{},
DOMDirectiveTransforms,
options.directiveTransforms || {}
),
transformHoist: null
})
);
}
function parse(template, options = {}) {
return baseParse(template, extend({}, parserOptions, options));
}
export { DOMDirectiveTransforms, DOMErrorCodes, DOMErrorMessages, DOMNodeTransforms, TRANSITION, TRANSITION_GROUP, V_MODEL_CHECKBOX, V_MODEL_DYNAMIC, V_MODEL_RADIO, V_MODEL_SELECT, V_MODEL_TEXT, V_ON_WITH_KEYS, V_ON_WITH_MODIFIERS, V_SHOW, compile, createDOMCompilerError, parse, parserOptions, transformStyle };

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

7
node_modules/@vue/compiler-dom/index.js generated vendored Normal file
View File

@@ -0,0 +1,7 @@
'use strict'
if (process.env.NODE_ENV === 'production') {
module.exports = require('./dist/compiler-dom.cjs.prod.js')
} else {
module.exports = require('./dist/compiler-dom.cjs.js')
}

57
node_modules/@vue/compiler-dom/package.json generated vendored Normal file
View File

@@ -0,0 +1,57 @@
{
"name": "@vue/compiler-dom",
"version": "3.5.26",
"description": "@vue/compiler-dom",
"main": "index.js",
"module": "dist/compiler-dom.esm-bundler.js",
"types": "dist/compiler-dom.d.ts",
"unpkg": "dist/compiler-dom.global.js",
"jsdelivr": "dist/compiler-dom.global.js",
"files": [
"index.js",
"dist"
],
"exports": {
".": {
"types": "./dist/compiler-dom.d.ts",
"node": {
"production": "./dist/compiler-dom.cjs.prod.js",
"development": "./dist/compiler-dom.cjs.js",
"default": "./index.js"
},
"module": "./dist/compiler-dom.esm-bundler.js",
"import": "./dist/compiler-dom.esm-bundler.js",
"require": "./index.js"
},
"./*": "./*"
},
"sideEffects": false,
"buildOptions": {
"name": "VueCompilerDOM",
"compat": true,
"formats": [
"esm-bundler",
"esm-browser",
"cjs",
"global"
]
},
"repository": {
"type": "git",
"url": "git+https://github.com/vuejs/core.git",
"directory": "packages/compiler-dom"
},
"keywords": [
"vue"
],
"author": "Evan You",
"license": "MIT",
"bugs": {
"url": "https://github.com/vuejs/core/issues"
},
"homepage": "https://github.com/vuejs/core/tree/main/packages/compiler-dom#readme",
"dependencies": {
"@vue/compiler-core": "3.5.26",
"@vue/shared": "3.5.26"
}
}

21
node_modules/@vue/compiler-sfc/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2018-present, Yuxi (Evan) You
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

79
node_modules/@vue/compiler-sfc/README.md generated vendored Normal file
View File

@@ -0,0 +1,79 @@
# @vue/compiler-sfc
> Lower level utilities for compiling Vue Single File Components
**Note: as of 3.2.13+, this package is included as a dependency of the main `vue` package and can be accessed as `vue/compiler-sfc`. This means you no longer need to explicitly install this package and ensure its version match that of `vue`'s. Just use the main `vue/compiler-sfc` deep import instead.**
This package contains lower level utilities that you can use if you are writing a plugin / transform for a bundler or module system that compiles Vue Single File Components (SFCs) into JavaScript. It is used in [vue-loader](https://github.com/vuejs/vue-loader) and [@vitejs/plugin-vue](https://github.com/vitejs/vite-plugin-vue/tree/main/packages/plugin-vue).
## API
The API is intentionally low-level due to the various considerations when integrating Vue SFCs in a build system:
- Separate hot-module replacement (HMR) for script, template and styles
- template updates should not reset component state
- style updates should be performed without component re-render
- Leveraging the tool's plugin system for pre-processor handling. e.g. `<style lang="scss">` should be processed by the corresponding webpack loader.
- In some cases, transformers of each block in an SFC do not share the same execution context. For example, when used with `thread-loader` or other parallelized configurations, the template sub-loader in `vue-loader` may not have access to the full SFC and its descriptor.
The general idea is to generate a facade module that imports the individual blocks of the component. The trick is the module imports itself with different query strings so that the build system can handle each request as "virtual" modules:
```
+--------------------+
| |
| script transform |
+----->+ |
| +--------------------+
|
+--------------------+ | +--------------------+
| | | | |
| facade transform +----------->+ template transform |
| | | | |
+--------------------+ | +--------------------+
|
| +--------------------+
+----->+ |
| style transform |
| |
+--------------------+
```
Where the facade module looks like this:
```js
// main script
import script from '/project/foo.vue?vue&type=script'
// template compiled to render function
import { render } from '/project/foo.vue?vue&type=template&id=xxxxxx'
// css
import '/project/foo.vue?vue&type=style&index=0&id=xxxxxx'
// attach render function to script
script.render = render
// attach additional metadata
// some of these should be dev only
script.__file = 'example.vue'
script.__scopeId = 'xxxxxx'
// additional tooling-specific HMR handling code
// using __VUE_HMR_API__ global
export default script
```
### High Level Workflow
1. In facade transform, parse the source into descriptor with the `parse` API and generate the above facade module code based on the descriptor;
2. In script transform, use `compileScript` to process the script. This handles features like `<script setup>` and CSS variable injection. Alternatively, this can be done directly in the facade module (with the code inlined instead of imported), but it will require rewriting `export default` to a temp variable (a `rewriteDefault` convenience API is provided for this purpose) so additional options can be attached to the exported object.
3. In template transform, use `compileTemplate` to compile the raw template into render function code.
4. In style transform, use `compileStyle` to compile raw CSS to handle `<style scoped>`, `<style module>` and CSS variable injection.
Options needed for these APIs can be passed via the query string.
For detailed API references and options, check out the source type definitions. For actual usage of these APIs, check out [@vitejs/plugin-vue](https://github.com/vitejs/vite-plugin-vue/tree/main/packages/plugin-vue) or [vue-loader](https://github.com/vuejs/vue-loader/tree/next).

25179
node_modules/@vue/compiler-sfc/dist/compiler-sfc.cjs.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

485
node_modules/@vue/compiler-sfc/dist/compiler-sfc.d.ts generated vendored Normal file
View File

@@ -0,0 +1,485 @@
import * as _babel_types from '@babel/types';
import { Statement, Expression, TSType, Node, Program, CallExpression, ObjectPattern, TSModuleDeclaration, TSPropertySignature, TSMethodSignature, TSCallSignatureDeclaration, TSFunctionType } from '@babel/types';
import { RootNode, CompilerOptions, CodegenResult, ParserOptions, RawSourceMap, CompilerError, SourceLocation, BindingMetadata as BindingMetadata$1 } from '@vue/compiler-core';
export { BindingMetadata, CompilerError, CompilerOptions, extractIdentifiers, generateCodeFrame, isInDestructureAssignment, isStaticProperty, walkIdentifiers } from '@vue/compiler-core';
import { ParserPlugin } from '@babel/parser';
export { parse as babelParse } from '@babel/parser';
import { Result, LazyResult } from 'postcss';
import MagicString from 'magic-string';
export { default as MagicString } from 'magic-string';
import TS from 'typescript';
export interface AssetURLTagConfig {
[name: string]: string[];
}
export interface AssetURLOptions {
/**
* If base is provided, instead of transforming relative asset urls into
* imports, they will be directly rewritten to absolute urls.
*/
base?: string | null;
/**
* If true, also processes absolute urls.
*/
includeAbsolute?: boolean;
tags?: AssetURLTagConfig;
}
export interface TemplateCompiler {
compile(source: string | RootNode, options: CompilerOptions): CodegenResult;
parse(template: string, options: ParserOptions): RootNode;
}
export interface SFCTemplateCompileResults {
code: string;
ast?: RootNode;
preamble?: string;
source: string;
tips: string[];
errors: (string | CompilerError)[];
map?: RawSourceMap;
}
export interface SFCTemplateCompileOptions {
source: string;
ast?: RootNode;
filename: string;
id: string;
scoped?: boolean;
slotted?: boolean;
isProd?: boolean;
ssr?: boolean;
ssrCssVars?: string[];
inMap?: RawSourceMap;
compiler?: TemplateCompiler;
compilerOptions?: CompilerOptions;
preprocessLang?: string;
preprocessOptions?: any;
/**
* In some cases, compiler-sfc may not be inside the project root (e.g. when
* linked or globally installed). In such cases a custom `require` can be
* passed to correctly resolve the preprocessors.
*/
preprocessCustomRequire?: (id: string) => any;
/**
* Configure what tags/attributes to transform into asset url imports,
* or disable the transform altogether with `false`.
*/
transformAssetUrls?: AssetURLOptions | AssetURLTagConfig | boolean;
}
export declare function compileTemplate(options: SFCTemplateCompileOptions): SFCTemplateCompileResults;
export interface SFCScriptCompileOptions {
/**
* Scope ID for prefixing injected CSS variables.
* This must be consistent with the `id` passed to `compileStyle`.
*/
id: string;
/**
* Production mode. Used to determine whether to generate hashed CSS variables
*/
isProd?: boolean;
/**
* Enable/disable source map. Defaults to true.
*/
sourceMap?: boolean;
/**
* https://babeljs.io/docs/en/babel-parser#plugins
*/
babelParserPlugins?: ParserPlugin[];
/**
* A list of files to parse for global types to be made available for type
* resolving in SFC macros. The list must be fully resolved file system paths.
*/
globalTypeFiles?: string[];
/**
* Compile the template and inline the resulting render function
* directly inside setup().
* - Only affects `<script setup>`
* - This should only be used in production because it prevents the template
* from being hot-reloaded separately from component state.
*/
inlineTemplate?: boolean;
/**
* Generate the final component as a variable instead of default export.
* This is useful in e.g. @vitejs/plugin-vue where the script needs to be
* placed inside the main module.
*/
genDefaultAs?: string;
/**
* Options for template compilation when inlining. Note these are options that
* would normally be passed to `compiler-sfc`'s own `compileTemplate()`, not
* options passed to `compiler-dom`.
*/
templateOptions?: Partial<SFCTemplateCompileOptions>;
/**
* Hoist <script setup> static constants.
* - Only enables when one `<script setup>` exists.
* @default true
*/
hoistStatic?: boolean;
/**
* Set to `false` to disable reactive destructure for `defineProps` (pre-3.5
* behavior), or set to `'error'` to throw hard error on props destructures.
* @default true
*/
propsDestructure?: boolean | 'error';
/**
* File system access methods to be used when resolving types
* imported in SFC macros. Defaults to ts.sys in Node.js, can be overwritten
* to use a virtual file system for use in browsers (e.g. in REPLs)
*/
fs?: {
fileExists(file: string): boolean;
readFile(file: string): string | undefined;
realpath?(file: string): string;
};
/**
* Transform Vue SFCs into custom elements.
*/
customElement?: boolean | ((filename: string) => boolean);
}
interface ImportBinding {
isType: boolean;
imported: string;
local: string;
source: string;
isFromSetup: boolean;
isUsedInTemplate: boolean;
}
/**
* Compile `<script setup>`
* It requires the whole SFC descriptor because we need to handle and merge
* normal `<script>` + `<script setup>` if both are present.
*/
export declare function compileScript(sfc: SFCDescriptor, options: SFCScriptCompileOptions): SFCScriptBlock;
export interface SFCParseOptions {
filename?: string;
sourceMap?: boolean;
sourceRoot?: string;
pad?: boolean | 'line' | 'space';
ignoreEmpty?: boolean;
compiler?: TemplateCompiler;
templateParseOptions?: ParserOptions;
}
export interface SFCBlock {
type: string;
content: string;
attrs: Record<string, string | true>;
loc: SourceLocation;
map?: RawSourceMap;
lang?: string;
src?: string;
}
export interface SFCTemplateBlock extends SFCBlock {
type: 'template';
ast?: RootNode;
}
export interface SFCScriptBlock extends SFCBlock {
type: 'script';
setup?: string | boolean;
bindings?: BindingMetadata$1;
imports?: Record<string, ImportBinding>;
scriptAst?: _babel_types.Statement[];
scriptSetupAst?: _babel_types.Statement[];
warnings?: string[];
/**
* Fully resolved dependency file paths (unix slashes) with imported types
* used in macros, used for HMR cache busting in @vitejs/plugin-vue and
* vue-loader.
*/
deps?: string[];
}
export interface SFCStyleBlock extends SFCBlock {
type: 'style';
scoped?: boolean;
module?: string | boolean;
}
export interface SFCDescriptor {
filename: string;
source: string;
template: SFCTemplateBlock | null;
script: SFCScriptBlock | null;
scriptSetup: SFCScriptBlock | null;
styles: SFCStyleBlock[];
customBlocks: SFCBlock[];
cssVars: string[];
/**
* whether the SFC uses :slotted() modifier.
* this is used as a compiler optimization hint.
*/
slotted: boolean;
/**
* compare with an existing descriptor to determine whether HMR should perform
* a reload vs. re-render.
*
* Note: this comparison assumes the prev/next script are already identical,
* and only checks the special case where <script setup lang="ts"> unused import
* pruning result changes due to template changes.
*/
shouldForceReload: (prevImports: Record<string, ImportBinding>) => boolean;
}
export interface SFCParseResult {
descriptor: SFCDescriptor;
errors: (CompilerError | SyntaxError)[];
}
export declare function parse(source: string, options?: SFCParseOptions): SFCParseResult;
type PreprocessLang = 'less' | 'sass' | 'scss' | 'styl' | 'stylus';
export interface SFCStyleCompileOptions {
source: string;
filename: string;
id: string;
scoped?: boolean;
trim?: boolean;
isProd?: boolean;
inMap?: RawSourceMap;
preprocessLang?: PreprocessLang;
preprocessOptions?: any;
preprocessCustomRequire?: (id: string) => any;
postcssOptions?: any;
postcssPlugins?: any[];
/**
* @deprecated use `inMap` instead.
*/
map?: RawSourceMap;
}
/**
* Aligns with postcss-modules
* https://github.com/css-modules/postcss-modules
*/
interface CSSModulesOptions {
scopeBehaviour?: 'global' | 'local';
generateScopedName?: string | ((name: string, filename: string, css: string) => string);
hashPrefix?: string;
localsConvention?: 'camelCase' | 'camelCaseOnly' | 'dashes' | 'dashesOnly';
exportGlobals?: boolean;
globalModulePaths?: RegExp[];
}
export interface SFCAsyncStyleCompileOptions extends SFCStyleCompileOptions {
isAsync?: boolean;
modules?: boolean;
modulesOptions?: CSSModulesOptions;
}
export interface SFCStyleCompileResults {
code: string;
map: RawSourceMap | undefined;
rawResult: Result | LazyResult | undefined;
errors: Error[];
modules?: Record<string, string>;
dependencies: Set<string>;
}
export declare function compileStyle(options: SFCStyleCompileOptions): SFCStyleCompileResults;
export declare function compileStyleAsync(options: SFCAsyncStyleCompileOptions): Promise<SFCStyleCompileResults>;
export declare function rewriteDefault(input: string, as: string, parserPlugins?: ParserPlugin[]): string;
/**
* Utility for rewriting `export default` in a script block into a variable
* declaration so that we can inject things into it
*/
export declare function rewriteDefaultAST(ast: Statement[], s: MagicString, as: string): void;
type PropsDestructureBindings = Record<string, // public prop key
{
local: string;
default?: Expression;
}>;
export declare function extractRuntimeProps(ctx: TypeResolveContext): string | undefined;
interface ModelDecl {
type: TSType | undefined;
options: string | undefined;
identifier: string | undefined;
runtimeOptionNodes: Node[];
}
declare enum BindingTypes {
/**
* returned from data()
*/
DATA = "data",
/**
* declared as a prop
*/
PROPS = "props",
/**
* a local alias of a `<script setup>` destructured prop.
* the original is stored in __propsAliases of the bindingMetadata object.
*/
PROPS_ALIASED = "props-aliased",
/**
* a let binding (may or may not be a ref)
*/
SETUP_LET = "setup-let",
/**
* a const binding that can never be a ref.
* these bindings don't need `unref()` calls when processed in inlined
* template expressions.
*/
SETUP_CONST = "setup-const",
/**
* a const binding that does not need `unref()`, but may be mutated.
*/
SETUP_REACTIVE_CONST = "setup-reactive-const",
/**
* a const binding that may be a ref.
*/
SETUP_MAYBE_REF = "setup-maybe-ref",
/**
* bindings that are guaranteed to be refs
*/
SETUP_REF = "setup-ref",
/**
* declared by other options, e.g. computed, inject
*/
OPTIONS = "options",
/**
* a literal constant, e.g. 'foo', 1, true
*/
LITERAL_CONST = "literal-const"
}
type BindingMetadata = {
[key: string]: BindingTypes | undefined;
} & {
__isScriptSetup?: boolean;
__propsAliases?: Record<string, string>;
};
export declare class ScriptCompileContext {
descriptor: SFCDescriptor;
options: Partial<SFCScriptCompileOptions>;
isJS: boolean;
isTS: boolean;
isCE: boolean;
scriptAst: Program | null;
scriptSetupAst: Program | null;
source: string;
filename: string;
s: MagicString;
startOffset: number | undefined;
endOffset: number | undefined;
scope?: TypeScope;
globalScopes?: TypeScope[];
userImports: Record<string, ImportBinding>;
hasDefinePropsCall: boolean;
hasDefineEmitCall: boolean;
hasDefineExposeCall: boolean;
hasDefaultExportName: boolean;
hasDefaultExportRender: boolean;
hasDefineOptionsCall: boolean;
hasDefineSlotsCall: boolean;
hasDefineModelCall: boolean;
propsCall: CallExpression | undefined;
propsDecl: Node | undefined;
propsRuntimeDecl: Node | undefined;
propsTypeDecl: Node | undefined;
propsDestructureDecl: ObjectPattern | undefined;
propsDestructuredBindings: PropsDestructureBindings;
propsDestructureRestId: string | undefined;
propsRuntimeDefaults: Node | undefined;
emitsRuntimeDecl: Node | undefined;
emitsTypeDecl: Node | undefined;
emitDecl: Node | undefined;
modelDecls: Record<string, ModelDecl>;
optionsRuntimeDecl: Node | undefined;
bindingMetadata: BindingMetadata;
helperImports: Set<string>;
helper(key: string): string;
/**
* to be exposed on compiled script block for HMR cache busting
*/
deps?: Set<string>;
/**
* cache for resolved fs
*/
fs?: NonNullable<SFCScriptCompileOptions['fs']>;
constructor(descriptor: SFCDescriptor, options: Partial<SFCScriptCompileOptions>);
getString(node: Node, scriptSetup?: boolean): string;
warn(msg: string, node: Node, scope?: TypeScope): void;
error(msg: string, node: Node, scope?: TypeScope): never;
}
export type SimpleTypeResolveOptions = Partial<Pick<SFCScriptCompileOptions, 'globalTypeFiles' | 'fs' | 'babelParserPlugins' | 'isProd'>>;
/**
* TypeResolveContext is compatible with ScriptCompileContext
* but also allows a simpler version of it with minimal required properties
* when resolveType needs to be used in a non-SFC context, e.g. in a babel
* plugin. The simplest context can be just:
* ```ts
* const ctx: SimpleTypeResolveContext = {
* filename: '...',
* source: '...',
* options: {},
* error() {},
* ast: []
* }
* ```
*/
export type SimpleTypeResolveContext = Pick<ScriptCompileContext, 'source' | 'filename' | 'error' | 'helper' | 'getString' | 'propsTypeDecl' | 'propsRuntimeDefaults' | 'propsDestructuredBindings' | 'emitsTypeDecl' | 'isCE'> & Partial<Pick<ScriptCompileContext, 'scope' | 'globalScopes' | 'deps' | 'fs'>> & {
ast: Statement[];
options: SimpleTypeResolveOptions;
};
export type TypeResolveContext = ScriptCompileContext | SimpleTypeResolveContext;
type Import = Pick<ImportBinding, 'source' | 'imported'>;
interface WithScope {
_ownerScope: TypeScope;
}
type ScopeTypeNode = Node & WithScope & {
_ns?: TSModuleDeclaration & WithScope;
};
declare class TypeScope {
filename: string;
source: string;
offset: number;
imports: Record<string, Import>;
types: Record<string, ScopeTypeNode>;
declares: Record<string, ScopeTypeNode>;
constructor(filename: string, source: string, offset?: number, imports?: Record<string, Import>, types?: Record<string, ScopeTypeNode>, declares?: Record<string, ScopeTypeNode>);
isGenericScope: boolean;
resolvedImportSources: Record<string, string>;
exportedTypes: Record<string, ScopeTypeNode>;
exportedDeclares: Record<string, ScopeTypeNode>;
}
interface MaybeWithScope {
_ownerScope?: TypeScope;
}
interface ResolvedElements {
props: Record<string, (TSPropertySignature | TSMethodSignature) & {
_ownerScope: TypeScope;
}>;
calls?: (TSCallSignatureDeclaration | TSFunctionType)[];
}
/**
* Resolve arbitrary type node to a list of type elements that can be then
* mapped to runtime props or emits.
*/
export declare function resolveTypeElements(ctx: TypeResolveContext, node: Node & MaybeWithScope & {
_resolvedElements?: ResolvedElements;
}, scope?: TypeScope, typeParameters?: Record<string, Node>): ResolvedElements;
/**
* @private
*/
export declare function registerTS(_loadTS: () => typeof TS): void;
/**
* @private
*/
export declare function invalidateTypeCache(filename: string): void;
export declare function inferRuntimeType(ctx: TypeResolveContext, node: Node & MaybeWithScope, scope?: TypeScope, isKeyOf?: boolean, typeParameters?: Record<string, Node>): string[];
export declare function extractRuntimeEmits(ctx: TypeResolveContext): Set<string>;
export declare const version: string;
export declare const parseCache: Map<string, SFCParseResult>;
export declare const errorMessages: Record<number, string>;
export declare const walk: any;
/**
* @deprecated this is preserved to avoid breaking vite-plugin-vue < 5.0
* with reactivityTransform: true. The desired behavior should be silently
* ignoring the option instead of breaking.
*/
export declare const shouldTransformRef: () => boolean;

File diff suppressed because one or more lines are too long

67
node_modules/@vue/compiler-sfc/package.json generated vendored Normal file
View File

@@ -0,0 +1,67 @@
{
"name": "@vue/compiler-sfc",
"version": "3.5.26",
"description": "@vue/compiler-sfc",
"main": "dist/compiler-sfc.cjs.js",
"module": "dist/compiler-sfc.esm-browser.js",
"types": "dist/compiler-sfc.d.ts",
"files": [
"dist"
],
"exports": {
".": {
"types": "./dist/compiler-sfc.d.ts",
"node": "./dist/compiler-sfc.cjs.js",
"module": "./dist/compiler-sfc.esm-browser.js",
"import": "./dist/compiler-sfc.esm-browser.js",
"require": "./dist/compiler-sfc.cjs.js"
},
"./*": "./*"
},
"buildOptions": {
"name": "VueCompilerSFC",
"formats": [
"cjs",
"esm-browser"
],
"prod": false,
"enableNonBrowserBranches": true
},
"repository": {
"type": "git",
"url": "git+https://github.com/vuejs/core.git",
"directory": "packages/compiler-sfc"
},
"keywords": [
"vue"
],
"author": "Evan You",
"license": "MIT",
"bugs": {
"url": "https://github.com/vuejs/core/issues"
},
"homepage": "https://github.com/vuejs/core/tree/main/packages/compiler-sfc#readme",
"dependencies": {
"@babel/parser": "^7.28.5",
"estree-walker": "^2.0.2",
"magic-string": "^0.30.21",
"postcss": "^8.5.6",
"source-map-js": "^1.2.1",
"@vue/compiler-core": "3.5.26",
"@vue/compiler-dom": "3.5.26",
"@vue/compiler-ssr": "3.5.26",
"@vue/shared": "3.5.26"
},
"devDependencies": {
"@babel/types": "^7.28.5",
"@vue/consolidate": "^1.0.0",
"hash-sum": "^2.0.0",
"lru-cache": "10.1.0",
"merge-source-map": "^1.1.0",
"minimatch": "~10.1.1",
"postcss-modules": "^6.0.1",
"postcss-selector-parser": "^7.1.0",
"pug": "^3.0.3",
"sass": "^1.96.0"
}
}

21
node_modules/@vue/compiler-ssr/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2018-present, Yuxi (Evan) You
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

1
node_modules/@vue/compiler-ssr/README.md generated vendored Normal file
View File

@@ -0,0 +1 @@
# @vue/compiler-ssr

1413
node_modules/@vue/compiler-ssr/dist/compiler-ssr.cjs.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,4 @@
import { RootNode, CompilerOptions, CodegenResult } from '@vue/compiler-dom';
export declare function compile(source: string | RootNode, options?: CompilerOptions): CodegenResult;

34
node_modules/@vue/compiler-ssr/package.json generated vendored Normal file
View File

@@ -0,0 +1,34 @@
{
"name": "@vue/compiler-ssr",
"version": "3.5.26",
"description": "@vue/compiler-ssr",
"main": "dist/compiler-ssr.cjs.js",
"types": "dist/compiler-ssr.d.ts",
"files": [
"dist"
],
"buildOptions": {
"prod": false,
"formats": [
"cjs"
]
},
"repository": {
"type": "git",
"url": "git+https://github.com/vuejs/core.git",
"directory": "packages/compiler-ssr"
},
"keywords": [
"vue"
],
"author": "Evan You",
"license": "MIT",
"bugs": {
"url": "https://github.com/vuejs/core/issues"
},
"homepage": "https://github.com/vuejs/core/tree/main/packages/compiler-ssr#readme",
"dependencies": {
"@vue/shared": "3.5.26",
"@vue/compiler-dom": "3.5.26"
}
}

162
node_modules/@vue/compiler-vue2/README.md generated vendored Normal file
View File

@@ -0,0 +1,162 @@
# vue-template-compiler
> This package is auto-generated. For pull requests please see [src/platforms/web/entry-compiler.js](https://github.com/vuejs/vue/tree/dev/src/platforms/web/entry-compiler.js).
This package can be used to pre-compile Vue 2.0 templates into render functions to avoid runtime-compilation overhead and CSP restrictions. In most cases you should be using it with [`vue-loader`](https://github.com/vuejs/vue-loader), you will only need it separately if you are writing build tools with very specific needs.
## Installation
``` bash
npm install vue-template-compiler
```
``` js
const compiler = require('vue-template-compiler')
```
## API
### compiler.compile(template, [options])
Compiles a template string and returns compiled JavaScript code. The returned result is an object of the following format:
``` js
{
ast: ?ASTElement, // parsed template elements to AST
render: string, // main render function code
staticRenderFns: Array<string>, // render code for static sub trees, if any
errors: Array<string> // template syntax errors, if any
}
```
Note the returned function code uses `with` and thus cannot be used in strict mode code.
#### Options
- `outputSourceRange` *new in 2.6*
- Type: `boolean`
- Default: `false`
Set this to true will cause the `errors` returned in the compiled result become objects in the form of `{ msg, start, end }`. The `start` and `end` properties are numbers that mark the code range of the error source in the template. This can be passed on to the `compiler.generateCodeFrame` API to generate a code frame for the error.
- `whitespace`
- Type: `string`
- Valid values: `'preserve' | 'condense'`
- Default: `'preserve'`
The default value `'preserve'` handles whitespaces as follows:
- A whitespace-only text node between element tags is condensed into a single space.
- All other whitespaces are preserved as-is.
If set to `'condense'`:
- A whitespace-only text node between element tags is removed if it contains new lines. Otherwise, it is condensed into a single space.
- Consecutive whitespaces inside a non-whitespace-only text node are condensed into a single space.
Using condense mode will result in smaller compiled code size and slightly improved performance. However, it will produce minor visual layout differences compared to plain HTML in certain cases.
**This option does not affect the `<pre>` tag.**
Example:
``` html
<!-- source -->
<div>
<span>
foo
</span> <span>bar</span>
</div>
<!-- whitespace: 'preserve' -->
<div> <span>
foo
</span> <span>bar</span> </div>
<!-- whitespace: 'condense' -->
<div><span> foo </span> <span>bar</span></div>
```
- `modules`
It's possible to hook into the compilation process to support custom template features. **However, beware that by injecting custom compile-time modules, your templates will not work with other build tools built on standard built-in modules, e.g `vue-loader` and `vueify`.**
An array of compiler modules. For details on compiler modules, refer to the `ModuleOptions` type in [flow declarations](https://github.com/vuejs/vue/blob/dev/flow/compiler.js#L47-L59) and the [built-in modules](https://github.com/vuejs/vue/tree/dev/src/platforms/web/compiler/modules).
- `directives`
An object where the key is the directive name and the value is a function that transforms an template AST node. For example:
``` js
compiler.compile('<div v-test></div>', {
directives: {
test (node, directiveMeta) {
// transform node based on directiveMeta
}
}
})
```
By default, a compile-time directive will extract the directive and the directive will not be present at runtime. If you want the directive to also be handled by a runtime definition, return `true` in the transform function.
Refer to the implementation of some [built-in compile-time directives](https://github.com/vuejs/vue/tree/dev/src/platforms/web/compiler/directives).
- `preserveWhitespace` **Deprecated since 2.6**
- Type: `boolean`
- Default: `true`
By default, the compiled render function preserves all whitespace characters between HTML tags. If set to `false`, whitespace between tags will be ignored. This can result in slightly better performance but may affect layout for inline elements.
---
### compiler.compileToFunctions(template)
Similar to `compiler.compile`, but directly returns instantiated functions:
``` js
{
render: Function,
staticRenderFns: Array<Function>
}
```
This is only useful at runtime with pre-configured builds, so it doesn't accept any compile-time options. In addition, this method uses `new Function()` so it is not CSP-compliant.
---
### compiler.ssrCompile(template, [options])
> 2.4.0+
Same as `compiler.compile` but generates SSR-specific render function code by optimizing parts of the template into string concatenation in order to improve SSR performance.
This is used by default in `vue-loader@>=12` and can be disabled using the [`optimizeSSR`](https://vue-loader.vuejs.org/en/options.html#optimizessr) option.
---
### compiler.ssrCompileToFunctions(template)
> 2.4.0+
Same as `compiler.compileToFunction` but generates SSR-specific render function code by optimizing parts of the template into string concatenation in order to improve SSR performance.
---
### compiler.parseComponent(file, [options])
Parse a SFC (single-file component, or `*.vue` file) into a descriptor (refer to the `SFCDescriptor` type in [flow declarations](https://github.com/vuejs/vue/blob/dev/flow/compiler.js)). This is used in SFC build tools like `vue-loader` and `vueify`.
---
### compiler.generateCodeFrame(template, start, end)
Generate a code frame that highlights the part in `template` defined by `start` and `end`. Useful for error reporting in higher-level tooling.
#### Options
#### `pad`
`pad` is useful when you are piping the extracted content into other pre-processors, as you will get correct line numbers or character indices if there are any syntax errors.
- with `{ pad: "line" }`, the extracted content for each block will be prefixed with one newline for each line in the leading content from the original file to ensure that the line numbers align with the original file.
- with `{ pad: "space" }`, the extracted content for each block will be prefixed with one space for each character in the leading content from the original file to ensure that the character count remains the same as the original file.

7140
node_modules/@vue/compiler-vue2/browser.js generated vendored Normal file

File diff suppressed because one or more lines are too long

6670
node_modules/@vue/compiler-vue2/build.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

32
node_modules/@vue/compiler-vue2/index.js generated vendored Normal file
View File

@@ -0,0 +1,32 @@
try {
var vueVersion = require('vue').version
} catch (e) {}
var packageName = require('./package.json').name
var packageVersion = require('./package.json').version
if (vueVersion && vueVersion !== packageVersion) {
var vuePath = require.resolve('vue')
var packagePath = require.resolve('./package.json')
throw new Error(
'\n\nVue packages version mismatch:\n\n' +
'- vue@' +
vueVersion +
' (' +
vuePath +
')\n' +
'- ' +
packageName +
'@' +
packageVersion +
' (' +
packagePath +
')\n\n' +
'This may cause things to work incorrectly. Make sure to use the same version for both.\n' +
'If you are using vue-loader@>=10.0, simply update vue-template-compiler.\n' +
'If you are using vue-loader@<10.0 or vueify, re-installing vue-loader/vueify should bump ' +
packageName +
' to the latest.\n'
)
}
module.exports = require('./build')

35
node_modules/@vue/compiler-vue2/package.json generated vendored Normal file
View File

@@ -0,0 +1,35 @@
{
"name": "@vue/compiler-vue2",
"version": "2.7.16",
"description": "template compiler for Vue 2.x",
"main": "index.js",
"unpkg": "browser.js",
"jsdelivr": "browser.js",
"browser": "browser.js",
"types": "types/index.d.ts",
"files": [
"types/*.d.ts",
"*.js"
],
"repository": {
"type": "git",
"url": "git+https://github.com/vuejs/vue.git"
},
"keywords": [
"vue",
"compiler"
],
"author": "Evan You",
"license": "MIT",
"bugs": {
"url": "https://github.com/vuejs/vue/issues"
},
"homepage": "https://github.com/vuejs/vue/tree/dev/packages/vue-template-compiler#readme",
"dependencies": {
"de-indent": "^1.0.2",
"he": "^1.2.0"
},
"devDependencies": {
"vue": "file:../.."
}
}

247
node_modules/@vue/compiler-vue2/types/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,247 @@
import { VNode } from 'vue'
/*
* Template compilation options / results
*/
interface CompilerOptions {
modules?: ModuleOptions[]
directives?: Record<string, DirectiveFunction>
preserveWhitespace?: boolean
whitespace?: 'preserve' | 'condense'
outputSourceRange?: any
}
interface CompilerOptionsWithSourceRange extends CompilerOptions {
outputSourceRange: true
}
interface ErrorWithRange {
msg: string
start: number
end: number
}
interface CompiledResult<ErrorType> {
ast: ASTElement | undefined
render: string
staticRenderFns: string[]
errors: ErrorType[]
tips: ErrorType[]
}
interface CompiledResultFunctions {
render: () => VNode
staticRenderFns: (() => VNode)[]
}
interface ModuleOptions {
preTransformNode: (el: ASTElement) => ASTElement | undefined
transformNode: (el: ASTElement) => ASTElement | undefined
postTransformNode: (el: ASTElement) => void
genData: (el: ASTElement) => string
transformCode?: (el: ASTElement, code: string) => string
staticKeys?: string[]
}
type DirectiveFunction = (node: ASTElement, directiveMeta: ASTDirective) => void
/*
* AST Types
*/
/**
* - 0: FALSE - whole sub tree un-optimizable
* - 1: FULL - whole sub tree optimizable
* - 2: SELF - self optimizable but has some un-optimizable children
* - 3: CHILDREN - self un-optimizable but have fully optimizable children
* - 4: PARTIAL - self un-optimizable with some un-optimizable children
*/
export type SSROptimizability = 0 | 1 | 2 | 3 | 4
export interface ASTModifiers {
[key: string]: boolean
}
export interface ASTIfCondition {
exp: string | undefined
block: ASTElement
}
export interface ASTElementHandler {
value: string
params?: any[]
modifiers: ASTModifiers | undefined
}
export interface ASTElementHandlers {
[key: string]: ASTElementHandler | ASTElementHandler[]
}
export interface ASTDirective {
name: string
rawName: string
value: string
arg: string | undefined
modifiers: ASTModifiers | undefined
}
export type ASTNode = ASTElement | ASTText | ASTExpression
export interface ASTElement {
type: 1
tag: string
attrsList: { name: string; value: any }[]
attrsMap: Record<string, any>
parent: ASTElement | undefined
children: ASTNode[]
processed?: true
static?: boolean
staticRoot?: boolean
staticInFor?: boolean
staticProcessed?: boolean
hasBindings?: boolean
text?: string
attrs?: { name: string; value: any }[]
props?: { name: string; value: string }[]
plain?: boolean
pre?: true
ns?: string
component?: string
inlineTemplate?: true
transitionMode?: string | null
slotName?: string
slotTarget?: string
slotScope?: string
scopedSlots?: Record<string, ASTElement>
ref?: string
refInFor?: boolean
if?: string
ifProcessed?: boolean
elseif?: string
else?: true
ifConditions?: ASTIfCondition[]
for?: string
forProcessed?: boolean
key?: string
alias?: string
iterator1?: string
iterator2?: string
staticClass?: string
classBinding?: string
staticStyle?: string
styleBinding?: string
events?: ASTElementHandlers
nativeEvents?: ASTElementHandlers
transition?: string | true
transitionOnAppear?: boolean
model?: {
value: string
callback: string
expression: string
}
directives?: ASTDirective[]
forbidden?: true
once?: true
onceProcessed?: boolean
wrapData?: (code: string) => string
wrapListeners?: (code: string) => string
// 2.4 ssr optimization
ssrOptimizability?: SSROptimizability
}
export interface ASTExpression {
type: 2
expression: string
text: string
tokens: (string | Record<string, any>)[]
static?: boolean
// 2.4 ssr optimization
ssrOptimizability?: SSROptimizability
}
export interface ASTText {
type: 3
text: string
static?: boolean
isComment?: boolean
// 2.4 ssr optimization
ssrOptimizability?: SSROptimizability
}
/*
* SFC parser related types
*/
interface SFCParserOptions {
pad?: true | 'line' | 'space'
deindent?: boolean
}
export interface SFCBlock {
type: string
content: string
attrs: Record<string, string>
start?: number
end?: number
lang?: string
src?: string
scoped?: boolean
module?: string | boolean
}
export interface SFCDescriptor {
template: SFCBlock | undefined
script: SFCBlock | undefined
styles: SFCBlock[]
customBlocks: SFCBlock[]
}
/*
* Exposed functions
*/
export function compile(
template: string,
options: CompilerOptionsWithSourceRange
): CompiledResult<ErrorWithRange>
export function compile(
template: string,
options?: CompilerOptions
): CompiledResult<string>
export function compileToFunctions(template: string): CompiledResultFunctions
export function ssrCompile(
template: string,
options: CompilerOptionsWithSourceRange
): CompiledResult<ErrorWithRange>
export function ssrCompile(
template: string,
options?: CompilerOptions
): CompiledResult<string>
export function ssrCompileToFunctions(template: string): CompiledResultFunctions
export function parseComponent(
file: string,
options?: SFCParserOptions
): SFCDescriptor
export function generateCodeFrame(
template: string,
start: number,
end: number
): string

21
node_modules/@vue/language-core/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021-present Johnson Chu
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

13
node_modules/@vue/language-core/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,13 @@
export * from './lib/codegen/globalTypes';
export * from './lib/codegen/template';
export * from './lib/languagePlugin';
export * from './lib/parsers/scriptSetupRanges';
export * from './lib/plugins';
export * from './lib/types';
export * from './lib/utils/parseSfc';
export * from './lib/utils/ts';
export * from './lib/virtualFile/vueFile';
export { tsCodegen } from './lib/plugins/vue-tsx';
export * from './lib/utils/shared';
export * from '@volar/language-core';
export type * as CompilerDOM from '@vue/compiler-dom';

31
node_modules/@vue/language-core/index.js generated vendored Normal file
View File

@@ -0,0 +1,31 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.tsCodegen = void 0;
__exportStar(require("./lib/codegen/globalTypes"), exports);
__exportStar(require("./lib/codegen/template"), exports);
__exportStar(require("./lib/languagePlugin"), exports);
__exportStar(require("./lib/parsers/scriptSetupRanges"), exports);
__exportStar(require("./lib/plugins"), exports);
__exportStar(require("./lib/types"), exports);
__exportStar(require("./lib/utils/parseSfc"), exports);
__exportStar(require("./lib/utils/ts"), exports);
__exportStar(require("./lib/virtualFile/vueFile"), exports);
var vue_tsx_1 = require("./lib/plugins/vue-tsx");
Object.defineProperty(exports, "tsCodegen", { enumerable: true, get: function () { return vue_tsx_1.tsCodegen; } });
__exportStar(require("./lib/utils/shared"), exports);
__exportStar(require("@volar/language-core"), exports);
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1,83 @@
import type { VueCodeInformation } from '../types';
declare const raw: {
all: {
verification: true;
completion: true;
semantic: true;
navigation: true;
};
none: {};
verification: {
verification: true;
};
completion: {
completion: true;
};
additionalCompletion: {
completion: {
isAdditional: true;
};
};
withoutCompletion: {
verification: true;
semantic: true;
navigation: true;
};
navigation: {
navigation: true;
};
navigationWithoutRename: {
navigation: {
shouldRename: () => false;
};
};
navigationAndCompletion: {
navigation: true;
completion: true;
};
navigationAndAdditionalCompletion: {
navigation: true;
completion: {
isAdditional: true;
};
};
navigationAndVerification: {
navigation: true;
verification: true;
};
withoutNavigation: {
verification: true;
completion: true;
semantic: true;
};
withoutHighlight: {
semantic: {
shouldHighlight: () => false;
};
verification: true;
navigation: true;
completion: true;
};
withoutHighlightAndNavigation: {
semantic: {
shouldHighlight: () => false;
};
verification: true;
completion: true;
};
withoutHighlightAndCompletion: {
semantic: {
shouldHighlight: () => false;
};
verification: true;
navigation: true;
};
withoutHighlightAndCompletionAndNavigation: {
semantic: {
shouldHighlight: () => false;
};
verification: true;
};
};
export declare const codeFeatures: { [K in keyof typeof raw]: VueCodeInformation; };
export {};

View File

@@ -0,0 +1,71 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.codeFeatures = void 0;
const raw = {
all: {
verification: true,
completion: true,
semantic: true,
navigation: true,
},
none: {},
verification: {
verification: true,
},
completion: {
completion: true,
},
additionalCompletion: {
completion: { isAdditional: true },
},
withoutCompletion: {
verification: true,
semantic: true,
navigation: true,
},
navigation: {
navigation: true,
},
navigationWithoutRename: {
navigation: { shouldRename: () => false },
},
navigationAndCompletion: {
navigation: true,
completion: true,
},
navigationAndAdditionalCompletion: {
navigation: true,
completion: { isAdditional: true },
},
navigationAndVerification: {
navigation: true,
verification: true,
},
withoutNavigation: {
verification: true,
completion: true,
semantic: true,
},
withoutHighlight: {
semantic: { shouldHighlight: () => false },
verification: true,
navigation: true,
completion: true,
},
withoutHighlightAndNavigation: {
semantic: { shouldHighlight: () => false },
verification: true,
completion: true,
},
withoutHighlightAndCompletion: {
semantic: { shouldHighlight: () => false },
verification: true,
navigation: true,
},
withoutHighlightAndCompletionAndNavigation: {
semantic: { shouldHighlight: () => false },
verification: true,
},
};
exports.codeFeatures = raw;
//# sourceMappingURL=codeFeatures.js.map

View File

@@ -0,0 +1,3 @@
import type { VueCompilerOptions } from '../types';
export declare function getGlobalTypesFileName({ lib, target, checkUnknownProps, checkUnknownEvents, checkUnknownComponents, }: VueCompilerOptions): string;
export declare function generateGlobalTypes({ lib, target, checkUnknownProps, checkUnknownEvents, checkUnknownComponents, }: VueCompilerOptions): string;

View File

@@ -0,0 +1,151 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getGlobalTypesFileName = getGlobalTypesFileName;
exports.generateGlobalTypes = generateGlobalTypes;
const shared_1 = require("../utils/shared");
function getGlobalTypesFileName({ lib, target, checkUnknownProps, checkUnknownEvents, checkUnknownComponents, }) {
return [
lib,
target,
checkUnknownProps,
checkUnknownEvents,
checkUnknownComponents,
].map(v => (typeof v === 'boolean' ? Number(v) : v)).join('_') + '.d.ts';
}
function generateGlobalTypes({ lib, target, checkUnknownProps, checkUnknownEvents, checkUnknownComponents, }) {
const fnPropsType = `(K extends { $props: infer Props } ? Props : any)${checkUnknownProps ? '' : ' & Record<string, unknown>'}`;
let text = ``;
if (target < 3.5) {
text += `
; declare module '${lib}' {
export interface GlobalComponents { }
export interface GlobalDirectives { }
}`;
}
text += `
; declare global {
const __VLS_intrinsicElements: __VLS_IntrinsicElements;
const __VLS_directiveBindingRestFields: { instance: null, oldValue: null, modifiers: any, dir: any };
const __VLS_unref: typeof import('${lib}').unref;
const __VLS_placeholder: any;
type __VLS_NativeElements = __VLS_SpreadMerge<SVGElementTagNameMap, HTMLElementTagNameMap>;
type __VLS_IntrinsicElements = ${(target >= 3.3
? `import('${lib}/jsx-runtime').JSX.IntrinsicElements;`
: `globalThis.JSX.IntrinsicElements;`)}
type __VLS_Element = ${(target >= 3.3
? `import('${lib}/jsx-runtime').JSX.Element;`
: `globalThis.JSX.Element;`)}
type __VLS_GlobalComponents = ${(target >= 3.5
? `import('${lib}').GlobalComponents;`
: `import('${lib}').GlobalComponents & Pick<typeof import('${lib}'), 'Transition' | 'TransitionGroup' | 'KeepAlive' | 'Suspense' | 'Teleport'>;`)}
type __VLS_GlobalDirectives = import('${lib}').GlobalDirectives;
type __VLS_IsAny<T> = 0 extends 1 & T ? true : false;
type __VLS_PickNotAny<A, B> = __VLS_IsAny<A> extends true ? B : A;
type __VLS_SpreadMerge<A, B> = Omit<A, keyof B> & B;
type __VLS_WithComponent<N0 extends string, LocalComponents, Self, N1 extends string, N2 extends string, N3 extends string> =
N1 extends keyof LocalComponents ? N1 extends N0 ? Pick<LocalComponents, N0 extends keyof LocalComponents ? N0 : never> : { [K in N0]: LocalComponents[N1] } :
N2 extends keyof LocalComponents ? N2 extends N0 ? Pick<LocalComponents, N0 extends keyof LocalComponents ? N0 : never> : { [K in N0]: LocalComponents[N2] } :
N3 extends keyof LocalComponents ? N3 extends N0 ? Pick<LocalComponents, N0 extends keyof LocalComponents ? N0 : never> : { [K in N0]: LocalComponents[N3] } :
Self extends object ? { [K in N0]: Self } :
N1 extends keyof __VLS_GlobalComponents ? N1 extends N0 ? Pick<__VLS_GlobalComponents, N0 extends keyof __VLS_GlobalComponents ? N0 : never> : { [K in N0]: __VLS_GlobalComponents[N1] } :
N2 extends keyof __VLS_GlobalComponents ? N2 extends N0 ? Pick<__VLS_GlobalComponents, N0 extends keyof __VLS_GlobalComponents ? N0 : never> : { [K in N0]: __VLS_GlobalComponents[N2] } :
N3 extends keyof __VLS_GlobalComponents ? N3 extends N0 ? Pick<__VLS_GlobalComponents, N0 extends keyof __VLS_GlobalComponents ? N0 : never> : { [K in N0]: __VLS_GlobalComponents[N3] } :
${checkUnknownComponents ? '{}' : '{ [K in N0]: unknown }'};
type __VLS_FunctionalComponentProps<T, K> =
'__ctx' extends keyof __VLS_PickNotAny<K, {}> ? K extends { __ctx?: { props?: infer P } } ? NonNullable<P> : never
: T extends (props: infer P, ...args: any) => any ? P :
{};
type __VLS_IsFunction<T, K> = K extends keyof T
? __VLS_IsAny<T[K]> extends false
? unknown extends T[K]
? false
: true
: false
: false;
type __VLS_NormalizeComponentEvent<Props, Events, onEvent extends keyof Props, Event extends keyof Events, CamelizedEvent extends keyof Events> = (
__VLS_IsFunction<Props, onEvent> extends true
? Props
: __VLS_IsFunction<Events, Event> extends true
? { [K in onEvent]?: Events[Event] }
: __VLS_IsFunction<Events, CamelizedEvent> extends true
? { [K in onEvent]?: Events[CamelizedEvent] }
: Props
)${checkUnknownEvents ? '' : ' & Record<string, unknown>'};
// fix https://github.com/vuejs/language-tools/issues/926
type __VLS_UnionToIntersection<U> = (U extends unknown ? (arg: U) => unknown : never) extends ((arg: infer P) => unknown) ? P : never;
type __VLS_OverloadUnionInner<T, U = unknown> = U & T extends (...args: infer A) => infer R
? U extends T
? never
: __VLS_OverloadUnionInner<T, Pick<T, keyof T> & U & ((...args: A) => R)> | ((...args: A) => R)
: never;
type __VLS_OverloadUnion<T> = Exclude<
__VLS_OverloadUnionInner<(() => never) & T>,
T extends () => never ? never : () => never
>;
type __VLS_ConstructorOverloads<T> = __VLS_OverloadUnion<T> extends infer F
? F extends (event: infer E, ...args: infer A) => any
? { [K in E & string]: (...args: A) => void; }
: never
: never;
type __VLS_NormalizeEmits<T> = __VLS_PrettifyGlobal<
__VLS_UnionToIntersection<
__VLS_ConstructorOverloads<T> & {
[K in keyof T]: T[K] extends any[] ? { (...args: T[K]): void } : never
}
>
>;
type __VLS_PrettifyGlobal<T> = { [K in keyof T]: T[K]; } & {};
type __VLS_PickFunctionalComponentCtx<T, K> = NonNullable<__VLS_PickNotAny<
'__ctx' extends keyof __VLS_PickNotAny<K, {}> ? K extends { __ctx?: infer Ctx } ? Ctx : never : any
, T extends (props: any, ctx: infer Ctx) => any ? Ctx : any
>>;
type __VLS_UseTemplateRef<T> = Readonly<import('${lib}').ShallowRef<T | null>>;
function __VLS_getVForSourceType<T extends number | string | any[] | Iterable<any>>(source: T): [
item: T extends number ? number
: T extends string ? string
: T extends any[] ? T[number]
: T extends Iterable<infer T1> ? T1
: any,
index: number,
][];
function __VLS_getVForSourceType<T>(source: T): [
item: T[keyof T],
key: keyof T,
index: number,
][];
// @ts-ignore
function __VLS_getSlotParams<T>(slot: T): Parameters<__VLS_PickNotAny<NonNullable<T>, (...args: any[]) => any>>;
// @ts-ignore
function __VLS_getSlotParam<T>(slot: T): Parameters<__VLS_PickNotAny<NonNullable<T>, (...args: any[]) => any>>[0];
function __VLS_asFunctionalDirective<T>(dir: T): T extends import('${lib}').ObjectDirective
? NonNullable<T['created' | 'beforeMount' | 'mounted' | 'beforeUpdate' | 'updated' | 'beforeUnmount' | 'unmounted']>
: T extends (...args: any) => any
? T
: (arg1: unknown, arg2: unknown, arg3: unknown, arg4: unknown) => void;
function __VLS_makeOptional<T>(t: T): { [K in keyof T]?: T[K] };
function __VLS_asFunctionalComponent<T, K = T extends new (...args: any) => any ? InstanceType<T> : unknown>(t: T, instance?: K):
T extends new (...args: any) => any
? (props: ${fnPropsType}, ctx?: any) => __VLS_Element & {
__ctx?: {
attrs?: any;
slots?: K extends { ${(0, shared_1.getSlotsPropertyName)(target)}: infer Slots } ? Slots : any;
emit?: K extends { $emit: infer Emit } ? Emit : any;
expose?(exposed: K): void;
props?: ${fnPropsType};
}
}
: T extends () => any ? (props: {}, ctx?: any) => ReturnType<T>
: T extends (...args: any) => any ? T
: (_: {}${checkUnknownProps ? '' : ' & Record<string, unknown>'}, ctx?: any) => { __ctx?: { attrs?: any, expose?: any, slots?: any, emit?: any, props?: {}${checkUnknownProps ? '' : ' & Record<string, unknown>'} } };
function __VLS_functionalComponentArgsRest<T extends (...args: any) => any>(t: T): 2 extends Parameters<T>['length'] ? [any] : [];
function __VLS_asFunctionalElement<T>(tag: T, endTag?: T): (attrs: T${checkUnknownComponents ? '' : ' & Record<string, unknown>'}) => void;
function __VLS_asFunctionalSlot<S>(slot: S): S extends () => infer R ? (props: {}) => R : NonNullable<S>;
function __VLS_tryAsConstant<const T>(t: T): T;
}
`;
return text;
}
;
//# sourceMappingURL=globalTypes.js.map

View File

@@ -0,0 +1,11 @@
import type * as CompilerDOM from '@vue/compiler-dom';
export interface InlayHintInfo {
blockName: string;
offset: number;
setting: string;
label: string;
tooltip?: string;
paddingRight?: boolean;
paddingLeft?: boolean;
}
export declare function createVBindShorthandInlayHintInfo(loc: CompilerDOM.SourceLocation, variableName: string): InlayHintInfo;

View File

@@ -0,0 +1,17 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createVBindShorthandInlayHintInfo = createVBindShorthandInlayHintInfo;
function createVBindShorthandInlayHintInfo(loc, variableName) {
return {
blockName: 'template',
offset: loc.end.offset,
setting: 'vue.inlayHints.vBindShorthand',
label: `="${variableName}"`,
tooltip: [
`This is a shorthand for \`${loc.source}="${variableName}"\`.`,
'To hide this hint, set `vue.inlayHints.vBindShorthand` to `false` in IDE settings.',
'[More info](https://github.com/vuejs/core/pull/9451)',
].join('\n\n'),
};
}
//# sourceMappingURL=inlayHints.js.map

View File

@@ -0,0 +1,13 @@
import type * as ts from 'typescript';
import { VueCompilerOptions } from '../types';
export declare function getLocalTypesGenerator(compilerOptions: ts.CompilerOptions, vueCompilerOptions: VueCompilerOptions): {
generate: (names: string[]) => Generator<string, void, unknown>;
getUsedNames(): Set<string>;
readonly PrettifyLocal: string;
readonly OmitKeepDiscriminatedUnion: string;
readonly WithDefaults: string;
readonly WithSlots: string;
readonly PropsChildren: string;
readonly TypePropsToOption: string;
readonly OmitIndexSignature: string;
};

View File

@@ -0,0 +1,109 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getLocalTypesGenerator = getLocalTypesGenerator;
const shared_1 = require("../utils/shared");
const utils_1 = require("./utils");
function getLocalTypesGenerator(compilerOptions, vueCompilerOptions) {
const used = new Set();
const OmitKeepDiscriminatedUnion = defineHelper(`__VLS_OmitKeepDiscriminatedUnion`, () => `
type __VLS_OmitKeepDiscriminatedUnion<T, K extends keyof any> = T extends any
? Pick<T, Exclude<keyof T, K>>
: never;
`.trimStart());
const WithDefaults = defineHelper(`__VLS_WithDefaults`, () => `
type __VLS_WithDefaults<P, D> = {
[K in keyof Pick<P, keyof P>]: K extends keyof D
? ${PrettifyLocal.name}<P[K] & { default: D[K]}>
: P[K]
};
`.trimStart());
const PrettifyLocal = defineHelper(`__VLS_PrettifyLocal`, () => `type __VLS_PrettifyLocal<T> = { [K in keyof T]: T[K]; } & {}${utils_1.endOfLine}`);
const WithSlots = defineHelper(`__VLS_WithSlots`, () => `
type __VLS_WithSlots<T, S> = T & {
new(): {
${(0, shared_1.getSlotsPropertyName)(vueCompilerOptions.target)}: S;
${vueCompilerOptions.jsxSlots ? `$props: ${PropsChildren.name}<S>;` : ''}
}
};
`.trimStart());
const PropsChildren = defineHelper(`__VLS_PropsChildren`, () => `
type __VLS_PropsChildren<S> = {
[K in keyof (
boolean extends (
// @ts-ignore
JSX.ElementChildrenAttribute extends never
? true
: false
)
? never
// @ts-ignore
: JSX.ElementChildrenAttribute
)]?: S;
};
`.trimStart());
const TypePropsToOption = defineHelper(`__VLS_TypePropsToOption`, () => compilerOptions.exactOptionalPropertyTypes ?
`
type __VLS_TypePropsToOption<T> = {
[K in keyof T]-?: {} extends Pick<T, K>
? { type: import('${vueCompilerOptions.lib}').PropType<T[K]> }
: { type: import('${vueCompilerOptions.lib}').PropType<T[K]>, required: true }
};
`.trimStart() :
`
type __VLS_NonUndefinedable<T> = T extends undefined ? never : T;
type __VLS_TypePropsToOption<T> = {
[K in keyof T]-?: {} extends Pick<T, K>
? { type: import('${vueCompilerOptions.lib}').PropType<__VLS_NonUndefinedable<T[K]>> }
: { type: import('${vueCompilerOptions.lib}').PropType<T[K]>, required: true }
};
`.trimStart());
const OmitIndexSignature = defineHelper(`__VLS_OmitIndexSignature`, () => `type __VLS_OmitIndexSignature<T> = { [K in keyof T as {} extends Record<K, unknown> ? never : K]: T[K]; }${utils_1.endOfLine}`);
const helpers = {
[PrettifyLocal.name]: PrettifyLocal,
[OmitKeepDiscriminatedUnion.name]: OmitKeepDiscriminatedUnion,
[WithDefaults.name]: WithDefaults,
[WithSlots.name]: WithSlots,
[PropsChildren.name]: PropsChildren,
[TypePropsToOption.name]: TypePropsToOption,
[OmitIndexSignature.name]: OmitIndexSignature,
};
used.clear();
return {
generate,
getUsedNames() {
return used;
},
get PrettifyLocal() { return PrettifyLocal.name; },
get OmitKeepDiscriminatedUnion() { return OmitKeepDiscriminatedUnion.name; },
get WithDefaults() { return WithDefaults.name; },
get WithSlots() { return WithSlots.name; },
get PropsChildren() { return PropsChildren.name; },
get TypePropsToOption() { return TypePropsToOption.name; },
get OmitIndexSignature() { return OmitIndexSignature.name; },
};
function* generate(names) {
const generated = new Set();
while (names.length) {
used.clear();
for (const name of names) {
if (generated.has(name)) {
continue;
}
const helper = helpers[name];
yield helper.generate();
generated.add(name);
}
names = [...used].filter(name => !generated.has(name));
}
}
function defineHelper(name, generate) {
return {
get name() {
used.add(name);
return name;
},
generate,
};
}
}
//# sourceMappingURL=localTypes.js.map

View File

@@ -0,0 +1,8 @@
import type { ScriptSetupRanges } from '../../parsers/scriptSetupRanges';
import type { Code, Sfc } from '../../types';
import type { ScriptCodegenContext } from './context';
import type { ScriptCodegenOptions } from './index';
export declare function generateComponent(options: ScriptCodegenOptions, ctx: ScriptCodegenContext, scriptSetup: NonNullable<Sfc['scriptSetup']>, scriptSetupRanges: ScriptSetupRanges): Generator<Code>;
export declare function generateComponentSetupReturns(scriptSetupRanges: ScriptSetupRanges): Generator<Code>;
export declare function generateEmitsOption(options: ScriptCodegenOptions, scriptSetupRanges: ScriptSetupRanges): Generator<Code>;
export declare function generatePropsOption(options: ScriptCodegenOptions, ctx: ScriptCodegenContext, scriptSetup: NonNullable<Sfc['scriptSetup']>, scriptSetupRanges: ScriptSetupRanges, hasEmitsOption: boolean, inheritAttrs: boolean): Generator<Code>;

View File

@@ -0,0 +1,181 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateComponent = generateComponent;
exports.generateComponentSetupReturns = generateComponentSetupReturns;
exports.generateEmitsOption = generateEmitsOption;
exports.generatePropsOption = generatePropsOption;
const codeFeatures_1 = require("../codeFeatures");
const utils_1 = require("../utils");
function* generateComponent(options, ctx, scriptSetup, scriptSetupRanges) {
if (options.sfc.script && options.scriptRanges?.exportDefault && options.scriptRanges.exportDefault.expression.start !== options.scriptRanges.exportDefault.args.start) {
// use defineComponent() from user space code if it exist
yield (0, utils_1.generateSfcBlockSection)(options.sfc.script, options.scriptRanges.exportDefault.expression.start, options.scriptRanges.exportDefault.args.start, codeFeatures_1.codeFeatures.all);
yield `{${utils_1.newLine}`;
}
else {
yield `(await import('${options.vueCompilerOptions.lib}')).defineComponent({${utils_1.newLine}`;
}
yield `setup() {${utils_1.newLine}`;
yield `return {${utils_1.newLine}`;
if (ctx.bypassDefineComponent) {
yield* generateComponentSetupReturns(scriptSetupRanges);
}
if (scriptSetupRanges.defineExpose) {
yield `...__VLS_exposed,${utils_1.newLine}`;
}
yield `}${utils_1.endOfLine}`;
yield `},${utils_1.newLine}`;
if (!ctx.bypassDefineComponent) {
const emitOptionCodes = [...generateEmitsOption(options, scriptSetupRanges)];
yield* emitOptionCodes;
yield* generatePropsOption(options, ctx, scriptSetup, scriptSetupRanges, !!emitOptionCodes.length, true);
}
if (options.vueCompilerOptions.target >= 3.5
&& options.vueCompilerOptions.inferComponentDollarRefs
&& options.templateCodegen?.templateRefs.size) {
yield `__typeRefs: {} as __VLS_TemplateRefs,${utils_1.newLine}`;
}
if (options.vueCompilerOptions.target >= 3.5
&& options.vueCompilerOptions.inferComponentDollarEl
&& options.templateCodegen?.singleRootElTypes.length) {
yield `__typeEl: {} as __VLS_RootEl,${utils_1.newLine}`;
}
if (options.sfc.script && options.scriptRanges?.exportDefault?.args) {
const { args } = options.scriptRanges.exportDefault;
yield (0, utils_1.generateSfcBlockSection)(options.sfc.script, args.start + 1, args.end - 1, codeFeatures_1.codeFeatures.all);
}
yield `})`;
}
function* generateComponentSetupReturns(scriptSetupRanges) {
// fill $props
if (scriptSetupRanges.defineProps) {
// NOTE: defineProps is inaccurate for $props
yield `$props: __VLS_makeOptional(${scriptSetupRanges.defineProps.name ?? `__VLS_props`}),${utils_1.newLine}`;
yield `...${scriptSetupRanges.defineProps.name ?? `__VLS_props`},${utils_1.newLine}`;
}
// fill $emit
if (scriptSetupRanges.defineEmits) {
yield `$emit: ${scriptSetupRanges.defineEmits.name ?? '__VLS_emit'},${utils_1.newLine}`;
}
}
function* generateEmitsOption(options, scriptSetupRanges) {
const codes = [];
if (scriptSetupRanges.defineProp.some(p => p.isModel)) {
codes.push({
optionExp: `{} as __VLS_NormalizeEmits<typeof __VLS_modelEmit>`,
typeOptionType: `__VLS_ModelEmit`,
});
}
if (scriptSetupRanges.defineEmits) {
const { name, typeArg, hasUnionTypeArg } = scriptSetupRanges.defineEmits;
codes.push({
optionExp: `{} as __VLS_NormalizeEmits<typeof ${name ?? '__VLS_emit'}>`,
typeOptionType: typeArg && !hasUnionTypeArg
? `__VLS_Emit`
: undefined,
});
}
if (options.vueCompilerOptions.target >= 3.5 && codes.every(code => code.typeOptionType)) {
if (codes.length === 1) {
yield `__typeEmits: {} as `;
yield codes[0].typeOptionType;
yield `,${utils_1.newLine}`;
}
else if (codes.length >= 2) {
yield `__typeEmits: {} as `;
yield codes[0].typeOptionType;
for (let i = 1; i < codes.length; i++) {
yield ` & `;
yield codes[i].typeOptionType;
}
yield `,${utils_1.newLine}`;
}
}
else if (codes.every(code => code.optionExp)) {
if (codes.length === 1) {
yield `emits: `;
yield codes[0].optionExp;
yield `,${utils_1.newLine}`;
}
else if (codes.length >= 2) {
yield `emits: {${utils_1.newLine}`;
for (const code of codes) {
yield `...`;
yield code.optionExp;
yield `,${utils_1.newLine}`;
}
yield `},${utils_1.newLine}`;
}
}
}
function* generatePropsOption(options, ctx, scriptSetup, scriptSetupRanges, hasEmitsOption, inheritAttrs) {
const codes = [];
if (ctx.generatedPropsType) {
codes.push({
optionExp: [
`{} as `,
scriptSetupRanges.withDefaults?.arg ? `${ctx.localTypes.WithDefaults}<` : '',
`${ctx.localTypes.TypePropsToOption}<__VLS_PublicProps>`,
scriptSetupRanges.withDefaults?.arg ? `, typeof __VLS_withDefaultsArg>` : '',
].join(''),
typeOptionExp: `{} as __VLS_PublicProps`,
});
}
if (scriptSetupRanges.defineProps?.arg) {
const { arg } = scriptSetupRanges.defineProps;
codes.push({
optionExp: (0, utils_1.generateSfcBlockSection)(scriptSetup, arg.start, arg.end, codeFeatures_1.codeFeatures.navigation),
typeOptionExp: undefined,
});
}
if (inheritAttrs && options.templateCodegen?.inheritedAttrVars.size) {
let attrsType = `Partial<__VLS_InheritedAttrs>`;
if (hasEmitsOption) {
attrsType = `Omit<${attrsType}, \`on\${string}\`>`;
}
const propsType = `__VLS_PickNotAny<${ctx.localTypes.OmitIndexSignature}<${attrsType}>, {}>`;
const optionType = `${ctx.localTypes.TypePropsToOption}<${propsType}>`;
codes.unshift({
optionExp: codes.length
? `{} as ${optionType}`
// workaround for https://github.com/vuejs/core/pull/7419
: `{} as keyof ${propsType} extends never ? never: ${optionType}`,
typeOptionExp: `{} as ${attrsType}`,
});
}
const useTypeOption = options.vueCompilerOptions.target >= 3.5 && codes.every(code => code.typeOptionExp);
const useOption = !useTypeOption || scriptSetupRanges.withDefaults;
if (useTypeOption) {
if (codes.length === 1) {
yield `__typeProps: `;
yield codes[0].typeOptionExp;
yield `,${utils_1.newLine}`;
}
else if (codes.length >= 2) {
yield `__typeProps: {${utils_1.newLine}`;
for (const { typeOptionExp } of codes) {
yield `...`;
yield typeOptionExp;
yield `,${utils_1.newLine}`;
}
yield `},${utils_1.newLine}`;
}
}
if (useOption) {
if (codes.length === 1) {
yield `props: `;
yield codes[0].optionExp;
yield `,${utils_1.newLine}`;
}
else if (codes.length >= 2) {
yield `props: {${utils_1.newLine}`;
for (const { optionExp } of codes) {
yield `...`;
yield optionExp;
yield `,${utils_1.newLine}`;
}
yield `},${utils_1.newLine}`;
}
}
}
//# sourceMappingURL=component.js.map

View File

@@ -0,0 +1,5 @@
import type { Code } from '../../types';
import type { TemplateCodegenContext } from '../template/context';
import type { ScriptCodegenContext } from './context';
import type { ScriptCodegenOptions } from './index';
export declare function generateComponentSelf(options: ScriptCodegenOptions, ctx: ScriptCodegenContext, templateCodegenCtx: TemplateCodegenContext): Generator<Code>;

View File

@@ -0,0 +1,57 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateComponentSelf = generateComponentSelf;
const path = require("path-browserify");
const codeFeatures_1 = require("../codeFeatures");
const utils_1 = require("../utils");
const component_1 = require("./component");
const template_1 = require("./template");
function* generateComponentSelf(options, ctx, templateCodegenCtx) {
if (options.sfc.scriptSetup && options.scriptSetupRanges) {
yield `const __VLS_self = (await import('${options.vueCompilerOptions.lib}')).defineComponent({${utils_1.newLine}`;
yield `setup() {${utils_1.newLine}`;
yield `return {${utils_1.newLine}`;
if (ctx.bypassDefineComponent) {
yield* (0, component_1.generateComponentSetupReturns)(options.scriptSetupRanges);
}
// bindings
const templateUsageVars = (0, template_1.getTemplateUsageVars)(options, ctx);
for (const [content, bindings] of [
[options.sfc.scriptSetup.content, options.scriptSetupRanges.bindings],
options.sfc.script && options.scriptRanges
? [options.sfc.script.content, options.scriptRanges.bindings]
: ['', []],
]) {
for (const { range } of bindings) {
const varName = content.slice(range.start, range.end);
if (!templateUsageVars.has(varName) && !templateCodegenCtx.accessExternalVariables.has(varName)) {
continue;
}
const token = Symbol(varName.length);
yield ['', undefined, 0, { __linkedToken: token }];
yield `${varName}: ${varName} as typeof `;
yield ['', undefined, 0, { __linkedToken: token }];
yield `${varName},${utils_1.newLine}`;
}
}
yield `}${utils_1.endOfLine}`; // return {
yield `},${utils_1.newLine}`; // setup() {
if (options.sfc.scriptSetup && options.scriptSetupRanges && !ctx.bypassDefineComponent) {
const emitOptionCodes = [...(0, component_1.generateEmitsOption)(options, options.scriptSetupRanges)];
yield* emitOptionCodes;
yield* (0, component_1.generatePropsOption)(options, ctx, options.sfc.scriptSetup, options.scriptSetupRanges, !!emitOptionCodes.length, false);
}
if (options.sfc.script && options.scriptRanges?.exportDefault?.args) {
const { args } = options.scriptRanges.exportDefault;
yield (0, utils_1.generateSfcBlockSection)(options.sfc.script, args.start + 1, args.end - 1, codeFeatures_1.codeFeatures.all);
}
yield `})${utils_1.endOfLine}`; // defineComponent {
}
else if (options.sfc.script) {
yield `let __VLS_self!: typeof import('./${path.basename(options.fileName)}').default${utils_1.endOfLine}`;
}
else {
yield `const __VLS_self = (await import('${options.vueCompilerOptions.lib}')).defineComponent({})${utils_1.endOfLine}`;
}
}
//# sourceMappingURL=componentSelf.js.map

View File

@@ -0,0 +1,27 @@
import { InlayHintInfo } from '../inlayHints';
import type { ScriptCodegenOptions } from './index';
export interface HelperType {
name: string;
used?: boolean;
generated?: boolean;
code: string;
}
export type ScriptCodegenContext = ReturnType<typeof createScriptCodegenContext>;
export declare function createScriptCodegenContext(options: ScriptCodegenOptions): {
generatedTemplate: boolean;
generatedPropsType: boolean;
bypassDefineComponent: boolean;
bindingNames: Set<string>;
localTypes: {
generate: (names: string[]) => Generator<string, void, unknown>;
getUsedNames(): Set<string>;
readonly PrettifyLocal: string;
readonly OmitKeepDiscriminatedUnion: string;
readonly WithDefaults: string;
readonly WithSlots: string;
readonly PropsChildren: string;
readonly TypePropsToOption: string;
readonly OmitIndexSignature: string;
};
inlayHints: InlayHintInfo[];
};

View File

@@ -0,0 +1,20 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createScriptCodegenContext = createScriptCodegenContext;
const localTypes_1 = require("../localTypes");
function createScriptCodegenContext(options) {
const localTypes = (0, localTypes_1.getLocalTypesGenerator)(options.compilerOptions, options.vueCompilerOptions);
const inlayHints = [];
return {
generatedTemplate: false,
generatedPropsType: false,
bypassDefineComponent: options.lang === 'js' || options.lang === 'jsx',
bindingNames: new Set([
...options.scriptRanges?.bindings.map(({ range }) => options.sfc.script.content.slice(range.start, range.end)) ?? [],
...options.scriptSetupRanges?.bindings.map(({ range }) => options.sfc.scriptSetup.content.slice(range.start, range.end)) ?? [],
]),
localTypes,
inlayHints,
};
}
//# sourceMappingURL=context.js.map

View File

@@ -0,0 +1,25 @@
import type * as ts from 'typescript';
import type { ScriptRanges } from '../../parsers/scriptRanges';
import type { ScriptSetupRanges } from '../../parsers/scriptSetupRanges';
import type { Code, Sfc, VueCompilerOptions } from '../../types';
import type { TemplateCodegenContext } from '../template/context';
import { ScriptCodegenContext } from './context';
export interface ScriptCodegenOptions {
ts: typeof ts;
compilerOptions: ts.CompilerOptions;
vueCompilerOptions: VueCompilerOptions;
sfc: Sfc;
edited: boolean;
fileName: string;
lang: string;
scriptRanges: ScriptRanges | undefined;
scriptSetupRanges: ScriptSetupRanges | undefined;
templateCodegen: TemplateCodegenContext & {
codes: Code[];
} | undefined;
destructuredPropNames: Set<string>;
templateRefNames: Set<string>;
appendGlobalTypes: boolean;
}
export declare function generateScript(options: ScriptCodegenOptions): Generator<Code, ScriptCodegenContext>;
export declare function generateScriptSectionPartiallyEnding(source: string, end: number, mark: string, delimiter?: string): Generator<Code>;

View File

@@ -0,0 +1,125 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateScript = generateScript;
exports.generateScriptSectionPartiallyEnding = generateScriptSectionPartiallyEnding;
const path = require("path-browserify");
const codeFeatures_1 = require("../codeFeatures");
const globalTypes_1 = require("../globalTypes");
const utils_1 = require("../utils");
const componentSelf_1 = require("./componentSelf");
const context_1 = require("./context");
const scriptSetup_1 = require("./scriptSetup");
const src_1 = require("./src");
const template_1 = require("./template");
function* generateScript(options) {
const ctx = (0, context_1.createScriptCodegenContext)(options);
if (options.vueCompilerOptions.__setupedGlobalTypes) {
const globalTypes = options.vueCompilerOptions.__setupedGlobalTypes;
if (typeof globalTypes === 'object') {
let relativePath = path.relative(path.dirname(options.fileName), globalTypes.absolutePath);
if (relativePath !== globalTypes.absolutePath && !relativePath.startsWith('./') && !relativePath.startsWith('../')) {
relativePath = './' + relativePath;
}
yield `/// <reference types="${relativePath}" />${utils_1.newLine}`;
}
else {
yield `/// <reference types=".vue-global-types/${(0, globalTypes_1.getGlobalTypesFileName)(options.vueCompilerOptions)}" />${utils_1.newLine}`;
}
}
else {
yield `/* placeholder */`;
}
if (options.sfc.script?.src) {
yield* (0, src_1.generateSrc)(options.sfc.script.src);
}
if (options.sfc.scriptSetup && options.scriptSetupRanges) {
yield* (0, scriptSetup_1.generateScriptSetupImports)(options.sfc.scriptSetup, options.scriptSetupRanges);
}
if (options.sfc.script && options.scriptRanges) {
const { exportDefault, classBlockEnd } = options.scriptRanges;
const isExportRawObject = exportDefault
&& options.sfc.script.content[exportDefault.expression.start] === '{';
if (options.sfc.scriptSetup && options.scriptSetupRanges) {
if (exportDefault) {
yield (0, utils_1.generateSfcBlockSection)(options.sfc.script, 0, exportDefault.expression.start, codeFeatures_1.codeFeatures.all);
yield* (0, scriptSetup_1.generateScriptSetup)(options, ctx, options.sfc.scriptSetup, options.scriptSetupRanges);
yield (0, utils_1.generateSfcBlockSection)(options.sfc.script, exportDefault.expression.end, options.sfc.script.content.length, codeFeatures_1.codeFeatures.all);
}
else {
yield (0, utils_1.generateSfcBlockSection)(options.sfc.script, 0, options.sfc.script.content.length, codeFeatures_1.codeFeatures.all);
yield* generateScriptSectionPartiallyEnding(options.sfc.script.name, options.sfc.script.content.length, '#3632/both.vue');
yield* (0, scriptSetup_1.generateScriptSetup)(options, ctx, options.sfc.scriptSetup, options.scriptSetupRanges);
}
}
else if (exportDefault && isExportRawObject && options.vueCompilerOptions.optionsWrapper.length) {
ctx.inlayHints.push({
blockName: options.sfc.script.name,
offset: exportDefault.expression.start,
setting: 'vue.inlayHints.optionsWrapper',
label: options.vueCompilerOptions.optionsWrapper.length
? options.vueCompilerOptions.optionsWrapper[0]
: '[Missing optionsWrapper[0]]',
tooltip: [
'This is virtual code that is automatically wrapped for type support, it does not affect your runtime behavior, you can customize it via `vueCompilerOptions.optionsWrapper` option in tsconfig / jsconfig.',
'To hide it, you can set `"vue.inlayHints.optionsWrapper": false` in IDE settings.',
].join('\n\n'),
}, {
blockName: options.sfc.script.name,
offset: exportDefault.expression.end,
setting: 'vue.inlayHints.optionsWrapper',
label: options.vueCompilerOptions.optionsWrapper.length >= 2
? options.vueCompilerOptions.optionsWrapper[1]
: '[Missing optionsWrapper[1]]',
});
yield (0, utils_1.generateSfcBlockSection)(options.sfc.script, 0, exportDefault.expression.start, codeFeatures_1.codeFeatures.all);
yield options.vueCompilerOptions.optionsWrapper[0];
yield (0, utils_1.generateSfcBlockSection)(options.sfc.script, exportDefault.expression.start, exportDefault.expression.end, codeFeatures_1.codeFeatures.all);
yield options.vueCompilerOptions.optionsWrapper[1];
yield (0, utils_1.generateSfcBlockSection)(options.sfc.script, exportDefault.expression.end, options.sfc.script.content.length, codeFeatures_1.codeFeatures.all);
}
else if (classBlockEnd !== undefined) {
if (options.vueCompilerOptions.skipTemplateCodegen) {
yield (0, utils_1.generateSfcBlockSection)(options.sfc.script, 0, options.sfc.script.content.length, codeFeatures_1.codeFeatures.all);
}
else {
yield (0, utils_1.generateSfcBlockSection)(options.sfc.script, 0, classBlockEnd, codeFeatures_1.codeFeatures.all);
yield `__VLS_template = () => {${utils_1.newLine}`;
const templateCodegenCtx = yield* (0, template_1.generateTemplate)(options, ctx);
yield* (0, componentSelf_1.generateComponentSelf)(options, ctx, templateCodegenCtx);
yield `}${utils_1.endOfLine}`;
yield (0, utils_1.generateSfcBlockSection)(options.sfc.script, classBlockEnd, options.sfc.script.content.length, codeFeatures_1.codeFeatures.all);
}
}
else {
yield (0, utils_1.generateSfcBlockSection)(options.sfc.script, 0, options.sfc.script.content.length, codeFeatures_1.codeFeatures.all);
yield* generateScriptSectionPartiallyEnding(options.sfc.script.name, options.sfc.script.content.length, '#3632/script.vue');
}
}
else if (options.sfc.scriptSetup && options.scriptSetupRanges) {
yield* (0, scriptSetup_1.generateScriptSetup)(options, ctx, options.sfc.scriptSetup, options.scriptSetupRanges);
}
if (options.sfc.scriptSetup) {
yield* generateScriptSectionPartiallyEnding(options.sfc.scriptSetup.name, options.sfc.scriptSetup.content.length, '#4569/main.vue', ';');
}
if (!ctx.generatedTemplate) {
const templateCodegenCtx = yield* (0, template_1.generateTemplate)(options, ctx);
yield* (0, componentSelf_1.generateComponentSelf)(options, ctx, templateCodegenCtx);
}
if (options.edited) {
yield `type __VLS_IntrinsicElementsCompletion = __VLS_IntrinsicElements${utils_1.endOfLine}`;
}
yield* ctx.localTypes.generate([...ctx.localTypes.getUsedNames()]);
if (options.appendGlobalTypes) {
yield (0, globalTypes_1.generateGlobalTypes)(options.vueCompilerOptions);
}
if (options.sfc.scriptSetup) {
yield ['', 'scriptSetup', options.sfc.scriptSetup.content.length, codeFeatures_1.codeFeatures.verification];
}
return ctx;
}
function* generateScriptSectionPartiallyEnding(source, end, mark, delimiter = 'debugger') {
yield delimiter;
yield ['', source, end, codeFeatures_1.codeFeatures.verification];
yield `/* PartiallyEnd: ${mark} */${utils_1.newLine}`;
}
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1,6 @@
import type { ScriptSetupRanges } from '../../parsers/scriptSetupRanges';
import type { Code, Sfc } from '../../types';
import type { ScriptCodegenContext } from './context';
import { type ScriptCodegenOptions } from './index';
export declare function generateScriptSetupImports(scriptSetup: NonNullable<Sfc['scriptSetup']>, scriptSetupRanges: ScriptSetupRanges): Generator<Code>;
export declare function generateScriptSetup(options: ScriptCodegenOptions, ctx: ScriptCodegenContext, scriptSetup: NonNullable<Sfc['scriptSetup']>, scriptSetupRanges: ScriptSetupRanges): Generator<Code>;

View File

@@ -0,0 +1,489 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateScriptSetupImports = generateScriptSetupImports;
exports.generateScriptSetup = generateScriptSetup;
const shared_1 = require("@vue/shared");
const codeFeatures_1 = require("../codeFeatures");
const utils_1 = require("../utils");
const camelized_1 = require("../utils/camelized");
const wrapWith_1 = require("../utils/wrapWith");
const component_1 = require("./component");
const componentSelf_1 = require("./componentSelf");
const index_1 = require("./index");
const template_1 = require("./template");
function* generateScriptSetupImports(scriptSetup, scriptSetupRanges) {
yield [
scriptSetup.content.slice(0, Math.max(scriptSetupRanges.importSectionEndOffset, scriptSetupRanges.leadingCommentEndOffset)),
'scriptSetup',
0,
codeFeatures_1.codeFeatures.all,
];
}
function* generateScriptSetup(options, ctx, scriptSetup, scriptSetupRanges) {
if (scriptSetup.generic) {
if (!options.scriptRanges?.exportDefault) {
// #4569
yield ['', 'scriptSetup', 0, codeFeatures_1.codeFeatures.verification];
yield `export default `;
}
yield `(`;
if (typeof scriptSetup.generic === 'object') {
yield `<`;
yield [
scriptSetup.generic.text,
'main',
scriptSetup.generic.offset,
codeFeatures_1.codeFeatures.all,
];
if (!scriptSetup.generic.text.endsWith(`,`)) {
yield `,`;
}
yield `>`;
}
yield `(${utils_1.newLine}`
+ ` __VLS_props: NonNullable<Awaited<typeof __VLS_setup>>['props'],${utils_1.newLine}`
+ ` __VLS_ctx?: ${ctx.localTypes.PrettifyLocal}<Pick<NonNullable<Awaited<typeof __VLS_setup>>, 'attrs' | 'emit' | 'slots'>>,${utils_1.newLine}` // use __VLS_Prettify for less dts code
+ ` __VLS_expose?: NonNullable<Awaited<typeof __VLS_setup>>['expose'],${utils_1.newLine}`
+ ` __VLS_setup = (async () => {${utils_1.newLine}`;
yield* generateSetupFunction(options, ctx, scriptSetup, scriptSetupRanges, undefined);
const emitTypes = [];
if (scriptSetupRanges.defineEmits) {
emitTypes.push(`typeof ${scriptSetupRanges.defineEmits.name ?? '__VLS_emit'}`);
}
if (scriptSetupRanges.defineProp.some(p => p.isModel)) {
emitTypes.push(`typeof __VLS_modelEmit`);
}
yield `return {} as {${utils_1.newLine}`
+ ` props: ${ctx.localTypes.PrettifyLocal}<__VLS_OwnProps & __VLS_PublicProps & Partial<__VLS_InheritedAttrs>> & __VLS_BuiltInPublicProps,${utils_1.newLine}`
+ ` expose(exposed: import('${options.vueCompilerOptions.lib}').ShallowUnwrapRef<${scriptSetupRanges.defineExpose ? 'typeof __VLS_exposed' : '{}'}>): void,${utils_1.newLine}`
+ ` attrs: any,${utils_1.newLine}`
+ ` slots: __VLS_Slots,${utils_1.newLine}`
+ ` emit: ${emitTypes.length ? emitTypes.join(' & ') : `{}`},${utils_1.newLine}`
+ `}${utils_1.endOfLine}`;
yield `})(),${utils_1.newLine}`; // __VLS_setup = (async () => {
yield `) => ({} as import('${options.vueCompilerOptions.lib}').VNode & { __ctx?: Awaited<typeof __VLS_setup> }))`;
}
else if (!options.sfc.script) {
// no script block, generate script setup code at root
yield* generateSetupFunction(options, ctx, scriptSetup, scriptSetupRanges, 'export default');
}
else {
if (!options.scriptRanges?.exportDefault) {
yield `export default `;
}
yield `await (async () => {${utils_1.newLine}`;
yield* generateSetupFunction(options, ctx, scriptSetup, scriptSetupRanges, 'return');
yield `})()`;
}
}
function* generateSetupFunction(options, ctx, scriptSetup, scriptSetupRanges, syntax) {
let setupCodeModifies = [];
for (const { comments } of scriptSetupRanges.defineProp) {
if (comments) {
setupCodeModifies.push([
[``],
comments.start,
comments.end,
]);
}
}
if (scriptSetupRanges.defineProps) {
const { name, statement, callExp, typeArg } = scriptSetupRanges.defineProps;
setupCodeModifies.push(...generateDefineWithType(scriptSetup, statement, scriptSetupRanges.withDefaults?.callExp ?? callExp, typeArg, name, `__VLS_props`, `__VLS_Props`));
}
if (scriptSetupRanges.defineEmits) {
const { name, statement, callExp, typeArg } = scriptSetupRanges.defineEmits;
setupCodeModifies.push(...generateDefineWithType(scriptSetup, statement, callExp, typeArg, name, `__VLS_emit`, `__VLS_Emit`));
}
if (scriptSetupRanges.defineSlots) {
const { name, statement, callExp, typeArg } = scriptSetupRanges.defineSlots;
setupCodeModifies.push(...generateDefineWithType(scriptSetup, statement, callExp, typeArg, name, `__VLS_slots`, `__VLS_Slots`));
}
if (scriptSetupRanges.defineExpose) {
const { callExp, arg, typeArg } = scriptSetupRanges.defineExpose;
if (typeArg) {
setupCodeModifies.push([
[
`let __VLS_exposed!: `,
(0, utils_1.generateSfcBlockSection)(scriptSetup, typeArg.start, typeArg.end, codeFeatures_1.codeFeatures.all),
`${utils_1.endOfLine}`,
],
callExp.start,
callExp.start,
], [
[`typeof __VLS_exposed`],
typeArg.start,
typeArg.end,
]);
}
else if (arg) {
setupCodeModifies.push([
[
`const __VLS_exposed = `,
(0, utils_1.generateSfcBlockSection)(scriptSetup, arg.start, arg.end, codeFeatures_1.codeFeatures.all),
`${utils_1.endOfLine}`,
],
callExp.start,
callExp.start,
], [
[`__VLS_exposed`],
arg.start,
arg.end,
]);
}
else {
setupCodeModifies.push([
[`const __VLS_exposed = {}${utils_1.endOfLine}`],
callExp.start,
callExp.start,
]);
}
}
if (options.vueCompilerOptions.inferTemplateDollarAttrs) {
for (const { callExp } of scriptSetupRanges.useAttrs) {
setupCodeModifies.push([
[`(`],
callExp.start,
callExp.start
], [
[` as typeof __VLS_dollars.$attrs)`],
callExp.end,
callExp.end
]);
}
}
for (const { callExp, exp, arg } of scriptSetupRanges.useCssModule) {
setupCodeModifies.push([
[`(`],
callExp.start,
callExp.start
], [
arg ? [
` as Omit<__VLS_StyleModules, '$style'>[`,
(0, utils_1.generateSfcBlockSection)(scriptSetup, arg.start, arg.end, codeFeatures_1.codeFeatures.all),
`])`
] : [
` as __VLS_StyleModules[`,
...(0, wrapWith_1.wrapWith)(exp.start, exp.end, scriptSetup.name, codeFeatures_1.codeFeatures.verification, `'$style'`),
`])`
],
callExp.end,
callExp.end
]);
if (arg) {
setupCodeModifies.push([
[`__VLS_placeholder`],
arg.start,
arg.end
]);
}
}
if (options.vueCompilerOptions.inferTemplateDollarSlots) {
for (const { callExp } of scriptSetupRanges.useSlots) {
setupCodeModifies.push([
[`(`],
callExp.start,
callExp.start
], [
[` as typeof __VLS_dollars.$slots)`],
callExp.end,
callExp.end
]);
}
}
const isTs = options.lang !== 'js' && options.lang !== 'jsx';
for (const { callExp, exp, arg } of scriptSetupRanges.useTemplateRef) {
const templateRefType = arg
? [
`__VLS_TemplateRefs[`,
(0, utils_1.generateSfcBlockSection)(scriptSetup, arg.start, arg.end, codeFeatures_1.codeFeatures.all),
`]`
]
: [`unknown`];
if (isTs) {
setupCodeModifies.push([
[
`<`,
...templateRefType,
`>`
],
exp.end,
exp.end
]);
}
else {
setupCodeModifies.push([
[`(`],
callExp.start,
callExp.start
], [
[
` as __VLS_UseTemplateRef<`,
...templateRefType,
`>)`
],
callExp.end,
callExp.end
]);
}
if (arg) {
setupCodeModifies.push([
[`__VLS_placeholder`],
arg.start,
arg.end
]);
}
}
setupCodeModifies = setupCodeModifies.sort((a, b) => a[1] - b[1]);
let nextStart = Math.max(scriptSetupRanges.importSectionEndOffset, scriptSetupRanges.leadingCommentEndOffset);
for (const [codes, start, end] of setupCodeModifies) {
yield (0, utils_1.generateSfcBlockSection)(scriptSetup, nextStart, start, codeFeatures_1.codeFeatures.all);
yield* codes;
nextStart = end;
}
yield (0, utils_1.generateSfcBlockSection)(scriptSetup, nextStart, scriptSetup.content.length, codeFeatures_1.codeFeatures.all);
yield* (0, index_1.generateScriptSectionPartiallyEnding)(scriptSetup.name, scriptSetup.content.length, '#3632/scriptSetup.vue');
yield* generateMacros(options, ctx);
yield* generateDefineProp(options);
if (scriptSetupRanges.defineProps?.typeArg && scriptSetupRanges.withDefaults?.arg) {
// fix https://github.com/vuejs/language-tools/issues/1187
yield `const __VLS_withDefaultsArg = (function <T>(t: T) { return t })(`;
yield (0, utils_1.generateSfcBlockSection)(scriptSetup, scriptSetupRanges.withDefaults.arg.start, scriptSetupRanges.withDefaults.arg.end, codeFeatures_1.codeFeatures.navigation);
yield `)${utils_1.endOfLine}`;
}
yield* generateComponentProps(options, ctx, scriptSetup, scriptSetupRanges);
yield* generateModelEmit(scriptSetup, scriptSetupRanges);
const templateCodegenCtx = yield* (0, template_1.generateTemplate)(options, ctx);
yield* (0, componentSelf_1.generateComponentSelf)(options, ctx, templateCodegenCtx);
if (syntax) {
if (!options.vueCompilerOptions.skipTemplateCodegen
&& (scriptSetupRanges.defineSlots
|| options.templateCodegen?.slots.length
|| options.templateCodegen?.dynamicSlots.length)) {
yield `const __VLS_component = `;
yield* (0, component_1.generateComponent)(options, ctx, scriptSetup, scriptSetupRanges);
yield utils_1.endOfLine;
yield `${syntax} `;
yield `{} as ${ctx.localTypes.WithSlots}<typeof __VLS_component, __VLS_Slots>${utils_1.endOfLine}`;
}
else {
yield `${syntax} `;
yield* (0, component_1.generateComponent)(options, ctx, scriptSetup, scriptSetupRanges);
yield utils_1.endOfLine;
}
}
}
function* generateMacros(options, ctx) {
if (options.vueCompilerOptions.target >= 3.3) {
yield `// @ts-ignore${utils_1.newLine}`;
yield `declare const { `;
for (const macro of Object.keys(options.vueCompilerOptions.macros)) {
if (!ctx.bindingNames.has(macro)) {
yield `${macro}, `;
}
}
yield `}: typeof import('${options.vueCompilerOptions.lib}')${utils_1.endOfLine}`;
}
}
function* generateDefineProp(options) {
const definePropProposalA = options.vueCompilerOptions.experimentalDefinePropProposal === 'kevinEdition';
const definePropProposalB = options.vueCompilerOptions.experimentalDefinePropProposal === 'johnsonEdition';
if (definePropProposalA || definePropProposalB) {
yield `type __VLS_PropOptions<T> = Exclude<import('${options.vueCompilerOptions.lib}').Prop<T>, import('${options.vueCompilerOptions.lib}').PropType<T>>${utils_1.endOfLine}`;
if (definePropProposalA) {
yield `declare function defineProp<T>(name: string, options: ({ required: true } | { default: T }) & __VLS_PropOptions<T>): import('${options.vueCompilerOptions.lib}').ComputedRef<T>${utils_1.endOfLine}`;
yield `declare function defineProp<T>(name?: string, options?: __VLS_PropOptions<T>): import('${options.vueCompilerOptions.lib}').ComputedRef<T | undefined>${utils_1.endOfLine}`;
}
if (definePropProposalB) {
yield `declare function defineProp<T>(value: T | (() => T), required?: boolean, options?: __VLS_PropOptions<T>): import('${options.vueCompilerOptions.lib}').ComputedRef<T>${utils_1.endOfLine}`;
yield `declare function defineProp<T>(value: T | (() => T) | undefined, required: true, options?: __VLS_PropOptions<T>): import('${options.vueCompilerOptions.lib}').ComputedRef<T>${utils_1.endOfLine}`;
yield `declare function defineProp<T>(value?: T | (() => T), required?: boolean, options?: __VLS_PropOptions<T>): import('${options.vueCompilerOptions.lib}').ComputedRef<T | undefined>${utils_1.endOfLine}`;
}
}
}
function* generateDefineWithType(scriptSetup, statement, callExp, typeArg, name, defaultName, typeName) {
if (typeArg) {
yield [[
`type ${typeName} = `,
(0, utils_1.generateSfcBlockSection)(scriptSetup, typeArg.start, typeArg.end, codeFeatures_1.codeFeatures.all),
utils_1.endOfLine,
], statement.start, statement.start];
yield [[typeName], typeArg.start, typeArg.end];
}
if (!name) {
if (statement.start === callExp.start && statement.end === callExp.end) {
yield [[`const ${defaultName} = `], callExp.start, callExp.start];
}
else if (typeArg) {
yield [[
`const ${defaultName} = `,
(0, utils_1.generateSfcBlockSection)(scriptSetup, callExp.start, typeArg.start, codeFeatures_1.codeFeatures.all)
], statement.start, typeArg.start];
yield [[
(0, utils_1.generateSfcBlockSection)(scriptSetup, typeArg.end, callExp.end, codeFeatures_1.codeFeatures.all),
utils_1.endOfLine,
(0, utils_1.generateSfcBlockSection)(scriptSetup, statement.start, callExp.start, codeFeatures_1.codeFeatures.all),
defaultName
], typeArg.end, callExp.end];
}
else {
yield [[
`const ${defaultName} = `,
(0, utils_1.generateSfcBlockSection)(scriptSetup, callExp.start, callExp.end, codeFeatures_1.codeFeatures.all),
utils_1.endOfLine,
(0, utils_1.generateSfcBlockSection)(scriptSetup, statement.start, callExp.start, codeFeatures_1.codeFeatures.all),
defaultName
], statement.start, callExp.end];
}
}
}
function* generateComponentProps(options, ctx, scriptSetup, scriptSetupRanges) {
if (scriptSetup.generic) {
yield `const __VLS_fnComponent = (await import('${options.vueCompilerOptions.lib}')).defineComponent({${utils_1.newLine}`;
if (scriptSetupRanges.defineProps?.arg) {
yield `props: `;
yield (0, utils_1.generateSfcBlockSection)(scriptSetup, scriptSetupRanges.defineProps.arg.start, scriptSetupRanges.defineProps.arg.end, codeFeatures_1.codeFeatures.navigation);
yield `,${utils_1.newLine}`;
}
yield* (0, component_1.generateEmitsOption)(options, scriptSetupRanges);
yield `})${utils_1.endOfLine}`;
yield `type __VLS_BuiltInPublicProps = ${options.vueCompilerOptions.target >= 3.4
? `import('${options.vueCompilerOptions.lib}').PublicProps`
: options.vueCompilerOptions.target >= 3.0
? `import('${options.vueCompilerOptions.lib}').VNodeProps`
+ ` & import('${options.vueCompilerOptions.lib}').AllowedComponentProps`
+ ` & import('${options.vueCompilerOptions.lib}').ComponentCustomProps`
: `globalThis.JSX.IntrinsicAttributes`}`;
yield utils_1.endOfLine;
yield `type __VLS_OwnProps = `;
yield `${ctx.localTypes.OmitKeepDiscriminatedUnion}<InstanceType<typeof __VLS_fnComponent>['$props'], keyof __VLS_BuiltInPublicProps>`;
yield utils_1.endOfLine;
}
if (scriptSetupRanges.defineProp.length) {
yield `const __VLS_defaults = {${utils_1.newLine}`;
for (const defineProp of scriptSetupRanges.defineProp) {
if (!defineProp.defaultValue) {
continue;
}
const [propName, localName] = getPropAndLocalName(scriptSetup, defineProp);
if (defineProp.name || defineProp.isModel) {
yield `'${propName}'`;
}
else if (defineProp.localName) {
yield localName;
}
else {
continue;
}
yield `: `;
yield getRangeText(scriptSetup, defineProp.defaultValue);
yield `,${utils_1.newLine}`;
}
yield `}${utils_1.endOfLine}`;
}
yield `type __VLS_PublicProps = `;
if (scriptSetupRanges.defineSlots && options.vueCompilerOptions.jsxSlots) {
if (ctx.generatedPropsType) {
yield ` & `;
}
ctx.generatedPropsType = true;
yield `${ctx.localTypes.PropsChildren}<__VLS_Slots>`;
}
if (scriptSetupRanges.defineProps?.typeArg) {
if (ctx.generatedPropsType) {
yield ` & `;
}
ctx.generatedPropsType = true;
yield `__VLS_Props`;
}
if (scriptSetupRanges.defineProp.length) {
if (ctx.generatedPropsType) {
yield ` & `;
}
ctx.generatedPropsType = true;
yield `{${utils_1.newLine}`;
for (const defineProp of scriptSetupRanges.defineProp) {
const [propName, localName] = getPropAndLocalName(scriptSetup, defineProp);
if (defineProp.comments) {
yield (0, utils_1.generateSfcBlockSection)(scriptSetup, defineProp.comments.start, defineProp.comments.end, codeFeatures_1.codeFeatures.all);
yield utils_1.newLine;
}
if (defineProp.isModel && !defineProp.name) {
yield propName;
}
else if (defineProp.name) {
yield* (0, camelized_1.generateCamelized)(getRangeText(scriptSetup, defineProp.name), scriptSetup.name, defineProp.name.start, codeFeatures_1.codeFeatures.navigation);
}
else if (defineProp.localName) {
yield (0, utils_1.generateSfcBlockSection)(scriptSetup, defineProp.localName.start, defineProp.localName.end, codeFeatures_1.codeFeatures.navigation);
}
else {
continue;
}
yield defineProp.required
? `: `
: `?: `;
yield* generateDefinePropType(scriptSetup, propName, localName, defineProp);
yield `,${utils_1.newLine}`;
if (defineProp.modifierType) {
const modifierName = `${defineProp.name ? propName : 'model'}Modifiers`;
const modifierType = getRangeText(scriptSetup, defineProp.modifierType);
yield `'${modifierName}'?: Partial<Record<${modifierType}, true>>,${utils_1.newLine}`;
}
}
yield `}`;
}
if (!ctx.generatedPropsType) {
yield `{}`;
}
yield utils_1.endOfLine;
}
function* generateModelEmit(scriptSetup, scriptSetupRanges) {
const defineModels = scriptSetupRanges.defineProp.filter(p => p.isModel);
if (defineModels.length) {
yield `type __VLS_ModelEmit = {${utils_1.newLine}`;
for (const defineModel of defineModels) {
const [propName, localName] = getPropAndLocalName(scriptSetup, defineModel);
yield `'update:${propName}': [value: `;
yield* generateDefinePropType(scriptSetup, propName, localName, defineModel);
if (!defineModel.required && !defineModel.defaultValue) {
yield ` | undefined`;
}
yield `]${utils_1.endOfLine}`;
}
yield `}${utils_1.endOfLine}`;
yield `const __VLS_modelEmit = defineEmits<__VLS_ModelEmit>()${utils_1.endOfLine}`;
}
}
function* generateDefinePropType(scriptSetup, propName, localName, defineProp) {
if (defineProp.type) {
// Infer from defineProp<T>
yield getRangeText(scriptSetup, defineProp.type);
}
else if (defineProp.runtimeType && localName) {
// Infer from actual prop declaration code
yield `typeof ${localName}['value']`;
}
else if (defineProp.defaultValue && propName) {
// Infer from defineProp({default: T})
yield `typeof __VLS_defaults['${propName}']`;
}
else {
yield `any`;
}
}
function getPropAndLocalName(scriptSetup, defineProp) {
const localName = defineProp.localName
? getRangeText(scriptSetup, defineProp.localName)
: undefined;
const propName = defineProp.name
? (0, shared_1.camelize)(getRangeText(scriptSetup, defineProp.name).slice(1, -1))
: defineProp.isModel
? 'modelValue'
: localName;
return [propName, localName];
}
function getRangeText(scriptSetup, range) {
return scriptSetup.content.slice(range.start, range.end);
}
//# sourceMappingURL=scriptSetup.js.map

View File

@@ -0,0 +1,2 @@
import type { Code, SfcBlockAttr } from '../../types';
export declare function generateSrc(src: SfcBlockAttr): Generator<Code>;

View File

@@ -0,0 +1,50 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateSrc = generateSrc;
const codeFeatures_1 = require("../codeFeatures");
const utils_1 = require("../utils");
function* generateSrc(src) {
if (src === true) {
return;
}
let { text } = src;
if (text.endsWith('.d.ts')) {
text = text.slice(0, -'.d.ts'.length);
}
else if (text.endsWith('.ts')) {
text = text.slice(0, -'.ts'.length);
}
else if (text.endsWith('.tsx')) {
text = text.slice(0, -'.tsx'.length) + '.jsx';
}
if (!text.endsWith('.js') && !text.endsWith('.jsx')) {
text = text + '.js';
}
yield `export * from `;
yield* (0, utils_1.generateSfcBlockAttrValue)(src, text, {
...codeFeatures_1.codeFeatures.all,
navigation: text === src.text
? true
: {
shouldRename: () => false,
resolveRenameEditText(newName) {
if (newName.endsWith('.jsx') || newName.endsWith('.js')) {
newName = newName.split('.').slice(0, -1).join('.');
}
if (src?.text.endsWith('.d.ts')) {
newName = newName + '.d.ts';
}
else if (src?.text.endsWith('.ts')) {
newName = newName + '.ts';
}
else if (src?.text.endsWith('.tsx')) {
newName = newName + '.tsx';
}
return newName;
},
},
});
yield utils_1.endOfLine;
yield `export { default } from '${text}'${utils_1.endOfLine}`;
}
//# sourceMappingURL=src.js.map

View File

@@ -0,0 +1,7 @@
import type { Code } from '../../types';
import { type TemplateCodegenContext } from '../template/context';
import type { ScriptCodegenContext } from './context';
import type { ScriptCodegenOptions } from './index';
export declare function generateTemplate(options: ScriptCodegenOptions, ctx: ScriptCodegenContext): Generator<Code, TemplateCodegenContext>;
export declare function generateTemplateDirectives(options: ScriptCodegenOptions): Generator<Code>;
export declare function getTemplateUsageVars(options: ScriptCodegenOptions, ctx: ScriptCodegenContext): Set<string>;

View File

@@ -0,0 +1,148 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateTemplate = generateTemplate;
exports.generateTemplateDirectives = generateTemplateDirectives;
exports.getTemplateUsageVars = getTemplateUsageVars;
const shared_1 = require("../../utils/shared");
const codeFeatures_1 = require("../codeFeatures");
const modules_1 = require("../style/modules");
const scopedClasses_1 = require("../style/scopedClasses");
const context_1 = require("../template/context");
const interpolation_1 = require("../template/interpolation");
const styleScopedClasses_1 = require("../template/styleScopedClasses");
const utils_1 = require("../utils");
function* generateTemplate(options, ctx) {
ctx.generatedTemplate = true;
const templateCodegenCtx = (0, context_1.createTemplateCodegenContext)({
scriptSetupBindingNames: new Set(),
edited: options.edited,
});
yield* generateTemplateCtx(options);
yield* generateTemplateComponents(options);
yield* generateTemplateDirectives(options);
yield* generateTemplateBody(options, templateCodegenCtx);
return templateCodegenCtx;
}
function* generateTemplateCtx(options) {
const exps = [];
exps.push(`{} as InstanceType<__VLS_PickNotAny<typeof __VLS_self, new () => {}>>`);
if (options.vueCompilerOptions.petiteVueExtensions.some(ext => options.fileName.endsWith(ext))) {
exps.push(`globalThis`);
}
if (options.sfc.styles.some(style => style.module)) {
exps.push(`{} as __VLS_StyleModules`);
}
yield `const __VLS_ctx = `;
if (exps.length === 1) {
yield exps[0];
yield `${utils_1.endOfLine}`;
}
else {
yield `{${utils_1.newLine}`;
for (const exp of exps) {
yield `...`;
yield exp;
yield `,${utils_1.newLine}`;
}
yield `}${utils_1.endOfLine}`;
}
}
function* generateTemplateComponents(options) {
const types = [];
if (options.sfc.script && options.scriptRanges?.exportDefault?.componentsOption) {
const { componentsOption } = options.scriptRanges.exportDefault;
yield `const __VLS_componentsOption = `;
yield [
options.sfc.script.content.slice(componentsOption.start, componentsOption.end),
'script',
componentsOption.start,
codeFeatures_1.codeFeatures.navigation,
];
yield utils_1.endOfLine;
types.push(`typeof __VLS_componentsOption`);
}
types.push(`typeof __VLS_ctx`);
yield `type __VLS_LocalComponents =`;
for (const type of types) {
yield ` & `;
yield type;
}
yield utils_1.endOfLine;
yield `let __VLS_components!: __VLS_LocalComponents & __VLS_GlobalComponents${utils_1.endOfLine}`;
}
function* generateTemplateDirectives(options) {
const types = [];
if (options.sfc.script && options.scriptRanges?.exportDefault?.directivesOption) {
const { directivesOption } = options.scriptRanges.exportDefault;
yield `const __VLS_directivesOption = `;
yield [
options.sfc.script.content.slice(directivesOption.start, directivesOption.end),
'script',
directivesOption.start,
codeFeatures_1.codeFeatures.navigation,
];
yield utils_1.endOfLine;
types.push(`typeof __VLS_directivesOption`);
}
types.push(`typeof __VLS_ctx`);
yield `type __VLS_LocalDirectives =`;
for (const type of types) {
yield ` & `;
yield type;
}
yield utils_1.endOfLine;
yield `let __VLS_directives!: __VLS_LocalDirectives & __VLS_GlobalDirectives${utils_1.endOfLine}`;
}
function* generateTemplateBody(options, templateCodegenCtx) {
yield* (0, scopedClasses_1.generateStyleScopedClasses)(options, templateCodegenCtx);
yield* (0, styleScopedClasses_1.generateStyleScopedClassReferences)(templateCodegenCtx, true);
yield* (0, modules_1.generateStyleModules)(options);
yield* generateCssVars(options, templateCodegenCtx);
if (options.templateCodegen) {
yield* options.templateCodegen.codes;
}
else {
yield `// no template${utils_1.newLine}`;
if (!options.scriptSetupRanges?.defineSlots) {
yield `type __VLS_Slots = {}${utils_1.endOfLine}`;
}
yield `type __VLS_InheritedAttrs = {}${utils_1.endOfLine}`;
yield `type __VLS_TemplateRefs = {}${utils_1.endOfLine}`;
yield `type __VLS_RootEl = any${utils_1.endOfLine}`;
}
}
function* generateCssVars(options, ctx) {
if (!options.sfc.styles.length) {
return;
}
yield `// CSS variable injection ${utils_1.newLine}`;
for (const style of options.sfc.styles) {
for (const cssBind of style.cssVars) {
yield* (0, interpolation_1.generateInterpolation)(options, ctx, style.name, codeFeatures_1.codeFeatures.all, cssBind.text, cssBind.offset);
yield utils_1.endOfLine;
}
}
yield `// CSS variable injection end ${utils_1.newLine}`;
}
function getTemplateUsageVars(options, ctx) {
const usageVars = new Set();
const components = new Set(options.sfc.template?.ast?.components);
if (options.templateCodegen) {
// fix import components unused report
for (const varName of ctx.bindingNames) {
if (components.has(varName) || components.has((0, shared_1.hyphenateTag)(varName))) {
usageVars.add(varName);
}
}
for (const component of components) {
if (component.includes('.')) {
usageVars.add(component.split('.')[0]);
}
}
for (const [varName] of options.templateCodegen.accessExternalVariables) {
usageVars.add(varName);
}
}
return usageVars;
}
//# sourceMappingURL=template.js.map

View File

@@ -0,0 +1,2 @@
import type { Code } from '../../types';
export declare function generateClassProperty(styleIndex: number, classNameWithDot: string, offset: number, propertyType: string): Generator<Code>;

View File

@@ -0,0 +1,18 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateClassProperty = generateClassProperty;
const codeFeatures_1 = require("../codeFeatures");
const utils_1 = require("../utils");
const wrapWith_1 = require("../utils/wrapWith");
function* generateClassProperty(styleIndex, classNameWithDot, offset, propertyType) {
yield `${utils_1.newLine} & { `;
yield* (0, wrapWith_1.wrapWith)(offset, offset + classNameWithDot.length, 'style_' + styleIndex, codeFeatures_1.codeFeatures.navigation, `'`, [
classNameWithDot.slice(1),
'style_' + styleIndex,
offset + 1,
utils_1.combineLastMapping
], `'`);
yield `: ${propertyType}`;
yield ` }`;
}
//# sourceMappingURL=classProperty.js.map

View File

@@ -0,0 +1,3 @@
import type { Code } from '../../types';
import type { ScriptCodegenOptions } from '../script';
export declare function generateStyleModules(options: ScriptCodegenOptions): Generator<Code>;

View File

@@ -0,0 +1,34 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateStyleModules = generateStyleModules;
const codeFeatures_1 = require("../codeFeatures");
const utils_1 = require("../utils");
const classProperty_1 = require("./classProperty");
function* generateStyleModules(options) {
const styles = options.sfc.styles.map((style, i) => [style, i]).filter(([style]) => style.module);
if (!styles.length && !options.scriptSetupRanges?.useCssModule.length) {
return;
}
yield `type __VLS_StyleModules = {${utils_1.newLine}`;
for (const [style, i] of styles) {
if (style.module === true) {
yield `$style`;
}
else {
const { text, offset } = style.module;
yield [
text,
'main',
offset,
codeFeatures_1.codeFeatures.withoutHighlight
];
}
yield `: Record<string, string> & __VLS_PrettifyGlobal<{}`;
for (const className of style.classNames) {
yield* (0, classProperty_1.generateClassProperty)(i, className.text, className.offset, 'string');
}
yield `>${utils_1.endOfLine}`;
}
yield `}${utils_1.endOfLine}`;
}
//# sourceMappingURL=modules.js.map

View File

@@ -0,0 +1,4 @@
import type { Code } from '../../types';
import type { ScriptCodegenOptions } from '../script';
import type { TemplateCodegenContext } from '../template/context';
export declare function generateStyleScopedClasses(options: ScriptCodegenOptions, ctx: TemplateCodegenContext): Generator<Code>;

View File

@@ -0,0 +1,32 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateStyleScopedClasses = generateStyleScopedClasses;
const utils_1 = require("../utils");
const classProperty_1 = require("./classProperty");
function* generateStyleScopedClasses(options, ctx) {
const option = options.vueCompilerOptions.experimentalResolveStyleCssClasses;
const styles = options.sfc.styles
.map((style, i) => [style, i])
.filter(([style]) => option === 'always' || (option === 'scoped' && style.scoped));
if (!styles.length) {
return;
}
const firstClasses = new Set();
yield `type __VLS_StyleScopedClasses = {}`;
for (const [style, i] of styles) {
for (const className of style.classNames) {
if (firstClasses.has(className.text)) {
ctx.scopedClasses.push({
source: 'style_' + i,
className: className.text.slice(1),
offset: className.offset + 1
});
continue;
}
firstClasses.add(className.text);
yield* (0, classProperty_1.generateClassProperty)(i, className.text, className.offset, 'boolean');
}
}
yield utils_1.endOfLine;
}
//# sourceMappingURL=scopedClasses.js.map

View File

@@ -0,0 +1,172 @@
import type * as CompilerDOM from '@vue/compiler-dom';
import type { Code, VueCodeInformation } from '../../types';
import { InlayHintInfo } from '../inlayHints';
import type { TemplateCodegenOptions } from './index';
export type TemplateCodegenContext = ReturnType<typeof createTemplateCodegenContext>;
/**
* Creates and returns a Context object used for generating type-checkable TS code
* from the template section of a .vue file.
*
* ## Implementation Notes for supporting `@vue-ignore`, `@vue-expect-error`, and `@vue-skip` directives.
*
* Vue language tooling supports a number of directives for suppressing diagnostics within
* Vue templates (https://github.com/vuejs/language-tools/pull/3215)
*
* Here is an overview for how support for how @vue-expect-error is implemented within this file
* (@vue-expect-error is the most complicated directive to support due to its behavior of raising
* a diagnostic when it is annotating a piece of code that doesn't actually have any errors/warning/diagnostics).
*
* Given .vue code:
*
* ```vue
* <script setup lang="ts">
* defineProps<{
* knownProp1: string;
* knownProp2: string;
* knownProp3: string;
* knownProp4_will_trigger_unused_expect_error: string;
* }>();
* </script>
*
* <template>
* {{ knownProp1 }}
* {{ error_unknownProp }} <!-- ERROR: Property 'error_unknownProp' does not exist on type [...] -->
* {{ knownProp2 }}
* <!-- @vue-expect-error This suppresses an Unknown Property Error -->
* {{ suppressed_error_unknownProp }}
* {{ knownProp3 }}
* <!-- @vue-expect-error This will trigger Unused '@ts-expect-error' directive.ts(2578) -->
* {{ knownProp4_will_trigger_unused_expect_error }}
* </template>
* ```
*
* The above code should raise two diagnostics:
*
* 1. Property 'error_unknownProp' does not exist on type [...]
* 2. Unused '@ts-expect-error' directive.ts(2578) -- this is the bottom `@vue-expect-error` directive
* that covers code that doesn't actually raise an error -- note that all `@vue-...` directives
* will ultimately translate into `@ts-...` diagnostics.
*
* The above code will produce the following type-checkable TS code (note: omitting asterisks
* to prevent VSCode syntax double-greying out double-commented code).
*
* ```ts
* ( __VLS_ctx.knownProp1 );
* ( __VLS_ctx.error_unknownProp ); // ERROR: Property 'error_unknownProp' does not exist on type [...]
* ( __VLS_ctx.knownProp2 );
* // @vue-expect-error start
* ( __VLS_ctx.suppressed_error_unknownProp );
* // @ts-expect-error __VLS_TS_EXPECT_ERROR
* ;
* // @vue-expect-error end of INTERPOLATION
* ( __VLS_ctx.knownProp3 );
* // @vue-expect-error start
* ( __VLS_ctx.knownProp4_will_trigger_unused_expect_error );
* // @ts-expect-error __VLS_TS_EXPECT_ERROR
* ;
* // @vue-expect-error end of INTERPOLATION
* ```
*
* In the generated code, there are actually 3 diagnostic errors that'll be raised in the first
* pass on this generated code (but through cleverness described below, not all of them will be
* propagated back to the original .vue file):
*
* 1. Property 'error_unknownProp' does not exist on type [...]
* 2. Unused '@ts-expect-error' directive.ts(2578) from the 1st `@ts-expect-error __VLS_TS_EXPECT_ERROR`
* 3. Unused '@ts-expect-error' directive.ts(2578) from the 2nd `@ts-expect-error __VLS_TS_EXPECT_ERROR`
*
* Be sure to pay careful attention to the mixture of `@vue-expect-error` and `@ts-expect-error`;
* Within the TS file, the only "real" directives recognized by TS are going to be prefixed with `@ts-`;
* any `@vue-` prefixed directives in the comments are only for debugging purposes.
*
* As mentioned above, there are 3 diagnostics errors that'll be generated for the above code, but
* only 2 should be propagated back to the original .vue file.
*
* (The reason we structure things this way is somewhat complicated, but in short it allows us
* to lean on TS as much as possible to generate actual `unused @ts-expect-error directive` errors
* while covering a number of edge cases.)
*
* So, we need a way to dynamically decide whether each of the `@ts-expect-error __VLS_TS_EXPECT_ERROR`
* directives should be reported as an unused directive or not.
*
* To do this, we'll make use of the `shouldReport` callback that'll optionally be provided to the
* `verification` property of the `CodeInformation` object attached to the mapping between source .vue
* and generated .ts code. The `verification` property determines whether "verification" (which includes
* semantic diagnostics) should be performed on the generated .ts code, and `shouldReport`, if provided,
* can be used to determine whether a given diagnostic should be reported back "upwards" to the original
* .vue file or not.
*
* See the comments in the code below for how and where we use this hook to keep track of whether
* an error/diagnostic was encountered for a region of code covered by a `@vue-expect-error` directive,
* and additionally how we use that to determine whether to propagate diagnostics back upward.
*/
export declare function createTemplateCodegenContext(options: Pick<TemplateCodegenOptions, 'scriptSetupBindingNames' | 'edited'>): {
codeFeatures: {
all: VueCodeInformation;
none: VueCodeInformation;
verification: VueCodeInformation;
completion: VueCodeInformation;
additionalCompletion: VueCodeInformation;
withoutCompletion: VueCodeInformation;
navigation: VueCodeInformation;
navigationWithoutRename: VueCodeInformation;
navigationAndCompletion: VueCodeInformation;
navigationAndAdditionalCompletion: VueCodeInformation;
navigationAndVerification: VueCodeInformation;
withoutNavigation: VueCodeInformation;
withoutHighlight: VueCodeInformation;
withoutHighlightAndNavigation: VueCodeInformation;
withoutHighlightAndCompletion: VueCodeInformation;
withoutHighlightAndCompletionAndNavigation: VueCodeInformation;
};
resolveCodeFeatures: (features: VueCodeInformation) => VueCodeInformation;
slots: {
name: string;
offset?: number;
tagRange: [number, number];
nodeLoc: any;
propsVar: string;
}[];
dynamicSlots: {
expVar: string;
propsVar: string;
}[];
dollarVars: Set<string>;
accessExternalVariables: Map<string, Set<number>>;
lastGenericComment: {
content: string;
offset: number;
} | undefined;
blockConditions: string[];
scopedClasses: {
source: string;
className: string;
offset: number;
}[];
emptyClassOffsets: number[];
inlayHints: InlayHintInfo[];
bindingAttrLocs: CompilerDOM.SourceLocation[];
inheritedAttrVars: Set<string>;
templateRefs: Map<string, {
typeExp: string;
offset: number;
}>;
currentComponent: {
ctxVar: string;
used: boolean;
} | undefined;
singleRootElTypes: string[];
singleRootNodes: Set<CompilerDOM.ElementNode | null>;
accessExternalVariable(name: string, offset?: number): void;
hasLocalVariable: (name: string) => boolean;
addLocalVariable: (name: string) => void;
removeLocalVariable: (name: string) => void;
getInternalVariable: () => string;
getHoistVariable: (originalVar: string) => string;
generateHoistVariables: () => Generator<string, void, unknown>;
generateConditionGuards: () => Generator<string, void, unknown>;
ignoreError: () => Generator<Code>;
expectError: (prevNode: CompilerDOM.CommentNode) => Generator<Code>;
resetDirectiveComments: (endStr: string) => Generator<Code>;
generateAutoImportCompletion: () => Generator<Code>;
};

View File

@@ -0,0 +1,293 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createTemplateCodegenContext = createTemplateCodegenContext;
const codeFeatures_1 = require("../codeFeatures");
const utils_1 = require("../utils");
const wrapWith_1 = require("../utils/wrapWith");
/**
* Creates and returns a Context object used for generating type-checkable TS code
* from the template section of a .vue file.
*
* ## Implementation Notes for supporting `@vue-ignore`, `@vue-expect-error`, and `@vue-skip` directives.
*
* Vue language tooling supports a number of directives for suppressing diagnostics within
* Vue templates (https://github.com/vuejs/language-tools/pull/3215)
*
* Here is an overview for how support for how @vue-expect-error is implemented within this file
* (@vue-expect-error is the most complicated directive to support due to its behavior of raising
* a diagnostic when it is annotating a piece of code that doesn't actually have any errors/warning/diagnostics).
*
* Given .vue code:
*
* ```vue
* <script setup lang="ts">
* defineProps<{
* knownProp1: string;
* knownProp2: string;
* knownProp3: string;
* knownProp4_will_trigger_unused_expect_error: string;
* }>();
* </script>
*
* <template>
* {{ knownProp1 }}
* {{ error_unknownProp }} <!-- ERROR: Property 'error_unknownProp' does not exist on type [...] -->
* {{ knownProp2 }}
* <!-- @vue-expect-error This suppresses an Unknown Property Error -->
* {{ suppressed_error_unknownProp }}
* {{ knownProp3 }}
* <!-- @vue-expect-error This will trigger Unused '@ts-expect-error' directive.ts(2578) -->
* {{ knownProp4_will_trigger_unused_expect_error }}
* </template>
* ```
*
* The above code should raise two diagnostics:
*
* 1. Property 'error_unknownProp' does not exist on type [...]
* 2. Unused '@ts-expect-error' directive.ts(2578) -- this is the bottom `@vue-expect-error` directive
* that covers code that doesn't actually raise an error -- note that all `@vue-...` directives
* will ultimately translate into `@ts-...` diagnostics.
*
* The above code will produce the following type-checkable TS code (note: omitting asterisks
* to prevent VSCode syntax double-greying out double-commented code).
*
* ```ts
* ( __VLS_ctx.knownProp1 );
* ( __VLS_ctx.error_unknownProp ); // ERROR: Property 'error_unknownProp' does not exist on type [...]
* ( __VLS_ctx.knownProp2 );
* // @vue-expect-error start
* ( __VLS_ctx.suppressed_error_unknownProp );
* // @ts-expect-error __VLS_TS_EXPECT_ERROR
* ;
* // @vue-expect-error end of INTERPOLATION
* ( __VLS_ctx.knownProp3 );
* // @vue-expect-error start
* ( __VLS_ctx.knownProp4_will_trigger_unused_expect_error );
* // @ts-expect-error __VLS_TS_EXPECT_ERROR
* ;
* // @vue-expect-error end of INTERPOLATION
* ```
*
* In the generated code, there are actually 3 diagnostic errors that'll be raised in the first
* pass on this generated code (but through cleverness described below, not all of them will be
* propagated back to the original .vue file):
*
* 1. Property 'error_unknownProp' does not exist on type [...]
* 2. Unused '@ts-expect-error' directive.ts(2578) from the 1st `@ts-expect-error __VLS_TS_EXPECT_ERROR`
* 3. Unused '@ts-expect-error' directive.ts(2578) from the 2nd `@ts-expect-error __VLS_TS_EXPECT_ERROR`
*
* Be sure to pay careful attention to the mixture of `@vue-expect-error` and `@ts-expect-error`;
* Within the TS file, the only "real" directives recognized by TS are going to be prefixed with `@ts-`;
* any `@vue-` prefixed directives in the comments are only for debugging purposes.
*
* As mentioned above, there are 3 diagnostics errors that'll be generated for the above code, but
* only 2 should be propagated back to the original .vue file.
*
* (The reason we structure things this way is somewhat complicated, but in short it allows us
* to lean on TS as much as possible to generate actual `unused @ts-expect-error directive` errors
* while covering a number of edge cases.)
*
* So, we need a way to dynamically decide whether each of the `@ts-expect-error __VLS_TS_EXPECT_ERROR`
* directives should be reported as an unused directive or not.
*
* To do this, we'll make use of the `shouldReport` callback that'll optionally be provided to the
* `verification` property of the `CodeInformation` object attached to the mapping between source .vue
* and generated .ts code. The `verification` property determines whether "verification" (which includes
* semantic diagnostics) should be performed on the generated .ts code, and `shouldReport`, if provided,
* can be used to determine whether a given diagnostic should be reported back "upwards" to the original
* .vue file or not.
*
* See the comments in the code below for how and where we use this hook to keep track of whether
* an error/diagnostic was encountered for a region of code covered by a `@vue-expect-error` directive,
* and additionally how we use that to determine whether to propagate diagnostics back upward.
*/
function createTemplateCodegenContext(options) {
let ignoredError = false;
let expectErrorToken;
let lastGenericComment;
let variableId = 0;
function resolveCodeFeatures(features) {
if (features.verification) {
if (ignoredError) {
// We are currently in a region of code covered by a @vue-ignore directive, so don't
// even bother performing any type-checking: set verification to false.
return {
...features,
verification: false,
};
}
if (expectErrorToken) {
// We are currently in a region of code covered by a @vue-expect-error directive. We need to
// keep track of the number of errors encountered within this region so that we can know whether
// we will need to propagate an "unused ts-expect-error" diagnostic back to the original
// .vue file or not.
const token = expectErrorToken;
return {
...features,
verification: {
shouldReport: () => {
token.errors++;
return false;
},
},
};
}
}
return features;
}
const hoistVars = new Map();
const localVars = new Map();
const dollarVars = new Set();
const accessExternalVariables = new Map();
const slots = [];
const dynamicSlots = [];
const blockConditions = [];
const scopedClasses = [];
const emptyClassOffsets = [];
const inlayHints = [];
const bindingAttrLocs = [];
const inheritedAttrVars = new Set();
const templateRefs = new Map();
return {
codeFeatures: new Proxy(codeFeatures_1.codeFeatures, {
get(target, key) {
const data = target[key];
return resolveCodeFeatures(data);
},
}),
resolveCodeFeatures,
slots,
dynamicSlots,
dollarVars,
accessExternalVariables,
lastGenericComment,
blockConditions,
scopedClasses,
emptyClassOffsets,
inlayHints,
bindingAttrLocs,
inheritedAttrVars,
templateRefs,
currentComponent: undefined,
singleRootElTypes: [],
singleRootNodes: new Set(),
accessExternalVariable(name, offset) {
let arr = accessExternalVariables.get(name);
if (!arr) {
accessExternalVariables.set(name, arr = new Set());
}
if (offset !== undefined) {
arr.add(offset);
}
},
hasLocalVariable: (name) => {
return !!localVars.get(name);
},
addLocalVariable: (name) => {
localVars.set(name, (localVars.get(name) ?? 0) + 1);
},
removeLocalVariable: (name) => {
localVars.set(name, localVars.get(name) - 1);
},
getInternalVariable: () => {
return `__VLS_${variableId++}`;
},
getHoistVariable: (originalVar) => {
let name = hoistVars.get(originalVar);
if (name === undefined) {
hoistVars.set(originalVar, name = `__VLS_${variableId++}`);
}
return name;
},
generateHoistVariables: function* () {
// trick to avoid TS 4081 (#5186)
if (hoistVars.size) {
yield `// @ts-ignore${utils_1.newLine}`;
yield `var `;
for (const [originalVar, hoistVar] of hoistVars) {
yield `${hoistVar} = ${originalVar}, `;
}
yield utils_1.endOfLine;
}
},
generateConditionGuards: function* () {
for (const condition of blockConditions) {
yield `if (!${condition}) return${utils_1.endOfLine}`;
}
},
ignoreError: function* () {
if (!ignoredError) {
ignoredError = true;
yield `// @vue-ignore start${utils_1.newLine}`;
}
},
expectError: function* (prevNode) {
if (!expectErrorToken) {
expectErrorToken = {
errors: 0,
node: prevNode,
};
yield `// @vue-expect-error start${utils_1.newLine}`;
}
},
resetDirectiveComments: function* (endStr) {
if (expectErrorToken) {
const token = expectErrorToken;
yield* (0, wrapWith_1.wrapWith)(expectErrorToken.node.loc.start.offset, expectErrorToken.node.loc.end.offset, {
verification: {
// If no errors/warnings/diagnostics were reported within the region of code covered
// by the @vue-expect-error directive, then we should allow any `unused @ts-expect-error`
// diagnostics to be reported upward.
shouldReport: () => token.errors === 0,
},
}, `// @ts-expect-error __VLS_TS_EXPECT_ERROR`);
yield `${utils_1.newLine}${utils_1.endOfLine}`;
expectErrorToken = undefined;
yield `// @vue-expect-error ${endStr}${utils_1.newLine}`;
}
if (ignoredError) {
ignoredError = false;
yield `// @vue-ignore ${endStr}${utils_1.newLine}`;
}
},
generateAutoImportCompletion: function* () {
if (!options.edited) {
return;
}
const all = [...accessExternalVariables.entries()];
if (!all.some(([_, offsets]) => offsets.size)) {
return;
}
yield `// @ts-ignore${utils_1.newLine}`; // #2304
yield `[`;
for (const [varName, offsets] of all) {
for (const offset of offsets) {
if (options.scriptSetupBindingNames.has(varName)) {
// #3409
yield [
varName,
'template',
offset,
{
...codeFeatures_1.codeFeatures.additionalCompletion,
...codeFeatures_1.codeFeatures.withoutHighlightAndCompletionAndNavigation,
},
];
}
else {
yield [
varName,
'template',
offset,
codeFeatures_1.codeFeatures.additionalCompletion,
];
}
yield `,`;
}
offsets.clear();
}
yield `]${utils_1.endOfLine}`;
}
};
}
//# sourceMappingURL=context.js.map

View File

@@ -0,0 +1,6 @@
import * as CompilerDOM from '@vue/compiler-dom';
import type { Code } from '../../types';
import type { TemplateCodegenContext } from './context';
import type { TemplateCodegenOptions } from './index';
export declare function generateComponent(options: TemplateCodegenOptions, ctx: TemplateCodegenContext, node: CompilerDOM.ElementNode, isVForChild: boolean): Generator<Code>;
export declare function generateElement(options: TemplateCodegenOptions, ctx: TemplateCodegenContext, node: CompilerDOM.ElementNode, isVForChild: boolean): Generator<Code>;

View File

@@ -0,0 +1,328 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateComponent = generateComponent;
exports.generateElement = generateElement;
const CompilerDOM = require("@vue/compiler-dom");
const shared_1 = require("@vue/shared");
const shared_2 = require("../../utils/shared");
const inlayHints_1 = require("../inlayHints");
const utils_1 = require("../utils");
const camelized_1 = require("../utils/camelized");
const wrapWith_1 = require("../utils/wrapWith");
const elementChildren_1 = require("./elementChildren");
const elementDirectives_1 = require("./elementDirectives");
const elementEvents_1 = require("./elementEvents");
const elementProps_1 = require("./elementProps");
const interpolation_1 = require("./interpolation");
const propertyAccess_1 = require("./propertyAccess");
const styleScopedClasses_1 = require("./styleScopedClasses");
const vSlot_1 = require("./vSlot");
const colonReg = /:/g;
function* generateComponent(options, ctx, node, isVForChild) {
const tagOffsets = [node.loc.start.offset + options.template.content.slice(node.loc.start.offset).indexOf(node.tag)];
if (!node.isSelfClosing && options.template.lang === 'html') {
const endTagOffset = node.loc.start.offset + node.loc.source.lastIndexOf(node.tag);
if (endTagOffset > tagOffsets[0]) {
tagOffsets.push(endTagOffset);
}
}
const failedPropExps = [];
const possibleOriginalNames = getPossibleOriginalComponentNames(node.tag, true);
const matchImportName = possibleOriginalNames.find(name => options.scriptSetupImportComponentNames.has(name));
const componentOriginalVar = matchImportName ?? ctx.getInternalVariable();
const componentFunctionalVar = ctx.getInternalVariable();
const componentVNodeVar = ctx.getInternalVariable();
const componentCtxVar = ctx.getInternalVariable();
const isComponentTag = node.tag.toLowerCase() === 'component';
ctx.currentComponent = {
ctxVar: componentCtxVar,
used: false
};
let props = node.props;
let dynamicTagInfo;
if (isComponentTag) {
for (const prop of node.props) {
if (prop.type === CompilerDOM.NodeTypes.DIRECTIVE
&& prop.name === 'bind'
&& prop.arg?.loc.source === 'is'
&& prop.exp?.type === CompilerDOM.NodeTypes.SIMPLE_EXPRESSION) {
if (prop.arg.loc.end.offset === prop.exp.loc.end.offset) {
ctx.inlayHints.push((0, inlayHints_1.createVBindShorthandInlayHintInfo)(prop.exp.loc, 'is'));
}
dynamicTagInfo = {
tag: prop.exp.content,
offsets: [prop.exp.loc.start.offset],
astHolder: prop.exp.loc,
};
props = props.filter(p => p !== prop);
break;
}
}
}
else if (node.tag.includes('.')) {
// namespace tag
dynamicTagInfo = {
tag: node.tag,
offsets: tagOffsets,
astHolder: node.loc,
};
}
if (matchImportName) {
// navigation support
yield `/** @type {[`;
for (const tagOffset of tagOffsets) {
yield `typeof `;
if (componentOriginalVar === node.tag) {
yield [
componentOriginalVar,
'template',
tagOffset,
ctx.codeFeatures.withoutHighlightAndCompletion,
];
}
else {
const shouldCapitalize = matchImportName[0].toUpperCase() === matchImportName[0];
yield* (0, camelized_1.generateCamelized)(shouldCapitalize ? (0, shared_1.capitalize)(node.tag) : node.tag, 'template', tagOffset, {
...ctx.codeFeatures.withoutHighlightAndCompletion,
navigation: {
resolveRenameNewName: camelizeComponentName,
resolveRenameEditText: getTagRenameApply(node.tag),
},
});
}
yield `, `;
}
yield `]} */${utils_1.endOfLine}`;
}
else if (dynamicTagInfo) {
yield `const ${componentOriginalVar} = (`;
yield* (0, interpolation_1.generateInterpolation)(options, ctx, 'template', ctx.codeFeatures.all, dynamicTagInfo.tag, dynamicTagInfo.offsets[0], dynamicTagInfo.astHolder, `(`, `)`);
if (dynamicTagInfo.offsets[1] !== undefined) {
yield `,`;
yield* (0, interpolation_1.generateInterpolation)(options, ctx, 'template', ctx.codeFeatures.withoutCompletion, dynamicTagInfo.tag, dynamicTagInfo.offsets[1], dynamicTagInfo.astHolder, `(`, `)`);
}
yield `)${utils_1.endOfLine}`;
}
else if (!isComponentTag) {
yield `const ${componentOriginalVar} = ({} as __VLS_WithComponent<'${getCanonicalComponentName(node.tag)}', __VLS_LocalComponents, `;
if (options.selfComponentName && possibleOriginalNames.includes(options.selfComponentName)) {
yield `typeof __VLS_self & (new () => { `
+ (0, shared_2.getSlotsPropertyName)(options.vueCompilerOptions.target)
+ `: __VLS_Slots }), `;
}
else {
yield `void, `;
}
yield getPossibleOriginalComponentNames(node.tag, false)
.map(name => `'${name}'`)
.join(`, `);
yield `>).`;
yield* generateCanonicalComponentName(node.tag, tagOffsets[0], ctx.codeFeatures.withoutHighlightAndCompletionAndNavigation);
yield `${utils_1.endOfLine}`;
const camelizedTag = (0, shared_1.camelize)(node.tag);
if (utils_1.identifierRegex.test(camelizedTag)) {
// navigation support
yield `/** @type {[`;
for (const tagOffset of tagOffsets) {
for (const shouldCapitalize of (node.tag[0] === node.tag[0].toUpperCase() ? [false] : [true, false])) {
const expectName = shouldCapitalize ? (0, shared_1.capitalize)(camelizedTag) : camelizedTag;
yield `typeof __VLS_components.`;
yield* (0, camelized_1.generateCamelized)(shouldCapitalize ? (0, shared_1.capitalize)(node.tag) : node.tag, 'template', tagOffset, {
navigation: {
resolveRenameNewName: node.tag !== expectName ? camelizeComponentName : undefined,
resolveRenameEditText: getTagRenameApply(node.tag),
},
});
yield `, `;
}
}
yield `]} */${utils_1.endOfLine}`;
// auto import support
if (options.edited) {
yield `// @ts-ignore${utils_1.newLine}`; // #2304
yield* (0, camelized_1.generateCamelized)((0, shared_1.capitalize)(node.tag), 'template', tagOffsets[0], {
completion: {
isAdditional: true,
onlyImport: true,
},
});
yield `${utils_1.endOfLine}`;
}
}
}
else {
yield `const ${componentOriginalVar} = {} as any${utils_1.endOfLine}`;
}
yield `// @ts-ignore${utils_1.newLine}`;
yield `const ${componentFunctionalVar} = __VLS_asFunctionalComponent(${componentOriginalVar}, new ${componentOriginalVar}({${utils_1.newLine}`;
yield* (0, elementProps_1.generateElementProps)(options, ctx, node, props, options.vueCompilerOptions.checkUnknownProps, false);
yield `}))${utils_1.endOfLine}`;
yield `const `;
yield* (0, wrapWith_1.wrapWith)(node.loc.start.offset, node.loc.end.offset, ctx.resolveCodeFeatures({
verification: {
shouldReport(_source, code) {
// https://typescript.tv/errors/#ts6133
return String(code) !== '6133';
},
}
}), componentVNodeVar);
yield ` = ${componentFunctionalVar}`;
yield* generateComponentGeneric(ctx);
yield `(`;
yield* (0, wrapWith_1.wrapWith)(tagOffsets[0], tagOffsets[0] + node.tag.length, ctx.codeFeatures.verification, `{${utils_1.newLine}`, ...(0, elementProps_1.generateElementProps)(options, ctx, node, props, options.vueCompilerOptions.checkUnknownProps, true, failedPropExps), `}`);
yield `, ...__VLS_functionalComponentArgsRest(${componentFunctionalVar}))${utils_1.endOfLine}`;
yield* generateFailedPropExps(options, ctx, failedPropExps);
yield* (0, elementEvents_1.generateElementEvents)(options, ctx, node, componentFunctionalVar, componentVNodeVar, componentCtxVar);
yield* (0, elementDirectives_1.generateElementDirectives)(options, ctx, node);
const [refName, offset] = yield* generateElementReference(options, ctx, node);
const tag = (0, shared_2.hyphenateTag)(node.tag);
const isRootNode = ctx.singleRootNodes.has(node) && !options.vueCompilerOptions.fallthroughComponentNames.includes(tag);
if (refName || isRootNode) {
const componentInstanceVar = ctx.getInternalVariable();
ctx.currentComponent.used = true;
yield `var ${componentInstanceVar} = {} as (Parameters<NonNullable<typeof ${componentCtxVar}['expose']>>[0] | null)`;
if (isVForChild) {
yield `[]`;
}
yield `${utils_1.endOfLine}`;
if (refName && offset) {
ctx.templateRefs.set(refName, {
typeExp: `typeof ${ctx.getHoistVariable(componentInstanceVar)}`,
offset
});
}
if (isRootNode) {
ctx.singleRootElTypes.push(`NonNullable<typeof ${componentInstanceVar}>['$el']`);
}
}
if (hasVBindAttrs(options, ctx, node)) {
const attrsVar = ctx.getInternalVariable();
yield `let ${attrsVar}!: Parameters<typeof ${componentFunctionalVar}>[0]${utils_1.endOfLine}`;
ctx.inheritedAttrVars.add(attrsVar);
}
(0, styleScopedClasses_1.collectStyleScopedClassReferences)(options, ctx, node);
const slotDir = node.props.find(p => p.type === CompilerDOM.NodeTypes.DIRECTIVE && p.name === 'slot');
if (slotDir) {
yield* (0, vSlot_1.generateVSlot)(options, ctx, node, slotDir);
}
else {
// #932: reference for default slot
yield* (0, vSlot_1.generateImplicitDefaultSlot)(ctx, node);
yield* (0, elementChildren_1.generateElementChildren)(options, ctx, node);
}
if (ctx.currentComponent.used) {
yield `var ${componentCtxVar}!: __VLS_PickFunctionalComponentCtx<typeof ${componentOriginalVar}, typeof ${componentVNodeVar}>${utils_1.endOfLine}`;
}
}
function* generateElement(options, ctx, node, isVForChild) {
const startTagOffset = node.loc.start.offset + options.template.content.slice(node.loc.start.offset).indexOf(node.tag);
const endTagOffset = !node.isSelfClosing && options.template.lang === 'html'
? node.loc.start.offset + node.loc.source.lastIndexOf(node.tag)
: undefined;
const failedPropExps = [];
yield `__VLS_asFunctionalElement(__VLS_intrinsicElements`;
yield* (0, propertyAccess_1.generatePropertyAccess)(options, ctx, node.tag, startTagOffset, ctx.codeFeatures.withoutHighlightAndCompletion);
if (endTagOffset !== undefined) {
yield `, __VLS_intrinsicElements`;
yield* (0, propertyAccess_1.generatePropertyAccess)(options, ctx, node.tag, endTagOffset, ctx.codeFeatures.withoutHighlightAndCompletion);
}
yield `)(`;
yield* (0, wrapWith_1.wrapWith)(startTagOffset, startTagOffset + node.tag.length, ctx.codeFeatures.verification, `{${utils_1.newLine}`, ...(0, elementProps_1.generateElementProps)(options, ctx, node, node.props, options.vueCompilerOptions.checkUnknownProps, true, failedPropExps), `}`);
yield `)${utils_1.endOfLine}`;
yield* generateFailedPropExps(options, ctx, failedPropExps);
yield* (0, elementDirectives_1.generateElementDirectives)(options, ctx, node);
const [refName, offset] = yield* generateElementReference(options, ctx, node);
if (refName && offset) {
let typeExp = `__VLS_NativeElements['${node.tag}']`;
if (isVForChild) {
typeExp += `[]`;
}
ctx.templateRefs.set(refName, {
typeExp,
offset
});
}
if (ctx.singleRootNodes.has(node)) {
ctx.singleRootElTypes.push(`__VLS_NativeElements['${node.tag}']`);
}
if (hasVBindAttrs(options, ctx, node)) {
ctx.inheritedAttrVars.add(`__VLS_intrinsicElements.${node.tag}`);
}
(0, styleScopedClasses_1.collectStyleScopedClassReferences)(options, ctx, node);
yield* (0, elementChildren_1.generateElementChildren)(options, ctx, node);
}
function* generateFailedPropExps(options, ctx, failedPropExps) {
for (const failedExp of failedPropExps) {
yield* (0, interpolation_1.generateInterpolation)(options, ctx, 'template', ctx.codeFeatures.all, failedExp.node.loc.source, failedExp.node.loc.start.offset, failedExp.node.loc, failedExp.prefix, failedExp.suffix);
yield utils_1.endOfLine;
}
}
function getCanonicalComponentName(tagText) {
return utils_1.identifierRegex.test(tagText)
? tagText
: (0, shared_1.capitalize)((0, shared_1.camelize)(tagText.replace(colonReg, '-')));
}
function getPossibleOriginalComponentNames(tagText, deduplicate) {
const name1 = (0, shared_1.capitalize)((0, shared_1.camelize)(tagText));
const name2 = (0, shared_1.camelize)(tagText);
const name3 = tagText;
const names = [name1];
if (!deduplicate || name2 !== name1) {
names.push(name2);
}
if (!deduplicate || name3 !== name2) {
names.push(name3);
}
return names;
}
function* generateCanonicalComponentName(tagText, offset, features) {
if (utils_1.identifierRegex.test(tagText)) {
yield [tagText, 'template', offset, features];
}
else {
yield* (0, camelized_1.generateCamelized)((0, shared_1.capitalize)(tagText.replace(colonReg, '-')), 'template', offset, features);
}
}
function* generateComponentGeneric(ctx) {
if (ctx.lastGenericComment) {
const { content, offset } = ctx.lastGenericComment;
yield* (0, wrapWith_1.wrapWith)(offset, offset + content.length, ctx.codeFeatures.verification, `<`, [
content,
'template',
offset,
ctx.codeFeatures.all
], `>`);
}
ctx.lastGenericComment = undefined;
}
function* generateElementReference(options, ctx, node) {
for (const prop of node.props) {
if (prop.type === CompilerDOM.NodeTypes.ATTRIBUTE
&& prop.name === 'ref'
&& prop.value) {
const [content, startOffset] = (0, utils_1.normalizeAttributeValue)(prop.value);
// navigation support for `const foo = ref()`
yield `/** @type {typeof __VLS_ctx`;
yield* (0, propertyAccess_1.generatePropertyAccess)(options, ctx, content, startOffset, ctx.codeFeatures.navigation, prop.value.loc);
yield `} */${utils_1.endOfLine}`;
if (utils_1.identifierRegex.test(content) && !options.templateRefNames.has(content)) {
ctx.accessExternalVariable(content, startOffset);
}
return [content, startOffset];
}
}
return [];
}
function hasVBindAttrs(options, ctx, node) {
return options.vueCompilerOptions.fallthroughAttributes && ((options.inheritAttrs && ctx.singleRootNodes.has(node)) ||
node.props.some(prop => prop.type === CompilerDOM.NodeTypes.DIRECTIVE
&& prop.name === 'bind'
&& prop.exp?.loc.source === '$attrs'));
}
function camelizeComponentName(newName) {
return (0, shared_1.camelize)('-' + newName);
}
function getTagRenameApply(oldName) {
return oldName === (0, shared_2.hyphenateTag)(oldName) ? shared_2.hyphenateTag : undefined;
}
//# sourceMappingURL=element.js.map

View File

@@ -0,0 +1,5 @@
import * as CompilerDOM from '@vue/compiler-dom';
import type { Code } from '../../types';
import type { TemplateCodegenContext } from './context';
import type { TemplateCodegenOptions } from './index';
export declare function generateElementChildren(options: TemplateCodegenOptions, ctx: TemplateCodegenContext, node: CompilerDOM.ElementNode): Generator<Code>;

View File

@@ -0,0 +1,14 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateElementChildren = generateElementChildren;
const templateChild_1 = require("./templateChild");
function* generateElementChildren(options, ctx, node) {
yield* ctx.resetDirectiveComments('end of element children start');
let prev;
for (const childNode of node.children) {
yield* (0, templateChild_1.generateTemplateChild)(options, ctx, childNode, prev);
prev = childNode;
}
yield* ctx.generateAutoImportCompletion();
}
//# sourceMappingURL=elementChildren.js.map

View File

@@ -0,0 +1,6 @@
import * as CompilerDOM from '@vue/compiler-dom';
import type { Code } from '../../types';
import type { TemplateCodegenContext } from './context';
import type { TemplateCodegenOptions } from './index';
export declare function generateElementDirectives(options: TemplateCodegenOptions, ctx: TemplateCodegenContext, node: CompilerDOM.ElementNode): Generator<Code>;
export declare function generateModifiers(options: TemplateCodegenOptions, ctx: TemplateCodegenContext, prop: CompilerDOM.DirectiveNode, propertyName?: string): Generator<Code>;

View File

@@ -0,0 +1,96 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateElementDirectives = generateElementDirectives;
exports.generateModifiers = generateModifiers;
const CompilerDOM = require("@vue/compiler-dom");
const shared_1 = require("@vue/shared");
const shared_2 = require("../../utils/shared");
const codeFeatures_1 = require("../codeFeatures");
const utils_1 = require("../utils");
const camelized_1 = require("../utils/camelized");
const stringLiteralKey_1 = require("../utils/stringLiteralKey");
const wrapWith_1 = require("../utils/wrapWith");
const elementProps_1 = require("./elementProps");
const interpolation_1 = require("./interpolation");
const objectProperty_1 = require("./objectProperty");
const builtInDirectives = new Set([
'cloak',
'html',
'memo',
'once',
'show',
'text',
]);
function* generateElementDirectives(options, ctx, node) {
for (const prop of node.props) {
if (prop.type !== CompilerDOM.NodeTypes.DIRECTIVE
|| prop.name === 'slot'
|| prop.name === 'on'
|| prop.name === 'model'
|| prop.name === 'bind'
|| prop.name === 'scope'
|| prop.name === 'data') {
continue;
}
ctx.accessExternalVariable((0, shared_1.camelize)('v-' + prop.name), prop.loc.start.offset);
yield* (0, wrapWith_1.wrapWith)(prop.loc.start.offset, prop.loc.end.offset, ctx.codeFeatures.verification, `__VLS_asFunctionalDirective(`, ...generateIdentifier(options, ctx, prop), `)(null!, { ...__VLS_directiveBindingRestFields, `, ...generateArg(options, ctx, prop), ...generateModifiers(options, ctx, prop), ...generateValue(options, ctx, prop), ` }, null!, null!)`);
yield utils_1.endOfLine;
}
}
function* generateIdentifier(options, ctx, prop) {
const rawName = 'v-' + prop.name;
yield* (0, wrapWith_1.wrapWith)(prop.loc.start.offset, prop.loc.start.offset + rawName.length, ctx.codeFeatures.verification, `__VLS_directives.`, ...(0, camelized_1.generateCamelized)(rawName, 'template', prop.loc.start.offset, ctx.resolveCodeFeatures({
...codeFeatures_1.codeFeatures.withoutHighlight,
// fix https://github.com/vuejs/language-tools/issues/1905
...codeFeatures_1.codeFeatures.additionalCompletion,
verification: options.vueCompilerOptions.checkUnknownDirectives && !builtInDirectives.has(prop.name),
navigation: {
resolveRenameNewName: shared_1.camelize,
resolveRenameEditText: getPropRenameApply(prop.name),
},
})));
}
function* generateArg(options, ctx, prop) {
const { arg } = prop;
if (arg?.type !== CompilerDOM.NodeTypes.SIMPLE_EXPRESSION) {
return;
}
const startOffset = arg.loc.start.offset + arg.loc.source.indexOf(arg.content);
yield* (0, wrapWith_1.wrapWith)(startOffset, startOffset + arg.content.length, ctx.codeFeatures.verification, `arg`);
yield `: `;
if (arg.isStatic) {
yield* (0, stringLiteralKey_1.generateStringLiteralKey)(arg.content, startOffset, ctx.codeFeatures.all);
}
else {
yield* (0, interpolation_1.generateInterpolation)(options, ctx, 'template', ctx.codeFeatures.all, arg.content, startOffset, arg.loc, `(`, `)`);
}
yield `, `;
}
function* generateModifiers(options, ctx, prop, propertyName = 'modifiers') {
const { modifiers } = prop;
if (!modifiers.length) {
return;
}
const startOffset = modifiers[0].loc.start.offset - 1;
const endOffset = modifiers.at(-1).loc.end.offset;
yield* (0, wrapWith_1.wrapWith)(startOffset, endOffset, ctx.codeFeatures.verification, propertyName);
yield `: { `;
for (const mod of modifiers) {
yield* (0, objectProperty_1.generateObjectProperty)(options, ctx, mod.content, mod.loc.start.offset, ctx.codeFeatures.withoutHighlightAndNavigation);
yield `: true, `;
}
yield `}, `;
}
function* generateValue(options, ctx, prop) {
const { exp } = prop;
if (exp?.type !== CompilerDOM.NodeTypes.SIMPLE_EXPRESSION) {
return;
}
yield* (0, wrapWith_1.wrapWith)(exp.loc.start.offset, exp.loc.end.offset, ctx.codeFeatures.verification, `value`);
yield `: `;
yield* (0, elementProps_1.generatePropExp)(options, ctx, prop, exp, ctx.codeFeatures.all);
}
function getPropRenameApply(oldName) {
return oldName === (0, shared_2.hyphenateAttr)(oldName) ? shared_2.hyphenateAttr : undefined;
}
//# sourceMappingURL=elementDirectives.js.map

View File

@@ -0,0 +1,9 @@
import * as CompilerDOM from '@vue/compiler-dom';
import type * as ts from 'typescript';
import type { Code } from '../../types';
import type { TemplateCodegenContext } from './context';
import type { TemplateCodegenOptions } from './index';
export declare function generateElementEvents(options: TemplateCodegenOptions, ctx: TemplateCodegenContext, node: CompilerDOM.ElementNode, componentFunctionalVar: string, componentVNodeVar: string, componentCtxVar: string): Generator<Code>;
export declare function generateEventArg(ctx: TemplateCodegenContext, name: string, start: number, directive?: string): Generator<Code>;
export declare function generateEventExpression(options: TemplateCodegenOptions, ctx: TemplateCodegenContext, prop: CompilerDOM.DirectiveNode): Generator<Code>;
export declare function isCompoundExpression(ts: typeof import('typescript'), ast: ts.SourceFile): boolean;

View File

@@ -0,0 +1,139 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateElementEvents = generateElementEvents;
exports.generateEventArg = generateEventArg;
exports.generateEventExpression = generateEventExpression;
exports.isCompoundExpression = isCompoundExpression;
const CompilerDOM = require("@vue/compiler-dom");
const shared_1 = require("@vue/shared");
const utils_1 = require("../utils");
const camelized_1 = require("../utils/camelized");
const wrapWith_1 = require("../utils/wrapWith");
const interpolation_1 = require("./interpolation");
function* generateElementEvents(options, ctx, node, componentFunctionalVar, componentVNodeVar, componentCtxVar) {
let emitVar;
let eventsVar;
let propsVar;
for (const prop of node.props) {
if (prop.type === CompilerDOM.NodeTypes.DIRECTIVE
&& prop.name === 'on'
&& prop.arg?.type === CompilerDOM.NodeTypes.SIMPLE_EXPRESSION
&& prop.arg.isStatic) {
ctx.currentComponent.used = true;
if (!emitVar) {
emitVar = ctx.getInternalVariable();
eventsVar = ctx.getInternalVariable();
propsVar = ctx.getInternalVariable();
yield `let ${emitVar}!: typeof ${componentCtxVar}.emit${utils_1.endOfLine}`;
yield `let ${eventsVar}!: __VLS_NormalizeEmits<typeof ${emitVar}>${utils_1.endOfLine}`;
yield `let ${propsVar}!: __VLS_FunctionalComponentProps<typeof ${componentFunctionalVar}, typeof ${componentVNodeVar}>${utils_1.endOfLine}`;
}
let source = prop.arg.loc.source;
let start = prop.arg.loc.start.offset;
let propPrefix = 'on';
let emitPrefix = '';
if (source.startsWith('vue:')) {
source = source.slice('vue:'.length);
start = start + 'vue:'.length;
propPrefix = 'onVnode';
emitPrefix = 'vnode-';
}
yield `const ${ctx.getInternalVariable()}: __VLS_NormalizeComponentEvent<typeof ${propsVar}, typeof ${eventsVar}, '${(0, shared_1.camelize)(propPrefix + '-' + source)}', '${emitPrefix}${source}', '${(0, shared_1.camelize)(emitPrefix + source)}'> = {${utils_1.newLine}`;
yield* generateEventArg(ctx, source, start, propPrefix);
yield `: `;
yield* generateEventExpression(options, ctx, prop);
yield `}${utils_1.endOfLine}`;
}
}
}
function* generateEventArg(ctx, name, start, directive = 'on') {
const features = {
...ctx.codeFeatures.withoutHighlightAndCompletion,
...ctx.codeFeatures.navigationWithoutRename,
};
if (utils_1.identifierRegex.test((0, shared_1.camelize)(name))) {
yield ['', 'template', start, features];
yield directive;
yield* (0, camelized_1.generateCamelized)((0, shared_1.capitalize)(name), 'template', start, utils_1.combineLastMapping);
}
else {
yield* (0, wrapWith_1.wrapWith)(start, start + name.length, features, `'`, directive, ...(0, camelized_1.generateCamelized)((0, shared_1.capitalize)(name), 'template', start, utils_1.combineLastMapping), `'`);
}
}
function* generateEventExpression(options, ctx, prop) {
if (prop.exp?.type === CompilerDOM.NodeTypes.SIMPLE_EXPRESSION) {
let prefix = `(`;
let suffix = `)`;
let isFirstMapping = true;
const ast = (0, utils_1.createTsAst)(options.ts, prop.exp, prop.exp.content);
const _isCompoundExpression = isCompoundExpression(options.ts, ast);
if (_isCompoundExpression) {
yield `(...[$event]) => {${utils_1.newLine}`;
ctx.addLocalVariable('$event');
yield* ctx.generateConditionGuards();
prefix = ``;
suffix = ``;
}
yield* (0, interpolation_1.generateInterpolation)(options, ctx, 'template', offset => {
if (_isCompoundExpression && isFirstMapping) {
isFirstMapping = false;
ctx.inlayHints.push({
blockName: 'template',
offset,
setting: 'vue.inlayHints.inlineHandlerLeading',
label: '$event =>',
paddingRight: true,
tooltip: [
'`$event` is a hidden parameter, you can use it in this callback.',
'To hide this hint, set `vue.inlayHints.inlineHandlerLeading` to `false` in IDE settings.',
'[More info](https://github.com/vuejs/language-tools/issues/2445#issuecomment-1444771420)',
].join('\n\n'),
});
}
return ctx.codeFeatures.all;
}, prop.exp.content, prop.exp.loc.start.offset, prop.exp.loc, prefix, suffix);
if (_isCompoundExpression) {
ctx.removeLocalVariable('$event');
yield utils_1.endOfLine;
yield* ctx.generateAutoImportCompletion();
yield `}`;
}
}
else {
yield `() => {}`;
}
}
function isCompoundExpression(ts, ast) {
let result = true;
if (ast.statements.length === 0) {
result = false;
}
else if (ast.statements.length === 1) {
ts.forEachChild(ast, child_1 => {
if (ts.isExpressionStatement(child_1)) {
ts.forEachChild(child_1, child_2 => {
if (ts.isArrowFunction(child_2)) {
result = false;
}
else if (isPropertyAccessOrId(ts, child_2)) {
result = false;
}
});
}
else if (ts.isFunctionDeclaration(child_1)) {
result = false;
}
});
}
return result;
}
function isPropertyAccessOrId(ts, node) {
if (ts.isIdentifier(node)) {
return true;
}
if (ts.isPropertyAccessExpression(node)) {
return isPropertyAccessOrId(ts, node.expression);
}
return false;
}
//# sourceMappingURL=elementEvents.js.map

View File

@@ -0,0 +1,11 @@
import * as CompilerDOM from '@vue/compiler-dom';
import type { Code, VueCodeInformation } from '../../types';
import type { TemplateCodegenContext } from './context';
import type { TemplateCodegenOptions } from './index';
export interface FailedPropExpression {
node: CompilerDOM.SimpleExpressionNode;
prefix: string;
suffix: string;
}
export declare function generateElementProps(options: TemplateCodegenOptions, ctx: TemplateCodegenContext, node: CompilerDOM.ElementNode, props: CompilerDOM.ElementNode['props'], strictPropsCheck: boolean, enableCodeFeatures: boolean, failedPropExps?: FailedPropExpression[]): Generator<Code>;
export declare function generatePropExp(options: TemplateCodegenOptions, ctx: TemplateCodegenContext, prop: CompilerDOM.DirectiveNode, exp: CompilerDOM.SimpleExpressionNode | undefined, features: VueCodeInformation, enableCodeFeatures?: boolean): Generator<Code>;

View File

@@ -0,0 +1,284 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateElementProps = generateElementProps;
exports.generatePropExp = generatePropExp;
const CompilerDOM = require("@vue/compiler-dom");
const shared_1 = require("@vue/shared");
const minimatch_1 = require("minimatch");
const muggle_string_1 = require("muggle-string");
const shared_2 = require("../../utils/shared");
const codeFeatures_1 = require("../codeFeatures");
const inlayHints_1 = require("../inlayHints");
const utils_1 = require("../utils");
const camelized_1 = require("../utils/camelized");
const unicode_1 = require("../utils/unicode");
const wrapWith_1 = require("../utils/wrapWith");
const elementDirectives_1 = require("./elementDirectives");
const elementEvents_1 = require("./elementEvents");
const interpolation_1 = require("./interpolation");
const objectProperty_1 = require("./objectProperty");
function* generateElementProps(options, ctx, node, props, strictPropsCheck, enableCodeFeatures, failedPropExps) {
const isComponent = node.tagType === CompilerDOM.ElementTypes.COMPONENT;
for (const prop of props) {
if (prop.type === CompilerDOM.NodeTypes.DIRECTIVE
&& prop.name === 'on') {
if (prop.arg?.type === CompilerDOM.NodeTypes.SIMPLE_EXPRESSION
&& !prop.arg.loc.source.startsWith('[')
&& !prop.arg.loc.source.endsWith(']')) {
if (!isComponent) {
yield `...{ `;
yield* (0, elementEvents_1.generateEventArg)(ctx, prop.arg.loc.source, prop.arg.loc.start.offset);
yield `: `;
yield* (0, elementEvents_1.generateEventExpression)(options, ctx, prop);
yield `},`;
}
else {
yield `...{ '${(0, shared_1.camelize)('on-' + prop.arg.loc.source)}': {} as any },`;
}
yield utils_1.newLine;
}
else if (prop.arg?.type === CompilerDOM.NodeTypes.SIMPLE_EXPRESSION
&& prop.exp?.type === CompilerDOM.NodeTypes.SIMPLE_EXPRESSION
&& prop.arg.loc.source.startsWith('[')
&& prop.arg.loc.source.endsWith(']')) {
failedPropExps?.push({ node: prop.arg, prefix: `(`, suffix: `)` });
failedPropExps?.push({ node: prop.exp, prefix: `() => {`, suffix: `}` });
}
else if (!prop.arg
&& prop.exp?.type === CompilerDOM.NodeTypes.SIMPLE_EXPRESSION) {
failedPropExps?.push({ node: prop.exp, prefix: `(`, suffix: `)` });
}
}
}
for (const prop of props) {
if (prop.type === CompilerDOM.NodeTypes.DIRECTIVE
&& ((prop.name === 'bind' && prop.arg?.type === CompilerDOM.NodeTypes.SIMPLE_EXPRESSION)
|| prop.name === 'model')
&& (!prop.exp || prop.exp.type === CompilerDOM.NodeTypes.SIMPLE_EXPRESSION)) {
let propName;
if (prop.arg?.type === CompilerDOM.NodeTypes.SIMPLE_EXPRESSION) {
propName = prop.arg.constType === CompilerDOM.ConstantTypes.CAN_STRINGIFY
? prop.arg.content
: prop.arg.loc.source;
}
else {
propName = getModelPropName(node, options.vueCompilerOptions);
}
if (propName === undefined
|| options.vueCompilerOptions.dataAttributes.some(pattern => (0, minimatch_1.minimatch)(propName, pattern))) {
if (prop.exp && prop.exp.constType !== CompilerDOM.ConstantTypes.CAN_STRINGIFY) {
failedPropExps?.push({ node: prop.exp, prefix: `(`, suffix: `)` });
}
continue;
}
if (prop.name === 'bind'
&& prop.modifiers.some(m => m.content === 'prop' || m.content === 'attr')) {
propName = propName.slice(1);
}
const shouldSpread = propName === 'style' || propName === 'class';
const shouldCamelize = isComponent && getShouldCamelize(options, prop, propName);
const codeInfo = getPropsCodeInfo(ctx, strictPropsCheck, shouldCamelize);
if (shouldSpread) {
yield `...{ `;
}
const codes = [...(0, wrapWith_1.wrapWith)(prop.loc.start.offset, prop.loc.end.offset, ctx.codeFeatures.verification, ...(prop.arg
? (0, objectProperty_1.generateObjectProperty)(options, ctx, propName, prop.arg.loc.start.offset, codeInfo, prop.loc.name_2 ??= {}, shouldCamelize)
: (0, wrapWith_1.wrapWith)(prop.loc.start.offset, prop.loc.start.offset + 'v-model'.length, ctx.codeFeatures.withoutHighlightAndCompletion, propName)), `: `, ...generatePropExp(options, ctx, prop, prop.exp, ctx.codeFeatures.all, enableCodeFeatures))];
if (enableCodeFeatures) {
yield* codes;
}
else {
yield (0, muggle_string_1.toString)(codes);
}
if (shouldSpread) {
yield ` }`;
}
yield `,${utils_1.newLine}`;
if (isComponent && prop.name === 'model' && prop.modifiers.length) {
const propertyName = prop.arg?.type === CompilerDOM.NodeTypes.SIMPLE_EXPRESSION
? !prop.arg.isStatic
? `[__VLS_tryAsConstant(\`$\{${prop.arg.content}\}Modifiers\`)]`
: (0, shared_1.camelize)(propName) + `Modifiers`
: `modelModifiers`;
const codes = [...(0, elementDirectives_1.generateModifiers)(options, ctx, prop, propertyName)];
if (enableCodeFeatures) {
yield* codes;
}
else {
yield (0, muggle_string_1.toString)(codes);
}
yield utils_1.newLine;
}
}
else if (prop.type === CompilerDOM.NodeTypes.ATTRIBUTE) {
if (options.vueCompilerOptions.dataAttributes.some(pattern => (0, minimatch_1.minimatch)(prop.name, pattern))
// Vue 2 Transition doesn't support "persisted" property but `@vue/compiler-dom` always adds it (#3881)
|| (options.vueCompilerOptions.target < 3
&& prop.name === 'persisted'
&& node.tag.toLowerCase() === 'transition')) {
continue;
}
const shouldSpread = prop.name === 'style' || prop.name === 'class';
const shouldCamelize = isComponent && getShouldCamelize(options, prop, prop.name);
const codeInfo = getPropsCodeInfo(ctx, strictPropsCheck, true);
if (shouldSpread) {
yield `...{ `;
}
const codes = [...(0, wrapWith_1.wrapWith)(prop.loc.start.offset, prop.loc.end.offset, ctx.codeFeatures.verification, ...(0, objectProperty_1.generateObjectProperty)(options, ctx, prop.name, prop.loc.start.offset, codeInfo, prop.loc.name_1 ??= {}, shouldCamelize), `: `, ...(prop.value
? generateAttrValue(prop.value, ctx.codeFeatures.withoutNavigation)
: [`true`]))];
if (enableCodeFeatures) {
yield* codes;
}
else {
yield (0, muggle_string_1.toString)(codes);
}
if (shouldSpread) {
yield ` }`;
}
yield `,${utils_1.newLine}`;
}
else if (prop.type === CompilerDOM.NodeTypes.DIRECTIVE
&& prop.name === 'bind'
&& !prop.arg
&& prop.exp?.type === CompilerDOM.NodeTypes.SIMPLE_EXPRESSION) {
if (prop.exp.loc.source === '$attrs') {
if (enableCodeFeatures) {
ctx.bindingAttrLocs.push(prop.exp.loc);
}
}
else {
const codes = [...(0, wrapWith_1.wrapWith)(prop.exp.loc.start.offset, prop.exp.loc.end.offset, ctx.codeFeatures.verification, `...`, ...generatePropExp(options, ctx, prop, prop.exp, ctx.codeFeatures.all, enableCodeFeatures))];
if (enableCodeFeatures) {
yield* codes;
}
else {
yield (0, muggle_string_1.toString)(codes);
}
yield `,${utils_1.newLine}`;
}
}
}
}
function* generatePropExp(options, ctx, prop, exp, features, enableCodeFeatures = true) {
const isShorthand = prop.arg?.loc.start.offset === prop.exp?.loc.start.offset;
if (isShorthand && features.completion) {
features = {
...features,
completion: undefined,
};
}
if (exp && exp.constType !== CompilerDOM.ConstantTypes.CAN_STRINGIFY) { // style='z-index: 2' will compile to {'z-index':'2'}
if (!isShorthand) { // vue 3.4+
yield* (0, interpolation_1.generateInterpolation)(options, ctx, 'template', features, exp.loc.source, exp.loc.start.offset, exp.loc, `(`, `)`);
}
else {
const propVariableName = (0, shared_1.camelize)(exp.loc.source);
if (utils_1.identifierRegex.test(propVariableName)) {
const isDestructuredProp = options.destructuredPropNames?.has(propVariableName) ?? false;
const isTemplateRef = options.templateRefNames?.has(propVariableName) ?? false;
const codes = (0, camelized_1.generateCamelized)(exp.loc.source, 'template', exp.loc.start.offset, features);
if (ctx.hasLocalVariable(propVariableName) || isDestructuredProp) {
yield* codes;
}
else {
ctx.accessExternalVariable(propVariableName, exp.loc.start.offset);
if (isTemplateRef) {
yield `__VLS_unref(`;
yield* codes;
yield `)`;
}
else {
yield `__VLS_ctx.`;
yield* codes;
}
}
if (enableCodeFeatures) {
ctx.inlayHints.push((0, inlayHints_1.createVBindShorthandInlayHintInfo)(prop.loc, propVariableName));
}
}
}
}
else {
yield `{}`;
}
}
function* generateAttrValue(attrNode, features) {
const quote = attrNode.loc.source.startsWith("'") ? "'" : '"';
yield quote;
let start = attrNode.loc.start.offset;
let content = attrNode.loc.source;
if ((content.startsWith('"') && content.endsWith('"'))
|| (content.startsWith("'") && content.endsWith("'"))) {
start++;
content = content.slice(1, -1);
}
yield* (0, unicode_1.generateUnicode)(content, start, features);
yield quote;
}
function getShouldCamelize(options, prop, propName) {
return (prop.type !== CompilerDOM.NodeTypes.DIRECTIVE
|| !prop.arg
|| (prop.arg?.type === CompilerDOM.NodeTypes.SIMPLE_EXPRESSION && prop.arg.isStatic))
&& (0, shared_2.hyphenateAttr)(propName) === propName
&& !options.vueCompilerOptions.htmlAttributes.some(pattern => (0, minimatch_1.minimatch)(propName, pattern));
}
function getPropsCodeInfo(ctx, strictPropsCheck, shouldCamelize) {
return ctx.resolveCodeFeatures({
...codeFeatures_1.codeFeatures.withoutHighlightAndCompletion,
navigation: {
resolveRenameNewName: shared_1.camelize,
resolveRenameEditText: shouldCamelize ? shared_2.hyphenateAttr : undefined,
},
verification: strictPropsCheck || {
shouldReport(_source, code) {
// https://typescript.tv/errors/#ts2353
// https://typescript.tv/errors/#ts2561
if (String(code) === '2353' || String(code) === '2561') {
return false;
}
return true;
},
},
});
}
function getModelPropName(node, vueCompilerOptions) {
for (const modelName in vueCompilerOptions.experimentalModelPropName) {
const tags = vueCompilerOptions.experimentalModelPropName[modelName];
for (const tag in tags) {
if (node.tag === tag || node.tag === (0, shared_2.hyphenateTag)(tag)) {
const val = tags[tag];
if (typeof val === 'object') {
const arr = Array.isArray(val) ? val : [val];
for (const attrs of arr) {
let failed = false;
for (const attr in attrs) {
const attrNode = node.props.find(prop => prop.type === CompilerDOM.NodeTypes.ATTRIBUTE && prop.name === attr);
if (!attrNode || attrNode.value?.content !== attrs[attr]) {
failed = true;
break;
}
}
if (!failed) {
// all match
return modelName || undefined;
}
}
}
}
}
}
for (const modelName in vueCompilerOptions.experimentalModelPropName) {
const tags = vueCompilerOptions.experimentalModelPropName[modelName];
for (const tag in tags) {
if (node.tag === tag || node.tag === (0, shared_2.hyphenateTag)(tag)) {
const attrs = tags[tag];
if (attrs === true) {
return modelName || undefined;
}
}
}
}
return vueCompilerOptions.target < 3 ? 'value' : 'modelValue';
}
//# sourceMappingURL=elementProps.js.map

View File

@@ -0,0 +1,22 @@
import * as CompilerDOM from '@vue/compiler-dom';
import type * as ts from 'typescript';
import type { Code, Sfc, VueCompilerOptions } from '../../types';
import { TemplateCodegenContext } from './context';
export interface TemplateCodegenOptions {
ts: typeof ts;
compilerOptions: ts.CompilerOptions;
vueCompilerOptions: VueCompilerOptions;
template: NonNullable<Sfc['template']>;
edited: boolean;
scriptSetupBindingNames: Set<string>;
scriptSetupImportComponentNames: Set<string>;
destructuredPropNames: Set<string>;
templateRefNames: Set<string>;
hasDefineSlots?: boolean;
slotsAssignName?: string;
propsAssignName?: string;
inheritAttrs: boolean;
selfComponentName?: string;
}
export declare function generateTemplate(options: TemplateCodegenOptions): Generator<Code, TemplateCodegenContext>;
export declare function forEachElementNode(node: CompilerDOM.RootNode | CompilerDOM.TemplateChildNode): Generator<CompilerDOM.ElementNode>;

View File

@@ -0,0 +1,151 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateTemplate = generateTemplate;
exports.forEachElementNode = forEachElementNode;
const CompilerDOM = require("@vue/compiler-dom");
const shared_1 = require("../../utils/shared");
const utils_1 = require("../utils");
const wrapWith_1 = require("../utils/wrapWith");
const context_1 = require("./context");
const objectProperty_1 = require("./objectProperty");
const styleScopedClasses_1 = require("./styleScopedClasses");
const templateChild_1 = require("./templateChild");
function* generateTemplate(options) {
const ctx = (0, context_1.createTemplateCodegenContext)(options);
if (options.slotsAssignName) {
ctx.addLocalVariable(options.slotsAssignName);
}
if (options.propsAssignName) {
ctx.addLocalVariable(options.propsAssignName);
}
const slotsPropertyName = (0, shared_1.getSlotsPropertyName)(options.vueCompilerOptions.target);
if (options.vueCompilerOptions.inferTemplateDollarSlots) {
ctx.dollarVars.add(slotsPropertyName);
}
if (options.vueCompilerOptions.inferTemplateDollarAttrs) {
ctx.dollarVars.add('$attrs');
}
if (options.vueCompilerOptions.inferTemplateDollarRefs) {
ctx.dollarVars.add('$refs');
}
if (options.vueCompilerOptions.inferTemplateDollarEl) {
ctx.dollarVars.add('$el');
}
if (options.template.ast) {
yield* (0, templateChild_1.generateTemplateChild)(options, ctx, options.template.ast, undefined);
}
yield* (0, styleScopedClasses_1.generateStyleScopedClassReferences)(ctx);
yield* ctx.generateAutoImportCompletion();
yield* ctx.generateHoistVariables();
const speicalTypes = [
[slotsPropertyName, yield* generateSlots(options, ctx)],
['$attrs', yield* generateInheritedAttrs(options, ctx)],
['$refs', yield* generateTemplateRefs(options, ctx)],
['$el', yield* generateRootEl(ctx)]
];
yield `var __VLS_dollars!: {${utils_1.newLine}`;
for (const [name, type] of speicalTypes) {
yield `${name}: ${type}${utils_1.endOfLine}`;
}
yield `} & { [K in keyof import('${options.vueCompilerOptions.lib}').ComponentPublicInstance]: unknown }${utils_1.endOfLine}`;
return ctx;
}
function* generateSlots(options, ctx) {
if (!options.hasDefineSlots) {
yield `type __VLS_Slots = {}`;
for (const { expVar, propsVar } of ctx.dynamicSlots) {
yield `${utils_1.newLine}& { [K in NonNullable<typeof ${expVar}>]?: (props: typeof ${propsVar}) => any }`;
}
for (const slot of ctx.slots) {
yield `${utils_1.newLine}& { `;
if (slot.name && slot.offset !== undefined) {
yield* (0, objectProperty_1.generateObjectProperty)(options, ctx, slot.name, slot.offset, ctx.codeFeatures.withoutHighlightAndCompletion, slot.nodeLoc);
}
else {
yield* (0, wrapWith_1.wrapWith)(slot.tagRange[0], slot.tagRange[1], ctx.codeFeatures.withoutHighlightAndCompletion, `default`);
}
yield `?: (props: typeof ${slot.propsVar}) => any }`;
}
yield `${utils_1.endOfLine}`;
}
return `__VLS_Slots`;
}
function* generateInheritedAttrs(options, ctx) {
yield `type __VLS_InheritedAttrs = {}`;
for (const varName of ctx.inheritedAttrVars) {
yield ` & typeof ${varName}`;
}
yield utils_1.endOfLine;
if (ctx.bindingAttrLocs.length) {
yield `[`;
for (const loc of ctx.bindingAttrLocs) {
yield `__VLS_dollars.`;
yield [
loc.source,
'template',
loc.start.offset,
ctx.codeFeatures.all
];
yield `,`;
}
yield `]${utils_1.endOfLine}`;
}
return `import('${options.vueCompilerOptions.lib}').ComponentPublicInstance['$attrs'] & Partial<__VLS_InheritedAttrs>`;
}
function* generateTemplateRefs(options, ctx) {
yield `type __VLS_TemplateRefs = {${utils_1.newLine}`;
for (const [name, { typeExp, offset }] of ctx.templateRefs) {
yield* (0, objectProperty_1.generateObjectProperty)(options, ctx, name, offset, ctx.codeFeatures.navigationAndCompletion);
yield `: ${typeExp},${utils_1.newLine}`;
}
yield `}${utils_1.endOfLine}`;
return `__VLS_TemplateRefs`;
}
function* generateRootEl(ctx) {
yield `type __VLS_RootEl = `;
if (ctx.singleRootElTypes.length && !ctx.singleRootNodes.has(null)) {
for (const type of ctx.singleRootElTypes) {
yield `${utils_1.newLine}| ${type}`;
}
}
else {
yield `any`;
}
yield utils_1.endOfLine;
return `__VLS_RootEl`;
}
function* forEachElementNode(node) {
if (node.type === CompilerDOM.NodeTypes.ROOT) {
for (const child of node.children) {
yield* forEachElementNode(child);
}
}
else if (node.type === CompilerDOM.NodeTypes.ELEMENT) {
const patchForNode = (0, templateChild_1.getVForNode)(node);
if (patchForNode) {
yield* forEachElementNode(patchForNode);
}
else {
yield node;
for (const child of node.children) {
yield* forEachElementNode(child);
}
}
}
else if (node.type === CompilerDOM.NodeTypes.IF) {
// v-if / v-else-if / v-else
for (let i = 0; i < node.branches.length; i++) {
const branch = node.branches[i];
for (const childNode of branch.children) {
yield* forEachElementNode(childNode);
}
}
}
else if (node.type === CompilerDOM.NodeTypes.FOR) {
// v-for
for (const child of node.children) {
yield* forEachElementNode(child);
}
}
}
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1,8 @@
import type * as ts from 'typescript';
import type { Code, VueCodeInformation } from '../../types';
import type { TemplateCodegenContext } from './context';
export declare function generateInterpolation(options: {
ts: typeof ts;
destructuredPropNames: Set<string> | undefined;
templateRefNames: Set<string> | undefined;
}, ctx: TemplateCodegenContext, source: string, data: VueCodeInformation | ((offset: number) => VueCodeInformation) | undefined, _code: string, start: number | undefined, astHolder?: any, prefix?: string, suffix?: string): Generator<Code>;

View File

@@ -0,0 +1,225 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateInterpolation = generateInterpolation;
const shared_1 = require("@vue/shared");
const scriptSetupRanges_1 = require("../../parsers/scriptSetupRanges");
const utils_1 = require("../utils");
function* generateInterpolation(options, ctx, source, data, _code, start, astHolder = {}, prefix = '', suffix = '') {
const code = prefix + _code + suffix;
const ast = (0, utils_1.createTsAst)(options.ts, astHolder, code);
for (let [section, offset, type] of forEachInterpolationSegment(options.ts, options.destructuredPropNames, options.templateRefNames, ctx, code, start !== undefined ? start - prefix.length : undefined, ast)) {
if (offset === undefined) {
yield section;
}
else {
offset -= prefix.length;
let addSuffix = '';
const overLength = offset + section.length - _code.length;
if (overLength > 0) {
addSuffix = section.slice(section.length - overLength);
section = section.slice(0, -overLength);
}
if (offset < 0) {
yield section.slice(0, -offset);
section = section.slice(-offset);
offset = 0;
}
const shouldSkip = section.length === 0 && (type === 'startText' || type === 'endText');
if (!shouldSkip) {
if (start !== undefined
&& data) {
yield [
section,
source,
start + offset,
type === 'errorMappingOnly'
? ctx.codeFeatures.verification
: typeof data === 'function' ? data(start + offset) : data,
];
}
else {
yield section;
}
}
yield addSuffix;
}
}
}
;
function* forEachInterpolationSegment(ts, destructuredPropNames, templateRefNames, ctx, code, offset, ast) {
let ctxVars = [];
const varCb = (id, isShorthand) => {
const text = (0, scriptSetupRanges_1.getNodeText)(ts, id, ast);
if (ctx.hasLocalVariable(text)
// https://github.com/vuejs/core/blob/245230e135152900189f13a4281302de45fdcfaa/packages/compiler-core/src/transforms/transformExpression.ts#L342-L352
|| (0, shared_1.isGloballyAllowed)(text)
|| text === 'require'
|| text.startsWith('__VLS_')) {
// localVarOffsets.push(localVar.getStart(ast));
}
else {
ctxVars.push({
text,
isShorthand: isShorthand,
offset: (0, scriptSetupRanges_1.getStartEnd)(ts, id, ast).start,
});
if (destructuredPropNames?.has(text)) {
return;
}
if (offset !== undefined) {
ctx.accessExternalVariable(text, offset + (0, scriptSetupRanges_1.getStartEnd)(ts, id, ast).start);
}
else {
ctx.accessExternalVariable(text);
}
}
};
ts.forEachChild(ast, node => walkIdentifiers(ts, node, ast, varCb, ctx));
ctxVars = ctxVars.sort((a, b) => a.offset - b.offset);
if (ctxVars.length) {
if (ctxVars[0].isShorthand) {
yield [code.slice(0, ctxVars[0].offset + ctxVars[0].text.length), 0];
yield [': ', undefined];
}
else if (ctxVars[0].offset > 0) {
yield [code.slice(0, ctxVars[0].offset), 0, 'startText'];
}
for (let i = 0; i < ctxVars.length - 1; i++) {
const curVar = ctxVars[i];
const nextVar = ctxVars[i + 1];
yield* generateVar(code, ctx.dollarVars, destructuredPropNames, templateRefNames, curVar);
if (nextVar.isShorthand) {
yield [code.slice(curVar.offset + curVar.text.length, nextVar.offset + nextVar.text.length), curVar.offset + curVar.text.length];
yield [': ', undefined];
}
else {
yield [code.slice(curVar.offset + curVar.text.length, nextVar.offset), curVar.offset + curVar.text.length];
}
}
const lastVar = ctxVars.at(-1);
yield* generateVar(code, ctx.dollarVars, destructuredPropNames, templateRefNames, lastVar);
if (lastVar.offset + lastVar.text.length < code.length) {
yield [code.slice(lastVar.offset + lastVar.text.length), lastVar.offset + lastVar.text.length, 'endText'];
}
}
else {
yield [code, 0];
}
}
function* generateVar(code, dollarVars, destructuredPropNames, templateRefNames, curVar) {
// fix https://github.com/vuejs/language-tools/issues/1205
// fix https://github.com/vuejs/language-tools/issues/1264
yield ['', curVar.offset, 'errorMappingOnly'];
const isDestructuredProp = destructuredPropNames?.has(curVar.text) ?? false;
const isTemplateRef = templateRefNames?.has(curVar.text) ?? false;
if (isTemplateRef) {
yield [`__VLS_unref(`, undefined];
yield [code.slice(curVar.offset, curVar.offset + curVar.text.length), curVar.offset];
yield [`)`, undefined];
}
else {
if (dollarVars.has(curVar.text)) {
yield [`__VLS_dollars.`, undefined];
}
else if (!isDestructuredProp) {
yield [`__VLS_ctx.`, undefined];
}
yield [code.slice(curVar.offset, curVar.offset + curVar.text.length), curVar.offset];
}
}
function walkIdentifiers(ts, node, ast, cb, ctx, blockVars = [], isRoot = true) {
if (ts.isIdentifier(node)) {
cb(node, false);
}
else if (ts.isShorthandPropertyAssignment(node)) {
cb(node.name, true);
}
else if (ts.isPropertyAccessExpression(node)) {
walkIdentifiers(ts, node.expression, ast, cb, ctx, blockVars, false);
}
else if (ts.isVariableDeclaration(node)) {
(0, utils_1.collectVars)(ts, node.name, ast, blockVars);
for (const varName of blockVars) {
ctx.addLocalVariable(varName);
}
if (node.initializer) {
walkIdentifiers(ts, node.initializer, ast, cb, ctx, blockVars, false);
}
}
else if (ts.isArrowFunction(node) || ts.isFunctionExpression(node)) {
processFunction(ts, node, ast, cb, ctx);
}
else if (ts.isObjectLiteralExpression(node)) {
for (const prop of node.properties) {
if (ts.isPropertyAssignment(prop)) {
// fix https://github.com/vuejs/language-tools/issues/1176
if (ts.isComputedPropertyName(prop.name)) {
walkIdentifiers(ts, prop.name.expression, ast, cb, ctx, blockVars, false);
}
walkIdentifiers(ts, prop.initializer, ast, cb, ctx, blockVars, false);
}
// fix https://github.com/vuejs/language-tools/issues/1156
else if (ts.isShorthandPropertyAssignment(prop)) {
walkIdentifiers(ts, prop, ast, cb, ctx, blockVars, false);
}
// fix https://github.com/vuejs/language-tools/issues/1148#issuecomment-1094378126
else if (ts.isSpreadAssignment(prop)) {
// TODO: cannot report "Spread types may only be created from object types.ts(2698)"
walkIdentifiers(ts, prop.expression, ast, cb, ctx, blockVars, false);
}
// fix https://github.com/vuejs/language-tools/issues/4604
else if (ts.isFunctionLike(prop) && prop.body) {
processFunction(ts, prop, ast, cb, ctx);
}
}
}
else if (ts.isTypeReferenceNode(node)) {
// fix https://github.com/vuejs/language-tools/issues/1422
ts.forEachChild(node, node => walkIdentifiersInTypeReference(ts, node, cb));
}
else {
const _blockVars = blockVars;
if (ts.isBlock(node)) {
blockVars = [];
}
ts.forEachChild(node, node => walkIdentifiers(ts, node, ast, cb, ctx, blockVars, false));
if (ts.isBlock(node)) {
for (const varName of blockVars) {
ctx.removeLocalVariable(varName);
}
}
blockVars = _blockVars;
}
if (isRoot) {
for (const varName of blockVars) {
ctx.removeLocalVariable(varName);
}
}
}
function processFunction(ts, node, ast, cb, ctx) {
const functionArgs = [];
for (const param of node.parameters) {
(0, utils_1.collectVars)(ts, param.name, ast, functionArgs);
if (param.type) {
walkIdentifiers(ts, param.type, ast, cb, ctx);
}
}
for (const varName of functionArgs) {
ctx.addLocalVariable(varName);
}
if (node.body) {
walkIdentifiers(ts, node.body, ast, cb, ctx);
}
for (const varName of functionArgs) {
ctx.removeLocalVariable(varName);
}
}
function walkIdentifiersInTypeReference(ts, node, cb) {
if (ts.isTypeQueryNode(node) && ts.isIdentifier(node.exprName)) {
cb(node.exprName, false);
}
else {
ts.forEachChild(node, node => walkIdentifiersInTypeReference(ts, node, cb));
}
}
//# sourceMappingURL=interpolation.js.map

View File

@@ -0,0 +1,4 @@
import type { Code, VueCodeInformation } from '../../types';
import type { TemplateCodegenContext } from './context';
import type { TemplateCodegenOptions } from './index';
export declare function generateObjectProperty(options: TemplateCodegenOptions, ctx: TemplateCodegenContext, code: string, offset: number, features: VueCodeInformation, astHolder?: any, shouldCamelize?: boolean, shouldBeConstant?: boolean): Generator<Code>;

View File

@@ -0,0 +1,36 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateObjectProperty = generateObjectProperty;
const shared_1 = require("@vue/shared");
const utils_1 = require("../utils");
const camelized_1 = require("../utils/camelized");
const stringLiteralKey_1 = require("../utils/stringLiteralKey");
const wrapWith_1 = require("../utils/wrapWith");
const interpolation_1 = require("./interpolation");
function* generateObjectProperty(options, ctx, code, offset, features, astHolder, shouldCamelize = false, shouldBeConstant = false) {
if (code.startsWith('[') && code.endsWith(']') && astHolder) {
if (shouldBeConstant) {
yield* (0, interpolation_1.generateInterpolation)(options, ctx, 'template', features, code.slice(1, -1), offset + 1, astHolder, `[__VLS_tryAsConstant(`, `)]`);
}
else {
yield* (0, interpolation_1.generateInterpolation)(options, ctx, 'template', features, code, offset, astHolder);
}
}
else if (shouldCamelize) {
if (utils_1.identifierRegex.test((0, shared_1.camelize)(code))) {
yield* (0, camelized_1.generateCamelized)(code, 'template', offset, features);
}
else {
yield* (0, wrapWith_1.wrapWith)(offset, offset + code.length, features, `'`, ...(0, camelized_1.generateCamelized)(code, 'template', offset, utils_1.combineLastMapping), `'`);
}
}
else {
if (utils_1.identifierRegex.test(code)) {
yield [code, 'template', offset, features];
}
else {
yield* (0, stringLiteralKey_1.generateStringLiteralKey)(code, offset, features);
}
}
}
//# sourceMappingURL=objectProperty.js.map

View File

@@ -0,0 +1,4 @@
import type { Code, VueCodeInformation } from '../../types';
import type { TemplateCodegenContext } from './context';
import type { TemplateCodegenOptions } from './index';
export declare function generatePropertyAccess(options: TemplateCodegenOptions, ctx: TemplateCodegenContext, code: string, offset?: number, features?: VueCodeInformation, astHolder?: any): Generator<Code>;

View File

@@ -0,0 +1,23 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generatePropertyAccess = generatePropertyAccess;
const utils_1 = require("../utils");
const stringLiteralKey_1 = require("../utils/stringLiteralKey");
const interpolation_1 = require("./interpolation");
function* generatePropertyAccess(options, ctx, code, offset, features, astHolder) {
if (!options.compilerOptions.noPropertyAccessFromIndexSignature && utils_1.identifierRegex.test(code)) {
yield `.`;
yield offset !== undefined && features
? [code, 'template', offset, features]
: code;
}
else if (code.startsWith('[') && code.endsWith(']')) {
yield* (0, interpolation_1.generateInterpolation)(options, ctx, 'template', features, code, offset, astHolder);
}
else {
yield `[`;
yield* (0, stringLiteralKey_1.generateStringLiteralKey)(code, offset, features);
yield `]`;
}
}
//# sourceMappingURL=propertyAccess.js.map

View File

@@ -0,0 +1,5 @@
import * as CompilerDOM from '@vue/compiler-dom';
import type { Code } from '../../types';
import type { TemplateCodegenContext } from './context';
import type { TemplateCodegenOptions } from './index';
export declare function generateSlotOutlet(options: TemplateCodegenOptions, ctx: TemplateCodegenContext, node: CompilerDOM.SlotOutletNode): Generator<Code>;

View File

@@ -0,0 +1,99 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateSlotOutlet = generateSlotOutlet;
const CompilerDOM = require("@vue/compiler-dom");
const inlayHints_1 = require("../inlayHints");
const utils_1 = require("../utils");
const wrapWith_1 = require("../utils/wrapWith");
const elementChildren_1 = require("./elementChildren");
const elementProps_1 = require("./elementProps");
const interpolation_1 = require("./interpolation");
const propertyAccess_1 = require("./propertyAccess");
function* generateSlotOutlet(options, ctx, node) {
const startTagOffset = node.loc.start.offset + options.template.content.slice(node.loc.start.offset).indexOf(node.tag);
const startTagEndOffset = startTagOffset + node.tag.length;
const propsVar = ctx.getInternalVariable();
const nameProp = node.props.find(prop => {
if (prop.type === CompilerDOM.NodeTypes.ATTRIBUTE) {
return prop.name === 'name';
}
if (prop.type === CompilerDOM.NodeTypes.DIRECTIVE
&& prop.name === 'bind'
&& prop.arg?.type === CompilerDOM.NodeTypes.SIMPLE_EXPRESSION) {
return prop.arg.content === 'name';
}
});
if (options.hasDefineSlots) {
yield `__VLS_asFunctionalSlot(`;
if (nameProp) {
let codes;
if (nameProp.type === CompilerDOM.NodeTypes.ATTRIBUTE && nameProp.value) {
let { source, start: { offset } } = nameProp.value.loc;
if (source.startsWith('"') || source.startsWith("'")) {
source = source.slice(1, -1);
offset++;
}
codes = (0, propertyAccess_1.generatePropertyAccess)(options, ctx, source, offset, ctx.codeFeatures.navigationAndVerification);
}
else if (nameProp.type === CompilerDOM.NodeTypes.DIRECTIVE
&& nameProp.exp?.type === CompilerDOM.NodeTypes.SIMPLE_EXPRESSION) {
codes = [
`[`,
...(0, elementProps_1.generatePropExp)(options, ctx, nameProp, nameProp.exp, ctx.codeFeatures.all),
`]`
];
}
else {
codes = [`['default']`];
}
yield* (0, wrapWith_1.wrapWith)(nameProp.loc.start.offset, nameProp.loc.end.offset, ctx.codeFeatures.verification, `${options.slotsAssignName ?? '__VLS_slots'}`, ...codes);
}
else {
yield* (0, wrapWith_1.wrapWith)(startTagOffset, startTagEndOffset, ctx.codeFeatures.verification, `${options.slotsAssignName ?? '__VLS_slots'}[`, ...(0, wrapWith_1.wrapWith)(startTagOffset, startTagEndOffset, ctx.codeFeatures.verification, `'default'`), `]`);
}
yield `)(`;
yield* (0, wrapWith_1.wrapWith)(startTagOffset, startTagEndOffset, ctx.codeFeatures.verification, `{${utils_1.newLine}`, ...(0, elementProps_1.generateElementProps)(options, ctx, node, node.props.filter(prop => prop !== nameProp), true, true), `}`);
yield `)${utils_1.endOfLine}`;
}
else {
yield `var ${propsVar} = {${utils_1.newLine}`;
yield* (0, elementProps_1.generateElementProps)(options, ctx, node, node.props.filter(prop => prop !== nameProp), options.vueCompilerOptions.checkUnknownProps, true);
yield `}${utils_1.endOfLine}`;
if (nameProp?.type === CompilerDOM.NodeTypes.ATTRIBUTE
&& nameProp.value) {
ctx.slots.push({
name: nameProp.value.content,
offset: nameProp.loc.start.offset + nameProp.loc.source.indexOf(nameProp.value.content, nameProp.name.length),
tagRange: [startTagOffset, startTagOffset + node.tag.length],
nodeLoc: node.loc,
propsVar: ctx.getHoistVariable(propsVar),
});
}
else if (nameProp?.type === CompilerDOM.NodeTypes.DIRECTIVE
&& nameProp.exp?.type === CompilerDOM.NodeTypes.SIMPLE_EXPRESSION) {
const isShortHand = nameProp.arg?.loc.start.offset === nameProp.exp.loc.start.offset;
if (isShortHand) {
ctx.inlayHints.push((0, inlayHints_1.createVBindShorthandInlayHintInfo)(nameProp.exp.loc, 'name'));
}
const expVar = ctx.getInternalVariable();
yield `var ${expVar} = __VLS_tryAsConstant(`;
yield* (0, interpolation_1.generateInterpolation)(options, ctx, 'template', ctx.codeFeatures.all, nameProp.exp.content, nameProp.exp.loc.start.offset, nameProp.exp);
yield `)${utils_1.endOfLine}`;
ctx.dynamicSlots.push({
expVar: ctx.getHoistVariable(expVar),
propsVar: ctx.getHoistVariable(propsVar),
});
}
else {
ctx.slots.push({
name: 'default',
tagRange: [startTagOffset, startTagEndOffset],
nodeLoc: node.loc,
propsVar: ctx.getHoistVariable(propsVar),
});
}
}
yield* ctx.generateAutoImportCompletion();
yield* (0, elementChildren_1.generateElementChildren)(options, ctx, node);
}
//# sourceMappingURL=slotOutlet.js.map

View File

@@ -0,0 +1,6 @@
import * as CompilerDOM from '@vue/compiler-dom';
import type { Code } from '../../types';
import type { TemplateCodegenContext } from './context';
import type { TemplateCodegenOptions } from './index';
export declare function generateStyleScopedClassReferences(ctx: TemplateCodegenContext, withDot?: boolean): Generator<Code>;
export declare function collectStyleScopedClassReferences(options: TemplateCodegenOptions, ctx: TemplateCodegenContext, node: CompilerDOM.ElementNode): void;

View File

@@ -0,0 +1,166 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateStyleScopedClassReferences = generateStyleScopedClassReferences;
exports.collectStyleScopedClassReferences = collectStyleScopedClassReferences;
const CompilerDOM = require("@vue/compiler-dom");
const scriptSetupRanges_1 = require("../../parsers/scriptSetupRanges");
const utils_1 = require("../utils");
const escaped_1 = require("../utils/escaped");
const wrapWith_1 = require("../utils/wrapWith");
const classNameEscapeRegex = /([\\'])/;
function* generateStyleScopedClassReferences(ctx, withDot = false) {
for (const offset of ctx.emptyClassOffsets) {
yield `/** @type {__VLS_StyleScopedClasses['`;
yield [
'',
'template',
offset,
ctx.codeFeatures.additionalCompletion,
];
yield `']} */${utils_1.endOfLine}`;
}
for (const { source, className, offset } of ctx.scopedClasses) {
yield `/** @type {__VLS_StyleScopedClasses[`;
yield* (0, wrapWith_1.wrapWith)(offset - (withDot ? 1 : 0), offset + className.length, source, ctx.codeFeatures.navigation, `'`, ...(0, escaped_1.generateEscaped)(className, source, offset, ctx.codeFeatures.navigationAndAdditionalCompletion, classNameEscapeRegex), `'`);
yield `]} */${utils_1.endOfLine}`;
}
}
function collectStyleScopedClassReferences(options, ctx, node) {
for (const prop of node.props) {
if (prop.type === CompilerDOM.NodeTypes.ATTRIBUTE
&& prop.name === 'class'
&& prop.value) {
if (options.template.lang === 'pug') {
const getClassOffset = Reflect.get(prop.value.loc.start, 'getClassOffset');
const content = prop.value.loc.source.slice(1, -1);
let startOffset = 1;
for (const className of content.split(' ')) {
if (className) {
ctx.scopedClasses.push({
source: 'template',
className,
offset: getClassOffset(startOffset),
});
}
startOffset += className.length + 1;
}
}
else {
let isWrapped = false;
const [content, startOffset] = (0, utils_1.normalizeAttributeValue)(prop.value);
if (content) {
const classes = collectClasses(content, startOffset + (isWrapped ? 1 : 0));
ctx.scopedClasses.push(...classes);
}
else {
ctx.emptyClassOffsets.push(startOffset);
}
}
}
else if (prop.type === CompilerDOM.NodeTypes.DIRECTIVE
&& prop.arg?.type === CompilerDOM.NodeTypes.SIMPLE_EXPRESSION
&& prop.exp?.type === CompilerDOM.NodeTypes.SIMPLE_EXPRESSION
&& prop.arg.content === 'class') {
const content = '`${' + prop.exp.content + '}`';
const startOffset = prop.exp.loc.start.offset - 3;
const { ts } = options;
const ast = ts.createSourceFile('', content, 99);
const literals = [];
ts.forEachChild(ast, node => {
if (!ts.isExpressionStatement(node) ||
!isTemplateExpression(node.expression)) {
return;
}
const expression = node.expression.templateSpans[0].expression;
if (ts.isStringLiteralLike(expression)) {
literals.push(expression);
}
if (ts.isArrayLiteralExpression(expression)) {
walkArrayLiteral(expression);
}
if (ts.isObjectLiteralExpression(expression)) {
walkObjectLiteral(expression);
}
});
for (const literal of literals) {
if (literal.text) {
const classes = collectClasses(literal.text, literal.end - literal.text.length - 1 + startOffset);
ctx.scopedClasses.push(...classes);
}
else {
ctx.emptyClassOffsets.push(literal.end - 1 + startOffset);
}
}
function walkArrayLiteral(node) {
const { elements } = node;
for (const element of elements) {
if (ts.isStringLiteralLike(element)) {
literals.push(element);
}
else if (ts.isObjectLiteralExpression(element)) {
walkObjectLiteral(element);
}
}
}
function walkObjectLiteral(node) {
const { properties } = node;
for (const property of properties) {
if (ts.isPropertyAssignment(property)) {
const { name } = property;
if (ts.isIdentifier(name)) {
walkIdentifier(name);
}
else if (ts.isStringLiteral(name)) {
literals.push(name);
}
else if (ts.isComputedPropertyName(name)) {
const { expression } = name;
if (ts.isStringLiteralLike(expression)) {
literals.push(expression);
}
}
}
else if (ts.isShorthandPropertyAssignment(property)) {
walkIdentifier(property.name);
}
}
}
function walkIdentifier(node) {
const text = (0, scriptSetupRanges_1.getNodeText)(ts, node, ast);
ctx.scopedClasses.push({
source: 'template',
className: text,
offset: node.end - text.length + startOffset
});
}
}
}
}
function collectClasses(content, startOffset = 0) {
const classes = [];
let currentClassName = '';
let offset = 0;
for (const char of (content + ' ')) {
if (char.trim() === '') {
if (currentClassName !== '') {
classes.push({
source: 'template',
className: currentClassName,
offset: offset + startOffset
});
offset += currentClassName.length;
currentClassName = '';
}
offset += char.length;
}
else {
currentClassName += char;
}
}
return classes;
}
// isTemplateExpression is missing in tsc
function isTemplateExpression(node) {
return node.kind === 228;
}
//# sourceMappingURL=styleScopedClasses.js.map

View File

@@ -0,0 +1,7 @@
import * as CompilerDOM from '@vue/compiler-dom';
import type { Code } from '../../types';
import type { TemplateCodegenContext } from './context';
import type { TemplateCodegenOptions } from './index';
export declare function generateTemplateChild(options: TemplateCodegenOptions, ctx: TemplateCodegenContext, node: CompilerDOM.RootNode | CompilerDOM.TemplateChildNode | CompilerDOM.SimpleExpressionNode, prevNode: CompilerDOM.TemplateChildNode | undefined, isVForChild?: boolean): Generator<Code>;
export declare function getVForNode(node: CompilerDOM.ElementNode): CompilerDOM.ForNode | undefined;
export declare function parseInterpolationNode(node: CompilerDOM.InterpolationNode, template: string): readonly [string, number];

View File

@@ -0,0 +1,218 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateTemplateChild = generateTemplateChild;
exports.getVForNode = getVForNode;
exports.parseInterpolationNode = parseInterpolationNode;
const CompilerDOM = require("@vue/compiler-dom");
const shared_1 = require("../../utils/shared");
const utils_1 = require("../utils");
const element_1 = require("./element");
const interpolation_1 = require("./interpolation");
const slotOutlet_1 = require("./slotOutlet");
const vFor_1 = require("./vFor");
const vIf_1 = require("./vIf");
const vSlot_1 = require("./vSlot");
const commentDirectiveRegex = /^<!--\s*@vue-(?<name>[-\w]+)\b(?<content>[\s\S]*)-->$/;
// @ts-ignore
const transformContext = {
onError: () => { },
helperString: str => str.toString(),
replaceNode: () => { },
cacheHandlers: false,
prefixIdentifiers: false,
scopes: {
vFor: 0,
vOnce: 0,
vPre: 0,
vSlot: 0,
},
expressionPlugins: ['typescript'],
};
function* generateTemplateChild(options, ctx, node, prevNode, isVForChild = false) {
if (prevNode?.type === CompilerDOM.NodeTypes.COMMENT) {
const match = prevNode.loc.source.match(commentDirectiveRegex);
if (match) {
const { name, content } = match.groups;
switch (name) {
case 'skip': {
yield `// @vue-skip${utils_1.newLine}`;
return;
}
case 'ignore': {
yield* ctx.ignoreError();
break;
}
case 'expect-error': {
yield* ctx.expectError(prevNode);
break;
}
case 'generic': {
const text = content.trim();
if (text.startsWith('{') && text.endsWith('}')) {
ctx.lastGenericComment = {
content: text.slice(1, -1),
offset: prevNode.loc.start.offset + prevNode.loc.source.indexOf('{') + 1,
};
}
break;
}
}
}
}
const cur = node;
if (cur.codegenNode?.type === CompilerDOM.NodeTypes.JS_CACHE_EXPRESSION) {
cur.codegenNode = cur.codegenNode.value;
}
if (node.type === CompilerDOM.NodeTypes.ROOT) {
for (const item of collectSingleRootNodes(options, node.children)) {
ctx.singleRootNodes.add(item);
}
let prev;
for (const childNode of node.children) {
yield* generateTemplateChild(options, ctx, childNode, prev);
prev = childNode;
}
yield* ctx.resetDirectiveComments('end of root');
}
else if (node.type === CompilerDOM.NodeTypes.ELEMENT) {
const vForNode = getVForNode(node);
const vIfNode = getVIfNode(node);
if (vForNode) {
yield* (0, vFor_1.generateVFor)(options, ctx, vForNode);
}
else if (vIfNode) {
yield* (0, vIf_1.generateVIf)(options, ctx, vIfNode);
}
else if (node.tagType === CompilerDOM.ElementTypes.SLOT) {
yield* (0, slotOutlet_1.generateSlotOutlet)(options, ctx, node);
}
else {
const slotDir = node.props.find(p => p.type === CompilerDOM.NodeTypes.DIRECTIVE && p.name === 'slot');
if (node.tagType === CompilerDOM.ElementTypes.TEMPLATE
&& ctx.currentComponent
&& slotDir) {
yield* (0, vSlot_1.generateVSlot)(options, ctx, node, slotDir);
}
else if (node.tagType === CompilerDOM.ElementTypes.ELEMENT
|| node.tagType === CompilerDOM.ElementTypes.TEMPLATE) {
yield* (0, element_1.generateElement)(options, ctx, node, isVForChild);
}
else {
const { currentComponent } = ctx;
yield* (0, element_1.generateComponent)(options, ctx, node, isVForChild);
ctx.currentComponent = currentComponent;
}
}
}
else if (node.type === CompilerDOM.NodeTypes.TEXT_CALL) {
// {{ var }}
yield* generateTemplateChild(options, ctx, node.content, undefined);
}
else if (node.type === CompilerDOM.NodeTypes.COMPOUND_EXPRESSION) {
// {{ ... }} {{ ... }}
for (const childNode of node.children) {
if (typeof childNode === 'object') {
yield* generateTemplateChild(options, ctx, childNode, undefined);
}
}
}
else if (node.type === CompilerDOM.NodeTypes.INTERPOLATION) {
// {{ ... }}
const [content, start] = parseInterpolationNode(node, options.template.content);
yield* (0, interpolation_1.generateInterpolation)(options, ctx, 'template', ctx.codeFeatures.all, content, start, node.content.loc, `(`, `)${utils_1.endOfLine}`);
yield* ctx.resetDirectiveComments('end of INTERPOLATION');
}
else if (node.type === CompilerDOM.NodeTypes.IF) {
// v-if / v-else-if / v-else
yield* (0, vIf_1.generateVIf)(options, ctx, node);
}
else if (node.type === CompilerDOM.NodeTypes.FOR) {
// v-for
yield* (0, vFor_1.generateVFor)(options, ctx, node);
}
else if (node.type === CompilerDOM.NodeTypes.TEXT) {
// not needed progress
}
}
function* collectSingleRootNodes(options, children) {
if (children.length !== 1) {
// "null" is used to determine whether the component is not always has a single root
if (children.length > 1) {
yield null;
}
return;
}
const child = children[0];
if (child.type === CompilerDOM.NodeTypes.IF) {
for (const branch of child.branches) {
yield* collectSingleRootNodes(options, branch.children);
}
return;
}
else if (child.type !== CompilerDOM.NodeTypes.ELEMENT) {
return;
}
yield child;
const tag = (0, shared_1.hyphenateTag)(child.tag);
if (options.vueCompilerOptions.fallthroughComponentNames.includes(tag)) {
yield* collectSingleRootNodes(options, child.children);
}
}
// TODO: track https://github.com/vuejs/vue-next/issues/3498
function getVForNode(node) {
const forDirective = node.props.find((prop) => prop.type === CompilerDOM.NodeTypes.DIRECTIVE
&& prop.name === 'for');
if (forDirective) {
let forNode;
CompilerDOM.processFor(node, forDirective, transformContext, _forNode => {
forNode = { ..._forNode };
return undefined;
});
if (forNode) {
forNode.children = [{
...node,
props: node.props.filter(prop => prop !== forDirective),
}];
return forNode;
}
}
}
function getVIfNode(node) {
const ifDirective = node.props.find((prop) => prop.type === CompilerDOM.NodeTypes.DIRECTIVE
&& prop.name === 'if');
if (ifDirective) {
let ifNode;
CompilerDOM.processIf(node, ifDirective, transformContext, _ifNode => {
ifNode = { ..._ifNode };
return undefined;
});
if (ifNode) {
for (const branch of ifNode.branches) {
branch.children = [{
...node,
props: node.props.filter(prop => prop !== ifDirective),
}];
}
return ifNode;
}
}
}
function parseInterpolationNode(node, template) {
let content = node.content.loc.source;
let start = node.content.loc.start.offset;
let leftCharacter;
let rightCharacter;
// fix https://github.com/vuejs/language-tools/issues/1787
while ((leftCharacter = template.slice(start - 1, start)).trim() === '' && leftCharacter.length) {
start--;
content = leftCharacter + content;
}
while ((rightCharacter = template.slice(start + content.length, start + content.length + 1)).trim() === '' && rightCharacter.length) {
content = content + rightCharacter;
}
return [
content,
start,
];
}
//# sourceMappingURL=templateChild.js.map

View File

@@ -0,0 +1,12 @@
import * as CompilerDOM from '@vue/compiler-dom';
import type { Code } from '../../types';
import type { TemplateCodegenContext } from './context';
import type { TemplateCodegenOptions } from './index';
export declare function generateVFor(options: TemplateCodegenOptions, ctx: TemplateCodegenContext, node: CompilerDOM.ForNode): Generator<Code>;
export declare function parseVForNode(node: CompilerDOM.ForNode): {
leftExpressionRange: {
start: number;
end: number;
} | undefined;
leftExpressionText: string | undefined;
};

View File

@@ -0,0 +1,85 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateVFor = generateVFor;
exports.parseVForNode = parseVForNode;
const CompilerDOM = require("@vue/compiler-dom");
const utils_1 = require("../utils");
const interpolation_1 = require("./interpolation");
const templateChild_1 = require("./templateChild");
function* generateVFor(options, ctx, node) {
const { source } = node.parseResult;
const { leftExpressionRange, leftExpressionText } = parseVForNode(node);
const forBlockVars = [];
yield `for (const [`;
if (leftExpressionRange && leftExpressionText) {
const collectAst = (0, utils_1.createTsAst)(options.ts, node.parseResult, `const [${leftExpressionText}]`);
(0, utils_1.collectVars)(options.ts, collectAst, collectAst, forBlockVars);
yield [
leftExpressionText,
'template',
leftExpressionRange.start,
ctx.codeFeatures.all,
];
}
yield `] of `;
if (source.type === CompilerDOM.NodeTypes.SIMPLE_EXPRESSION) {
yield `__VLS_getVForSourceType(`;
yield* (0, interpolation_1.generateInterpolation)(options, ctx, 'template', ctx.codeFeatures.all, source.content, source.loc.start.offset, source.loc, `(`, `)`);
yield `!)`; // #3102
}
else {
yield `{} as any`;
}
yield `) {${utils_1.newLine}`;
for (const varName of forBlockVars) {
ctx.addLocalVariable(varName);
}
let isFragment = true;
for (const argument of node.codegenNode?.children.arguments ?? []) {
if (argument.type === CompilerDOM.NodeTypes.JS_FUNCTION_EXPRESSION
&& argument.returns?.type === CompilerDOM.NodeTypes.VNODE_CALL
&& argument.returns?.props?.type === CompilerDOM.NodeTypes.JS_OBJECT_EXPRESSION) {
if (argument.returns.tag !== CompilerDOM.FRAGMENT) {
isFragment = false;
continue;
}
for (const prop of argument.returns.props.properties) {
if (prop.value.type === CompilerDOM.NodeTypes.SIMPLE_EXPRESSION
&& !prop.value.isStatic) {
yield* (0, interpolation_1.generateInterpolation)(options, ctx, 'template', ctx.codeFeatures.all, prop.value.content, prop.value.loc.start.offset, prop.value.loc, `(`, `)`);
yield utils_1.endOfLine;
}
}
}
}
if (isFragment) {
yield* ctx.resetDirectiveComments('end of v-for start');
}
let prev;
for (const childNode of node.children) {
yield* (0, templateChild_1.generateTemplateChild)(options, ctx, childNode, prev, true);
prev = childNode;
}
for (const varName of forBlockVars) {
ctx.removeLocalVariable(varName);
}
yield* ctx.generateAutoImportCompletion();
yield `}${utils_1.newLine}`;
}
function parseVForNode(node) {
const { value, key, index } = node.parseResult;
const leftExpressionRange = (value || key || index)
? {
start: (value ?? key ?? index).loc.start.offset,
end: (index ?? key ?? value).loc.end.offset,
}
: undefined;
const leftExpressionText = leftExpressionRange
? node.loc.source.slice(leftExpressionRange.start - node.loc.start.offset, leftExpressionRange.end - node.loc.start.offset)
: undefined;
return {
leftExpressionRange,
leftExpressionText,
};
}
//# sourceMappingURL=vFor.js.map

View File

@@ -0,0 +1,5 @@
import * as CompilerDOM from '@vue/compiler-dom';
import type { Code } from '../../types';
import type { TemplateCodegenContext } from './context';
import type { TemplateCodegenOptions } from './index';
export declare function generateVIf(options: TemplateCodegenOptions, ctx: TemplateCodegenContext, node: CompilerDOM.IfNode): Generator<Code>;

View File

@@ -0,0 +1,53 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateVIf = generateVIf;
const CompilerDOM = require("@vue/compiler-dom");
const muggle_string_1 = require("muggle-string");
const utils_1 = require("../utils");
const interpolation_1 = require("./interpolation");
const templateChild_1 = require("./templateChild");
function* generateVIf(options, ctx, node) {
const originalBlockConditionsLength = ctx.blockConditions.length;
for (let i = 0; i < node.branches.length; i++) {
const branch = node.branches[i];
if (i === 0) {
yield `if `;
}
else if (branch.condition) {
yield `else if `;
}
else {
yield `else `;
}
let addedBlockCondition = false;
if (branch.condition?.type === CompilerDOM.NodeTypes.SIMPLE_EXPRESSION) {
const codes = [...(0, interpolation_1.generateInterpolation)(options, ctx, 'template', ctx.codeFeatures.all, branch.condition.content, branch.condition.loc.start.offset, branch.condition.loc, `(`, `)`)];
yield* codes;
ctx.blockConditions.push((0, muggle_string_1.toString)(codes));
addedBlockCondition = true;
yield ` `;
}
yield `{${utils_1.newLine}`;
if (isFragment(node)) {
yield* ctx.resetDirectiveComments('end of v-if start');
}
let prev;
for (const childNode of branch.children) {
yield* (0, templateChild_1.generateTemplateChild)(options, ctx, childNode, prev);
prev = childNode;
}
yield* ctx.generateAutoImportCompletion();
yield `}${utils_1.newLine}`;
if (addedBlockCondition) {
ctx.blockConditions[ctx.blockConditions.length - 1] = `!${ctx.blockConditions[ctx.blockConditions.length - 1]}`;
}
}
ctx.blockConditions.length = originalBlockConditionsLength;
}
function isFragment(node) {
return node.codegenNode
&& 'consequent' in node.codegenNode
&& 'tag' in node.codegenNode.consequent
&& node.codegenNode.consequent.tag === CompilerDOM.FRAGMENT;
}
//# sourceMappingURL=vIf.js.map

View File

@@ -0,0 +1,6 @@
import * as CompilerDOM from '@vue/compiler-dom';
import type { Code } from '../../types';
import type { TemplateCodegenContext } from './context';
import type { TemplateCodegenOptions } from './index';
export declare function generateVSlot(options: TemplateCodegenOptions, ctx: TemplateCodegenContext, node: CompilerDOM.ElementNode, slotDir: CompilerDOM.DirectiveNode): Generator<Code>;
export declare function generateImplicitDefaultSlot(ctx: TemplateCodegenContext, node: CompilerDOM.ElementNode): Generator<Code, void, any>;

View File

@@ -0,0 +1,93 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateVSlot = generateVSlot;
exports.generateImplicitDefaultSlot = generateImplicitDefaultSlot;
const CompilerDOM = require("@vue/compiler-dom");
const utils_1 = require("../utils");
const wrapWith_1 = require("../utils/wrapWith");
const objectProperty_1 = require("./objectProperty");
const templateChild_1 = require("./templateChild");
function* generateVSlot(options, ctx, node, slotDir) {
if (!ctx.currentComponent) {
return;
}
ctx.currentComponent.used = true;
const slotBlockVars = [];
yield `{${utils_1.newLine}`;
yield `const { `;
if (slotDir.arg?.type === CompilerDOM.NodeTypes.SIMPLE_EXPRESSION && slotDir.arg.content) {
yield* (0, objectProperty_1.generateObjectProperty)(options, ctx, slotDir.arg.loc.source, slotDir.arg.loc.start.offset, slotDir.arg.isStatic ? ctx.codeFeatures.withoutHighlight : ctx.codeFeatures.all, slotDir.arg.loc, false, true);
}
else {
yield* (0, wrapWith_1.wrapWith)(slotDir.loc.start.offset, slotDir.loc.start.offset + (slotDir.rawName?.length ?? 0), ctx.codeFeatures.withoutHighlightAndCompletion, `default`);
}
yield `: __VLS_thisSlot } = ${ctx.currentComponent.ctxVar}.slots!${utils_1.endOfLine}`;
if (slotDir.exp?.type === CompilerDOM.NodeTypes.SIMPLE_EXPRESSION) {
const slotAst = (0, utils_1.createTsAst)(options.ts, slotDir, `(${slotDir.exp.content}) => {}`);
(0, utils_1.collectVars)(options.ts, slotAst, slotAst, slotBlockVars);
if (!slotDir.exp.content.includes(':')) {
yield `const [`;
yield [
slotDir.exp.content,
'template',
slotDir.exp.loc.start.offset,
ctx.codeFeatures.all,
];
yield `] = __VLS_getSlotParams(__VLS_thisSlot)${utils_1.endOfLine}`;
}
else {
yield `const `;
yield [
slotDir.exp.content,
'template',
slotDir.exp.loc.start.offset,
ctx.codeFeatures.all,
];
yield ` = __VLS_getSlotParam(__VLS_thisSlot)${utils_1.endOfLine}`;
}
}
for (const varName of slotBlockVars) {
ctx.addLocalVariable(varName);
}
yield* ctx.resetDirectiveComments('end of slot children start');
let prev;
for (const childNode of node.children) {
yield* (0, templateChild_1.generateTemplateChild)(options, ctx, childNode, prev);
prev = childNode;
}
for (const varName of slotBlockVars) {
ctx.removeLocalVariable(varName);
}
let isStatic = true;
if (slotDir.arg?.type === CompilerDOM.NodeTypes.SIMPLE_EXPRESSION) {
isStatic = slotDir.arg.isStatic;
}
if (isStatic && !slotDir.arg) {
yield `${ctx.currentComponent.ctxVar}.slots!['`;
yield [
'',
'template',
slotDir.loc.start.offset + (slotDir.loc.source.startsWith('#')
? '#'.length
: slotDir.loc.source.startsWith('v-slot:')
? 'v-slot:'.length
: 0),
ctx.codeFeatures.completion,
];
yield `'/* empty slot name completion */]${utils_1.endOfLine}`;
}
yield* ctx.generateAutoImportCompletion();
yield `}${utils_1.newLine}`;
}
function* generateImplicitDefaultSlot(ctx, node) {
if (!ctx.currentComponent) {
return;
}
if (node.children.length) {
ctx.currentComponent.used = true;
yield `${ctx.currentComponent.ctxVar}.slots!.`;
yield* (0, wrapWith_1.wrapWith)(node.children[0].loc.start.offset, node.children[node.children.length - 1].loc.end.offset, ctx.codeFeatures.navigation, `default`);
yield utils_1.endOfLine;
}
}
//# sourceMappingURL=vSlot.js.map

Some files were not shown because too many files have changed in this diff Show More