Initial implementation

This commit is contained in:
Atharva Sawant
2024-02-15 16:47:23 +05:30
commit 4e1e2054a6
8439 changed files with 2230738 additions and 0 deletions

View File

@@ -0,0 +1,4 @@
import { VueCompilerOptions } from '../types';
export declare const baseName = "__VLS_types.d.ts";
export declare function getTypesCode(vueCompilerOptions: VueCompilerOptions): string;
//# sourceMappingURL=globalTypes.d.ts.map

View File

@@ -0,0 +1,135 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getTypesCode = exports.baseName = void 0;
const shared_1 = require("./shared");
exports.baseName = '__VLS_types.d.ts';
function getTypesCode(vueCompilerOptions) {
return `
// @ts-nocheck
type __VLS_IntrinsicElements = __VLS_PickNotAny<import('vue/jsx-runtime').JSX.IntrinsicElements, __VLS_PickNotAny<JSX.IntrinsicElements, Record<string, any>>>;
type __VLS_Element = __VLS_PickNotAny<import('vue/jsx-runtime').JSX.Element, JSX.Element>;
type __VLS_IsAny<T> = 0 extends 1 & T ? true : false;
type __VLS_PickNotAny<A, B> = __VLS_IsAny<A> extends true ? B : A;
type __VLS_Prettify<T> = { [K in keyof T]: T[K]; } & {};
type __VLS_OmitKeepDiscriminatedUnion<T, K extends keyof any> =
T extends any
? Pick<T, Exclude<keyof T, K>>
: never;
type __VLS_GlobalComponents =
__VLS_PickNotAny<import('vue').GlobalComponents, {}>
& __VLS_PickNotAny<import('@vue/runtime-core').GlobalComponents, {}>
& __VLS_PickNotAny<import('@vue/runtime-dom').GlobalComponents, {}>
& Pick<typeof import('${vueCompilerOptions.lib}'),
'Transition'
| 'TransitionGroup'
| 'KeepAlive'
| 'Suspense'
| 'Teleport'
>;
declare const __VLS_intrinsicElements: __VLS_IntrinsicElements;
// v-for
declare function __VLS_getVForSourceType(source: number): [number, number, number][];
declare function __VLS_getVForSourceType(source: string): [string, number, number][];
declare function __VLS_getVForSourceType<T extends any[]>(source: T): [
T[number], // item
number, // key
number, // index
][];
declare function __VLS_getVForSourceType<T extends { [Symbol.iterator](): Iterator<any> }>(source: T): [
T extends { [Symbol.iterator](): Iterator<infer T1> } ? T1 : never, // item
number, // key
undefined, // index
][];
declare function __VLS_getVForSourceType<T>(source: T): [
T[keyof T], // item
keyof T, // key
number, // index
][];
declare function __VLS_getSlotParams<T>(slot: T): Parameters<__VLS_PickNotAny<NonNullable<T>, (...args: any[]) => any>>;
declare function __VLS_getSlotParam<T>(slot: T): Parameters<__VLS_PickNotAny<NonNullable<T>, (...args: any[]) => any>>[0];
declare function __VLS_directiveFunction<T>(dir: T):
T extends import('${vueCompilerOptions.lib}').ObjectDirective<infer E, infer V> | import('${vueCompilerOptions.lib}').FunctionDirective<infer E, infer V> ? (value: V) => void
: T;
declare function __VLS_withScope<T, K>(ctx: T, scope: K): ctx is T & K;
declare function __VLS_makeOptional<T>(t: T): { [K in keyof T]?: T[K] };
type __VLS_SelfComponent<N, C> = string extends N ? {} : N extends string ? { [P in N]: C } : {};
type __VLS_WithComponent<N0 extends string, LocalComponents, N1 extends string, N2 extends string, N3 extends string> =
N1 extends keyof LocalComponents ? N1 extends N0 ? Pick<LocalComponents, N0> : { [K in N0]: LocalComponents[N1] } :
N2 extends keyof LocalComponents ? N2 extends N0 ? Pick<LocalComponents, N0> : { [K in N0]: LocalComponents[N2] } :
N3 extends keyof LocalComponents ? N3 extends N0 ? Pick<LocalComponents, N0> : { [K in N0]: LocalComponents[N3] } :
N1 extends keyof __VLS_GlobalComponents ? N1 extends N0 ? Pick<__VLS_GlobalComponents, N0> : { [K in N0]: __VLS_GlobalComponents[N1] } :
N2 extends keyof __VLS_GlobalComponents ? N2 extends N0 ? Pick<__VLS_GlobalComponents, N0> : { [K in N0]: __VLS_GlobalComponents[N2] } :
N3 extends keyof __VLS_GlobalComponents ? N3 extends N0 ? Pick<__VLS_GlobalComponents, N0> : { [K in N0]: __VLS_GlobalComponents[N3] } :
${vueCompilerOptions.strictTemplates ? '{}' : '{ [K in N0]: unknown }'}
type __VLS_FillingEventArg_ParametersLength<E extends (...args: any) => any> = __VLS_IsAny<Parameters<E>> extends true ? -1 : Parameters<E>['length'];
type __VLS_FillingEventArg<E> = E extends (...args: any) => any ? __VLS_FillingEventArg_ParametersLength<E> extends 0 ? ($event?: undefined) => ReturnType<E> : E : E;
declare 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: (K extends { $props: infer Props } ? Props : any)${vueCompilerOptions.strictTemplates ? '' : ' & Record<string, unknown>'}, ctx?: {
attrs?: any,
slots?: K extends { ${(0, shared_1.getSlotsPropertyName)(vueCompilerOptions.target)}: infer Slots } ? Slots : any,
emit?: K extends { $emit: infer Emit } ? Emit : any
}) => __VLS_Element & { __ctx?: typeof ctx & { props?: typeof props; expose?(exposed: K): void; } }
: T extends () => any ? (props: {}, ctx?: any) => ReturnType<T>
: T extends (...args: any) => any ? T
: (_: {}${vueCompilerOptions.strictTemplates ? '' : ' & Record<string, unknown>'}, ctx?: any) => { __ctx?: { attrs?: any, expose?: any, slots?: any, emit?: any, props?: {}${vueCompilerOptions.strictTemplates ? '' : ' & Record<string, unknown>'} } };
declare function __VLS_elementAsFunctionalComponent<T>(t: T): (_: T${vueCompilerOptions.strictTemplates ? '' : ' & Record<string, unknown>'}, ctx?: any) => { __ctx?: { attrs?: any, expose?: any, slots?: any, emit?: any, props?: T${vueCompilerOptions.strictTemplates ? '' : ' & Record<string, unknown>'} } };
declare function __VLS_functionalComponentArgsRest<T extends (...args: any) => any>(t: T): Parameters<T>['length'] extends 2 ? [any] : [];
declare function __VLS_pickEvent<E1, E2>(emitEvent: E1, propEvent: E2): __VLS_FillingEventArg<
__VLS_PickNotAny<
__VLS_AsFunctionOrAny<E2>,
__VLS_AsFunctionOrAny<E1>
>
> | undefined;
declare function __VLS_pickFunctionalComponentCtx<T, K>(comp: T, compInstance: K): __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_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_AsFunctionOrAny<F> = unknown extends F ? any : ((...args: any) => any) extends F ? F : any;
declare function __VLS_normalizeSlot<S>(s: S): S extends () => infer R ? (props: {}) => R : S;
/**
* emit
*/
// 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_Prettify<
__VLS_UnionToIntersection<
__VLS_ConstructorOverloads<T> & {
[K in keyof T]: T[K] extends any[] ? { (...args: T[K]): void } : never
}
>
>;
`.trim();
}
exports.getTypesCode = getTypesCode;
//# sourceMappingURL=globalTypes.js.map

View File

@@ -0,0 +1,5 @@
export declare function parseCssClassNames(styleContent: string): Generator<{
offset: number;
text: string;
}, void, unknown>;
//# sourceMappingURL=parseCssClassNames.d.ts.map

View File

@@ -0,0 +1,19 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseCssClassNames = void 0;
const parseCssVars_1 = require("./parseCssVars");
const cssClassNameReg = /(?=([\.]{1}[a-zA-Z_]+[\w\_\-]*)[\s\.\+\{\>#\:]{1})/g;
function* parseCssClassNames(styleContent) {
styleContent = (0, parseCssVars_1.clearComments)(styleContent);
const matches = styleContent.matchAll(cssClassNameReg);
for (const match of matches) {
if (match.index !== undefined) {
const matchText = match[1];
if (matchText !== undefined) {
yield { offset: match.index, text: matchText };
}
}
}
}
exports.parseCssClassNames = parseCssClassNames;
//# sourceMappingURL=parseCssClassNames.js.map

View File

@@ -0,0 +1,6 @@
export declare function parseCssVars(styleContent: string): Generator<{
offset: number;
text: string;
}, void, unknown>;
export declare function clearComments(css: string): string;
//# sourceMappingURL=parseCssVars.d.ts.map

View File

@@ -0,0 +1,28 @@
"use strict";
// https://github.com/vuejs/core/blob/main/packages/compiler-sfc/src/cssVars.ts#L47-L61
Object.defineProperty(exports, "__esModule", { value: true });
exports.clearComments = exports.parseCssVars = void 0;
const vBindCssVarReg = /\bv-bind\(\s*(?:'([^']+)'|"([^"]+)"|([^'"][^)]*))\s*\)/g;
const commentReg1 = /\/\*([\s\S]*?)\*\//g;
const commentReg2 = /\/\/([\s\S]*?)\n/g;
function* parseCssVars(styleContent) {
styleContent = clearComments(styleContent);
const matchs = styleContent.matchAll(vBindCssVarReg);
for (const match of matchs) {
if (match.index !== undefined) {
const matchText = match[1] ?? match[2] ?? match[3];
if (matchText !== undefined) {
const offset = match.index + styleContent.slice(match.index).indexOf(matchText);
yield { offset, text: matchText };
}
}
}
}
exports.parseCssVars = parseCssVars;
function clearComments(css) {
return css
.replace(commentReg1, match => `/*${' '.repeat(match.length - 4)}*/`)
.replace(commentReg2, match => `//${' '.repeat(match.length - 3)}\n`);
}
exports.clearComments = clearComments;
//# sourceMappingURL=parseCssVars.js.map

View File

@@ -0,0 +1,3 @@
import type { SFCParseResult } from '@vue/compiler-sfc';
export declare function parse(source: string): SFCParseResult;
//# sourceMappingURL=parseSfc.d.ts.map

135
node_modules/@vue/language-core/out/utils/parseSfc.js generated vendored Normal file
View File

@@ -0,0 +1,135 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parse = void 0;
const compiler = require("@vue/compiler-dom");
function parse(source) {
const errors = [];
const ast = compiler.parse(source, {
// there are no components at SFC parsing level
isNativeTag: () => true,
// preserve all whitespaces
isPreTag: () => true,
getTextMode: ({ tag, props }, parent) => {
if ((!parent && tag !== 'template')
|| (tag === 'template'
&& props.some(p => p.type === 6 /* compiler.NodeTypes.ATTRIBUTE */ &&
p.name === 'lang' &&
p.value &&
p.value.content &&
p.value.content !== 'html'))) {
return 2 /* compiler.TextModes.RAWTEXT */;
}
else {
return 0 /* compiler.TextModes.DATA */;
}
},
onError: e => {
errors.push(e);
},
comments: true,
});
const descriptor = {
filename: 'anonymous.vue',
source,
template: null,
script: null,
scriptSetup: null,
styles: [],
customBlocks: [],
cssVars: [],
slotted: false,
shouldForceReload: () => false,
};
ast.children.forEach(node => {
if (node.type !== 1 /* compiler.NodeTypes.ELEMENT */) {
return;
}
switch (node.tag) {
case 'template':
const templateBlock = (descriptor.template = createBlock(node, source));
templateBlock.ast = node;
break;
case 'script':
const scriptBlock = createBlock(node, source);
const isSetup = !!scriptBlock.attrs.setup;
if (isSetup && !descriptor.scriptSetup) {
descriptor.scriptSetup = scriptBlock;
break;
}
if (!isSetup && !descriptor.script) {
descriptor.script = scriptBlock;
break;
}
break;
case 'style':
const styleBlock = createBlock(node, source);
descriptor.styles.push(styleBlock);
break;
default:
descriptor.customBlocks.push(createBlock(node, source));
break;
}
});
return {
descriptor,
errors,
};
}
exports.parse = parse;
function createBlock(node, source) {
const type = node.tag;
let { start, end } = node.loc;
let content = '';
if (node.children.length) {
start = node.children[0].loc.start;
end = node.children[node.children.length - 1].loc.end;
content = source.slice(start.offset, end.offset);
}
else {
const offset = node.loc.source.indexOf(`</`);
if (offset > -1) {
start = {
line: start.line,
column: start.column + offset,
offset: start.offset + offset
};
}
end = Object.assign({}, start);
}
const loc = {
source: content,
start,
end
};
const attrs = {};
const block = {
type,
content,
loc,
attrs
};
node.props.forEach(p => {
if (p.type === 6 /* compiler.NodeTypes.ATTRIBUTE */) {
attrs[p.name] = p.value ? p.value.content || true : true;
if (p.name === 'lang') {
block.lang = p.value && p.value.content;
}
else if (p.name === 'src') {
block.src = p.value && p.value.content;
}
else if (type === 'style') {
if (p.name === 'scoped') {
block.scoped = true;
}
else if (p.name === 'module') {
block.module = attrs[p.name];
}
}
else if (type === 'script' && p.name === 'setup') {
block.setup = attrs.setup;
}
}
});
return block;
}
//# sourceMappingURL=parseSfc.js.map

View File

@@ -0,0 +1,4 @@
export declare function getSlotsPropertyName(vueVersion: number): "$scopedSlots" | "$slots";
export { hyphenate as hyphenateTag } from '@vue/shared';
export declare function hyphenateAttr(str: string): string;
//# sourceMappingURL=shared.d.ts.map

20
node_modules/@vue/language-core/out/utils/shared.js generated vendored Normal file
View File

@@ -0,0 +1,20 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.hyphenateAttr = exports.hyphenateTag = exports.getSlotsPropertyName = void 0;
const shared_1 = require("@vue/shared");
function getSlotsPropertyName(vueVersion) {
return vueVersion < 3 ? '$scopedSlots' : '$slots';
}
exports.getSlotsPropertyName = getSlotsPropertyName;
var shared_2 = require("@vue/shared");
Object.defineProperty(exports, "hyphenateTag", { enumerable: true, get: function () { return shared_2.hyphenate; } });
function hyphenateAttr(str) {
let hyphencase = (0, shared_1.hyphenate)(str);
// fix https://github.com/vuejs/core/issues/8811
if (str.length && str[0] !== str[0].toLowerCase()) {
hyphencase = '-' + hyphencase;
}
return hyphencase;
}
exports.hyphenateAttr = hyphenateAttr;
//# sourceMappingURL=shared.js.map

View File

@@ -0,0 +1,9 @@
import type * as ts from 'typescript/lib/tsserverlibrary';
import { VueCompilerOptions } from '../types';
export declare function walkInterpolationFragment(ts: typeof import('typescript/lib/tsserverlibrary'), code: string, ast: ts.SourceFile, cb: (fragment: string, offset: number | undefined, isJustForErrorMapping?: boolean) => void, localVars: Map<string, number>, identifiers: Set<string>, vueOptions: VueCompilerOptions): {
text: string;
isShorthand: boolean;
offset: number;
}[];
export declare function collectVars(ts: typeof import('typescript/lib/tsserverlibrary'), node: ts.Node, result: string[]): void;
//# sourceMappingURL=transform.d.ts.map

195
node_modules/@vue/language-core/out/utils/transform.js generated vendored Normal file
View File

@@ -0,0 +1,195 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.collectVars = exports.walkInterpolationFragment = void 0;
const shared_1 = require("@vue/shared");
function walkInterpolationFragment(ts, code, ast, cb, localVars, identifiers, vueOptions) {
let ctxVars = [];
const varCb = (id, isShorthand) => {
if (localVars.get(id.text) ||
// https://github.com/vuejs/core/blob/245230e135152900189f13a4281302de45fdcfaa/packages/compiler-core/src/transforms/transformExpression.ts#L342-L352
(0, shared_1.isGloballyWhitelisted)(id.text) ||
id.text === 'require' ||
id.text.startsWith('__VLS_')) {
// localVarOffsets.push(localVar.getStart(ast));
}
else {
ctxVars.push({
text: id.text,
isShorthand: isShorthand,
offset: id.getStart(ast),
});
identifiers.add(id.text);
}
};
ast.forEachChild(node => walkIdentifiers(ts, node, varCb, localVars));
ctxVars = ctxVars.sort((a, b) => a.offset - b.offset);
if (ctxVars.length) {
if (ctxVars[0].isShorthand) {
cb(code.substring(0, ctxVars[0].offset + ctxVars[0].text.length), 0);
cb(': ', undefined);
}
else {
cb(code.substring(0, ctxVars[0].offset), 0);
}
for (let i = 0; i < ctxVars.length - 1; i++) {
// fix https://github.com/vuejs/language-tools/issues/1205
// fix https://github.com/vuejs/language-tools/issues/1264
cb('', ctxVars[i + 1].offset, true);
if (vueOptions.experimentalUseElementAccessInTemplate) {
const varStart = ctxVars[i].offset;
const varEnd = ctxVars[i].offset + ctxVars[i].text.length;
cb('__VLS_ctx[', undefined);
cb('', varStart, true);
cb("'", undefined);
cb(code.substring(varStart, varEnd), varStart);
cb("'", undefined);
cb('', varEnd, true);
cb(']', undefined);
if (ctxVars[i + 1].isShorthand) {
cb(code.substring(varEnd, ctxVars[i + 1].offset + ctxVars[i + 1].text.length), varEnd);
cb(': ', undefined);
}
else {
cb(code.substring(varEnd, ctxVars[i + 1].offset), varEnd);
}
}
else {
cb('__VLS_ctx.', undefined);
if (ctxVars[i + 1].isShorthand) {
cb(code.substring(ctxVars[i].offset, ctxVars[i + 1].offset + ctxVars[i + 1].text.length), ctxVars[i].offset);
cb(': ', undefined);
}
else {
cb(code.substring(ctxVars[i].offset, ctxVars[i + 1].offset), ctxVars[i].offset);
}
}
}
if (vueOptions.experimentalUseElementAccessInTemplate) {
const varStart = ctxVars[ctxVars.length - 1].offset;
const varEnd = ctxVars[ctxVars.length - 1].offset + ctxVars[ctxVars.length - 1].text.length;
cb('__VLS_ctx[', undefined);
cb('', varStart, true);
cb("'", undefined);
cb(code.substring(varStart, varEnd), varStart);
cb("'", undefined);
cb('', varEnd, true);
cb(']', undefined);
cb(code.substring(varEnd), varEnd);
}
else {
cb('', ctxVars[ctxVars.length - 1].offset, true);
cb('__VLS_ctx.', undefined);
cb(code.substring(ctxVars[ctxVars.length - 1].offset), ctxVars[ctxVars.length - 1].offset);
}
}
else {
cb(code, 0);
}
return ctxVars;
}
exports.walkInterpolationFragment = walkInterpolationFragment;
function walkIdentifiers(ts, node, cb, localVars, 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, cb, localVars, blockVars, false);
}
else if (ts.isVariableDeclaration(node)) {
collectVars(ts, node.name, blockVars);
for (const varName of blockVars) {
localVars.set(varName, (localVars.get(varName) ?? 0) + 1);
}
if (node.initializer)
walkIdentifiers(ts, node.initializer, cb, localVars, blockVars, false);
}
else if (ts.isArrowFunction(node) || ts.isFunctionExpression(node)) {
const functionArgs = [];
for (const param of node.parameters) {
collectVars(ts, param.name, functionArgs);
if (param.type) {
walkIdentifiers(ts, param.type, cb, localVars, blockVars, false);
}
}
for (const varName of functionArgs)
localVars.set(varName, (localVars.get(varName) ?? 0) + 1);
walkIdentifiers(ts, node.body, cb, localVars, blockVars, false);
for (const varName of functionArgs)
localVars.set(varName, localVars.get(varName) - 1);
}
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, cb, localVars, blockVars, false);
}
walkIdentifiers(ts, prop.initializer, cb, localVars, blockVars, false);
}
// fix https://github.com/vuejs/language-tools/issues/1156
else if (ts.isShorthandPropertyAssignment(prop)) {
walkIdentifiers(ts, prop, cb, localVars, 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, cb, localVars, blockVars, false);
}
}
}
else if (ts.isTypeReferenceNode(node)) {
// fix https://github.com/vuejs/language-tools/issues/1422
node.forEachChild(node => walkIdentifiersInTypeReference(ts, node, cb));
}
else {
const _blockVars = blockVars;
if (ts.isBlock(node)) {
blockVars = [];
}
node.forEachChild(node => walkIdentifiers(ts, node, cb, localVars, blockVars, false));
if (ts.isBlock(node)) {
for (const varName of blockVars) {
localVars.set(varName, localVars.get(varName) - 1);
}
}
blockVars = _blockVars;
}
if (isRoot) {
for (const varName of blockVars) {
localVars.set(varName, localVars.get(varName) - 1);
}
}
}
function walkIdentifiersInTypeReference(ts, node, cb) {
if (ts.isTypeQueryNode(node) && ts.isIdentifier(node.exprName)) {
cb(node.exprName, false);
}
else {
node.forEachChild(node => walkIdentifiersInTypeReference(ts, node, cb));
}
}
function collectVars(ts, node, result) {
if (ts.isIdentifier(node)) {
result.push(node.text);
}
else if (ts.isObjectBindingPattern(node)) {
for (const el of node.elements) {
collectVars(ts, el.name, result);
}
}
else if (ts.isArrayBindingPattern(node)) {
for (const el of node.elements) {
if (ts.isBindingElement(el)) {
collectVars(ts, el.name, result);
}
}
}
else {
node.forEachChild(node => collectVars(ts, node, result));
}
}
exports.collectVars = collectVars;
//# sourceMappingURL=transform.js.map

9
node_modules/@vue/language-core/out/utils/ts.d.ts generated vendored Normal file
View File

@@ -0,0 +1,9 @@
import type * as ts from 'typescript/lib/tsserverlibrary';
import type { VueCompilerOptions } from '../types';
export type ParsedCommandLine = ts.ParsedCommandLine & {
vueOptions: Partial<VueCompilerOptions>;
};
export declare function createParsedCommandLineByJson(ts: typeof import('typescript/lib/tsserverlibrary'), parseConfigHost: ts.ParseConfigHost, rootDir: string, json: any, configFileName?: string): ParsedCommandLine;
export declare function createParsedCommandLine(ts: typeof import('typescript/lib/tsserverlibrary'), parseConfigHost: ts.ParseConfigHost, tsConfigPath: string): ParsedCommandLine;
export declare function resolveVueCompilerOptions(vueOptions: Partial<VueCompilerOptions>): VueCompilerOptions;
//# sourceMappingURL=ts.d.ts.map

237
node_modules/@vue/language-core/out/utils/ts.js generated vendored Normal file
View File

@@ -0,0 +1,237 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveVueCompilerOptions = exports.createParsedCommandLine = exports.createParsedCommandLineByJson = void 0;
const path = require("path-browserify");
function createParsedCommandLineByJson(ts, parseConfigHost, rootDir, json, configFileName = rootDir + '/jsconfig.json') {
const proxyHost = proxyParseConfigHostForExtendConfigPaths(parseConfigHost);
ts.parseJsonConfigFileContent(json, proxyHost.host, rootDir, {}, configFileName);
let vueOptions = {};
for (const extendPath of proxyHost.extendConfigPaths.reverse()) {
try {
vueOptions = {
...vueOptions,
...getPartialVueCompilerOptions(ts, ts.readJsonConfigFile(extendPath, proxyHost.host.readFile)),
};
}
catch (err) { }
}
const parsed = ts.parseJsonConfigFileContent(json, proxyHost.host, rootDir, {}, configFileName, undefined, (vueOptions.extensions ?? ['.vue']).map(extension => ({
extension: extension.slice(1),
isMixedContent: true,
scriptKind: ts.ScriptKind.Deferred,
})));
// fix https://github.com/vuejs/language-tools/issues/1786
// https://github.com/microsoft/TypeScript/issues/30457
// patching ts server broke with outDir + rootDir + composite/incremental
parsed.options.outDir = undefined;
return {
...parsed,
vueOptions,
};
}
exports.createParsedCommandLineByJson = createParsedCommandLineByJson;
function createParsedCommandLine(ts, parseConfigHost, tsConfigPath) {
try {
const proxyHost = proxyParseConfigHostForExtendConfigPaths(parseConfigHost);
const config = ts.readJsonConfigFile(tsConfigPath, proxyHost.host.readFile);
ts.parseJsonSourceFileConfigFileContent(config, proxyHost.host, path.dirname(tsConfigPath), {}, tsConfigPath);
let vueOptions = {};
for (const extendPath of proxyHost.extendConfigPaths.reverse()) {
try {
vueOptions = {
...vueOptions,
...getPartialVueCompilerOptions(ts, ts.readJsonConfigFile(extendPath, proxyHost.host.readFile)),
};
}
catch (err) { }
}
const parsed = ts.parseJsonSourceFileConfigFileContent(config, proxyHost.host, path.dirname(tsConfigPath), {}, tsConfigPath, undefined, (vueOptions.extensions ?? ['.vue']).map(extension => ({
extension: extension.slice(1),
isMixedContent: true,
scriptKind: ts.ScriptKind.Deferred,
})));
// fix https://github.com/vuejs/language-tools/issues/1786
// https://github.com/microsoft/TypeScript/issues/30457
// patching ts server broke with outDir + rootDir + composite/incremental
parsed.options.outDir = undefined;
return {
...parsed,
vueOptions,
};
}
catch (err) {
// console.warn('Failed to resolve tsconfig path:', tsConfigPath, err);
return {
fileNames: [],
options: {},
vueOptions: resolveVueCompilerOptions({}),
errors: [],
};
}
}
exports.createParsedCommandLine = createParsedCommandLine;
function proxyParseConfigHostForExtendConfigPaths(parseConfigHost) {
const extendConfigPaths = [];
const host = new Proxy(parseConfigHost, {
get(target, key) {
if (key === 'readFile') {
return (fileName) => {
if (!fileName.endsWith('/package.json') && !extendConfigPaths.includes(fileName)) {
extendConfigPaths.push(fileName);
}
return target.readFile(fileName);
};
}
return target[key];
}
});
return {
host,
extendConfigPaths,
};
}
function getPartialVueCompilerOptions(ts, tsConfigSourceFile) {
const folder = path.dirname(tsConfigSourceFile.fileName);
const obj = ts.convertToObject(tsConfigSourceFile, []);
const rawOptions = obj?.vueCompilerOptions ?? {};
const result = {
...rawOptions,
};
const target = rawOptions.target ?? 'auto';
if (target === 'auto') {
const resolvedPath = resolvePath('vue/package.json');
if (resolvedPath) {
const vuePackageJson = require(resolvedPath);
const versionNumbers = vuePackageJson.version.split('.');
result.target = Number(versionNumbers[0] + '.' + versionNumbers[1]);
}
else {
// console.warn('Load vue/package.json failed from', folder);
}
}
else {
result.target = target;
}
if (rawOptions.plugins) {
const plugins = rawOptions.plugins
.map((pluginPath) => {
try {
const resolvedPath = resolvePath(pluginPath);
if (resolvedPath) {
return require(resolvedPath);
}
else {
console.warn('Load plugin failed:', pluginPath);
}
}
catch (error) {
console.warn('Load plugin failed:', pluginPath, error);
}
return [];
})
.flat(Infinity);
result.plugins = plugins;
}
if (rawOptions.hooks) {
result.hooks = rawOptions.hooks
.map(resolvePath)
.filter((hook) => !!hook);
}
if (rawOptions.experimentalAdditionalLanguageModules) {
result.experimentalAdditionalLanguageModules = rawOptions.experimentalAdditionalLanguageModules
.map(resolvePath)
.filter((module) => !!module);
}
return result;
function resolvePath(scriptPath) {
try {
if (require?.resolve) {
return require.resolve(scriptPath, { paths: [folder] });
}
else {
// console.warn('failed to resolve path:', scriptPath, 'require.resolve is not supported in web');
}
}
catch (error) {
// console.warn(error);
}
}
}
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element
const HTML_TAGS = 'html,body,base,head,link,meta,style,title,address,article,aside,footer,' +
'header,hgroup,h1,h2,h3,h4,h5,h6,nav,section,div,dd,dl,dt,figcaption,' +
'figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,' +
'data,dfn,em,i,kbd,mark,q,rp,rt,ruby,s,samp,small,span,strong,sub,sup,' +
'time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,' +
'canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,' +
'th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,' +
'option,output,progress,select,textarea,details,dialog,menu,' +
'summary,template,blockquote,iframe,tfoot';
// https://developer.mozilla.org/en-US/docs/Web/SVG/Element
const SVG_TAGS = 'svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,' +
'defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,' +
'feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,' +
'feDistanceLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,' +
'feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,' +
'fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,' +
'foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,' +
'mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,' +
'polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,' +
'text,textPath,title,tspan,unknown,use,view';
function resolveVueCompilerOptions(vueOptions) {
const target = vueOptions.target ?? 3.3;
const lib = vueOptions.lib || (target < 2.7 ? '@vue/runtime-dom' : 'vue');
return {
...vueOptions,
target,
extensions: vueOptions.extensions ?? ['.vue'],
lib,
jsxSlots: vueOptions.jsxSlots ?? false,
strictTemplates: vueOptions.strictTemplates ?? false,
skipTemplateCodegen: vueOptions.skipTemplateCodegen ?? false,
nativeTags: vueOptions.nativeTags ?? [...new Set([
...HTML_TAGS.split(','),
...SVG_TAGS.split(','),
// fix https://github.com/johnsoncodehk/volar/issues/1340
'hgroup',
'slot',
'component',
])],
dataAttributes: vueOptions.dataAttributes ?? [],
htmlAttributes: vueOptions.htmlAttributes ?? ['aria-*'],
optionsWrapper: vueOptions.optionsWrapper ?? (target >= 2.7
? [`(await import('${lib}')).defineComponent(`, `)`]
: [`(await import('vue')).default.extend(`, `)`]),
macros: {
defineProps: ['defineProps'],
defineSlots: ['defineSlots'],
defineEmits: ['defineEmits'],
defineExpose: ['defineExpose'],
defineModel: ['defineModel'],
defineOptions: ['defineOptions'],
withDefaults: ['withDefaults'],
...vueOptions.macros,
},
plugins: vueOptions.plugins ?? [],
hooks: vueOptions.hooks ?? [],
// experimental
experimentalDefinePropProposal: vueOptions.experimentalDefinePropProposal ?? false,
experimentalAdditionalLanguageModules: vueOptions.experimentalAdditionalLanguageModules ?? [],
experimentalResolveStyleCssClasses: vueOptions.experimentalResolveStyleCssClasses ?? 'scoped',
// https://github.com/vuejs/vue-next/blob/master/packages/compiler-dom/src/transforms/vModel.ts#L49-L51
// https://vuejs.org/guide/essentials/forms.html#form-input-bindings
experimentalModelPropName: vueOptions.experimentalModelPropName ?? {
'': {
input: true
},
value: {
input: { type: 'text' },
textarea: true,
select: true
}
},
experimentalUseElementAccessInTemplate: vueOptions.experimentalUseElementAccessInTemplate ?? false,
};
}
exports.resolveVueCompilerOptions = resolveVueCompilerOptions;
//# sourceMappingURL=ts.js.map

View File

@@ -0,0 +1,3 @@
import * as CompilerDOM from '@vue/compiler-dom';
export declare function compile(template: string, options?: CompilerDOM.CompilerOptions): CompilerDOM.CodegenResult;
//# sourceMappingURL=vue2TemplateCompiler.d.ts.map

View File

@@ -0,0 +1,86 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.compile = void 0;
const CompilerDOM = require("@vue/compiler-dom");
const Vue2TemplateCompiler = require('vue-template-compiler/build');
function compile(template, options = {}) {
const onError = options.onError;
const onWarn = options.onWarn;
options.onError = (error) => {
if (error.code === 33 // :key binding allowed in v-for template child in vue 2
|| error.code === 29 // fix https://github.com/vuejs/language-tools/issues/1638
) {
return;
}
if (onError) {
onError(error);
}
else {
throw error;
}
};
const vue2Result = Vue2TemplateCompiler.compile(template, { outputSourceRange: true });
for (const error of vue2Result.errors) {
onError?.({
code: 'vue-template-compiler',
name: '',
message: error.msg,
loc: {
source: '',
start: { column: -1, line: -1, offset: error.start },
end: { column: -1, line: -1, offset: error.end ?? error.start },
},
});
}
for (const error of vue2Result.tips) {
onWarn?.({
code: 'vue-template-compiler',
name: '',
message: error.msg,
loc: {
source: '',
start: { column: -1, line: -1, offset: error.start },
end: { column: -1, line: -1, offset: error.end ?? error.start },
},
});
}
return baseCompile(template, Object.assign({}, CompilerDOM.parserOptions, options, {
nodeTransforms: [
...CompilerDOM.DOMNodeTransforms,
...(options.nodeTransforms || [])
],
directiveTransforms: Object.assign({}, CompilerDOM.DOMDirectiveTransforms, options.directiveTransforms || {}),
}));
}
exports.compile = compile;
function baseCompile(template, options = {}) {
const onError = options.onError || ((error) => { throw error; });
const isModuleMode = options.mode === 'module';
const prefixIdentifiers = options.prefixIdentifiers === true || isModuleMode;
if (!prefixIdentifiers && options.cacheHandlers) {
onError(CompilerDOM.createCompilerError(49));
}
if (options.scopeId && !isModuleMode) {
onError(CompilerDOM.createCompilerError(50));
}
const ast = CompilerDOM.baseParse(template, options);
const [nodeTransforms, directiveTransforms] = CompilerDOM.getBaseTransformPreset(prefixIdentifiers);
// v-for > v-if in vue 2
const transformIf = nodeTransforms[1];
const transformFor = nodeTransforms[3];
nodeTransforms[1] = transformFor;
nodeTransforms[3] = transformIf;
CompilerDOM.transform(ast, Object.assign({}, options, {
prefixIdentifiers,
nodeTransforms: [
...nodeTransforms,
...(options.nodeTransforms || []) // user transforms
],
directiveTransforms: Object.assign({}, directiveTransforms, options.directiveTransforms || {} // user transforms
)
}));
return CompilerDOM.generate(ast, Object.assign({}, options, {
prefixIdentifiers
}));
}
//# sourceMappingURL=vue2TemplateCompiler.js.map