Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@volar/vue-language-core

Package Overview
Dependencies
Maintainers
1
Versions
112
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@volar/vue-language-core - npm Package Compare versions

Comparing version 1.3.8 to 1.3.9

4

out/generators/script.d.ts

@@ -11,6 +11,6 @@ import { Segment } from '@volar/source-map';

import type { VueCompilerOptions } from '../types';
export declare function generate(ts: typeof import('typescript/lib/tsserverlibrary'), fileName: string, _sfc: Sfc, lang: string, scriptRanges: ScriptRanges | undefined, scriptSetupRanges: ScriptSetupRanges | undefined, cssVars: ReturnType<typeof collectCssVars>, cssModuleClasses: ReturnType<typeof collectStyleCssClasses>, cssScopedClasses: ReturnType<typeof collectStyleCssClasses>, htmlGen: ReturnType<typeof templateGen['generate']> | undefined, compilerOptions: ts.CompilerOptions, vueCompilerOptions: VueCompilerOptions, codeGen?: Segment<FileRangeCapabilities>[], mirrorBehaviorMappings?: SourceMaps.Mapping<[MirrorBehaviorCapabilities, MirrorBehaviorCapabilities]>[]): {
codeGen: Segment<FileRangeCapabilities>[];
export declare function generate(ts: typeof import('typescript/lib/tsserverlibrary'), fileName: string, _sfc: Sfc, lang: string, scriptRanges: ScriptRanges | undefined, scriptSetupRanges: ScriptSetupRanges | undefined, cssVars: ReturnType<typeof collectCssVars>, cssModuleClasses: ReturnType<typeof collectStyleCssClasses>, cssScopedClasses: ReturnType<typeof collectStyleCssClasses>, htmlGen: ReturnType<typeof templateGen['generate']> | undefined, compilerOptions: ts.CompilerOptions, vueCompilerOptions: VueCompilerOptions, codes?: Segment<FileRangeCapabilities>[], mirrorBehaviorMappings?: SourceMaps.Mapping<[MirrorBehaviorCapabilities, MirrorBehaviorCapabilities]>[]): {
codes: Segment<FileRangeCapabilities>[];
extraMappings: SourceMaps.Mapping<any>[];
mirrorBehaviorMappings: SourceMaps.Mapping<[MirrorBehaviorCapabilities, MirrorBehaviorCapabilities]>[];
};

@@ -11,4 +11,4 @@ "use strict";

const localTypes_1 = require("../utils/localTypes");
function generate(ts, fileName, _sfc, lang, scriptRanges, scriptSetupRanges, cssVars, cssModuleClasses, cssScopedClasses, htmlGen, compilerOptions, vueCompilerOptions, codeGen = [], mirrorBehaviorMappings = []) {
// monkey fix for https://github.com/johnsoncodehk/volar/pull/2113
function generate(ts, fileName, _sfc, lang, scriptRanges, scriptSetupRanges, cssVars, cssModuleClasses, cssScopedClasses, htmlGen, compilerOptions, vueCompilerOptions, codes = [], mirrorBehaviorMappings = []) {
//#region monkey fix: https://github.com/johnsoncodehk/volar/pull/2113
const sfc = {

@@ -37,8 +37,9 @@ script: _sfc.script,

exposeRuntimeArg: undefined,
exposeTypeArg: undefined,
importSectionEndOffset: 0,
notOnTopTypeExports: [],
defineProps: undefined,
propsAssignName: undefined,
propsRuntimeArg: undefined,
propsTypeArg: undefined,
slotsTypeArg: undefined,
typeBindings: [],

@@ -48,5 +49,6 @@ withDefaultsArg: undefined,

}
//#endregion
const bypassDefineComponent = lang === 'js' || lang === 'jsx';
const vueLibName = (0, shared_2.getVueLibraryName)(vueCompilerOptions.target);
const usedTypes = {
const usedHelperTypes = {
DefinePropsToOptions: false,

@@ -57,24 +59,18 @@ mergePropDefaults: false,

};
const generateFunctionType = !!sfc.scriptSetup?.generic;
if (vueCompilerOptions.jsxTemplates && vueCompilerOptions.target >= 3.3) {
codeGen.push(`/** @jsxImportSource vue */\n`);
codes.push(`/** @jsxImportSource vue */\n`);
}
writeScriptSrc();
writeScriptSetupImportsSegment();
writeScriptContentBeforeExportDefault();
writeScriptSetupAndTemplate();
writeScriptSetupTypes();
writeScriptContentAfterExportDefault();
writeTemplateIfNoScriptSetup();
if (!sfc.script && !sfc.scriptSetup) {
codeGen.push([
'export default {} as any',
undefined,
[0, 0],
{},
]);
let generatedTemplate = false;
generateSrc();
generateScriptSetupImports();
generateScriptContentBeforeExportDefault();
generateScriptSetupAndTemplate();
generateHelperTypes();
generateScriptContentAfterExportDefault();
if (!generatedTemplate) {
generateTemplate();
}
if (sfc.scriptSetup) {
// for code action edits
codeGen.push([
codes.push([
'',

@@ -88,3 +84,3 @@ 'scriptSetup',

// fix https://github.com/johnsoncodehk/volar/issues/435
const text = (0, source_map_1.toString)(codeGen);
const text = (0, source_map_1.toString)(codes);
const start = text.length - text.trimStart().length;

@@ -105,39 +101,48 @@ const end = text.trimEnd().length;

return {
codeGen,
codes,
extraMappings,
mirrorBehaviorMappings,
};
function writeScriptSetupTypes() {
if (usedTypes.DefinePropsToOptions) {
function generateHelperTypes() {
let usedPrettify = false;
if (usedHelperTypes.DefinePropsToOptions) {
if (compilerOptions.exactOptionalPropertyTypes) {
codeGen.push(`type __VLS_TypePropsToRuntimeProps<T> = { [K in keyof T]-?: {} extends Pick<T, K> ? { type: import('${vueLibName}').PropType<T[K]> } : { type: import('${vueLibName}').PropType<T[K]>, required: true } };\n`);
codes.push(`type __VLS_TypePropsToRuntimeProps<T> = { [K in keyof T]-?: {} extends Pick<T, K> ? { type: import('${vueLibName}').PropType<T[K]> } : { type: import('${vueLibName}').PropType<T[K]>, required: true } };\n`);
}
else {
codeGen.push(`type __VLS_NonUndefinedable<T> = T extends undefined ? never : T;\n`);
codeGen.push(`type __VLS_TypePropsToRuntimeProps<T> = { [K in keyof T]-?: {} extends Pick<T, K> ? { type: import('${vueLibName}').PropType<__VLS_NonUndefinedable<T[K]>> } : { type: import('${vueLibName}').PropType<T[K]>, required: true } };\n`);
codes.push(`type __VLS_NonUndefinedable<T> = T extends undefined ? never : T;\n`);
codes.push(`type __VLS_TypePropsToRuntimeProps<T> = { [K in keyof T]-?: {} extends Pick<T, K> ? { type: import('${vueLibName}').PropType<__VLS_NonUndefinedable<T[K]>> } : { type: import('${vueLibName}').PropType<T[K]>, required: true } };\n`);
}
}
if (usedTypes.mergePropDefaults) {
codeGen.push(`type __VLS_WithDefaults<P, D> = {
if (usedHelperTypes.mergePropDefaults) {
codes.push(`type __VLS_WithDefaults<P, D> = {
// use 'keyof Pick<P, keyof P>' instead of 'keyof P' to keep props jsdoc
[K in keyof Pick<P, keyof P>]: K extends keyof D ? P[K] & {
[K in keyof Pick<P, keyof P>]: K extends keyof D ? __VLS_Prettify<P[K] & {
default: D[K]
} : P[K]
}> : P[K]
};\n`);
usedPrettify = true;
}
if (usedTypes.ConstructorOverloads) {
if (usedHelperTypes.ConstructorOverloads) {
// fix https://github.com/johnsoncodehk/volar/issues/926
codeGen.push('type __VLS_UnionToIntersection<U> = (U extends unknown ? (arg: U) => unknown : never) extends ((arg: infer P) => unknown) ? P : never;\n');
codes.push('type __VLS_UnionToIntersection<U> = __VLS_Prettify<(U extends unknown ? (arg: U) => unknown : never) extends ((arg: infer P) => unknown) ? P : never>;\n');
usedPrettify = true;
if (scriptSetupRanges && scriptSetupRanges.emitsTypeNums !== -1) {
codeGen.push((0, localTypes_1.genConstructorOverloads)('__VLS_ConstructorOverloads', scriptSetupRanges.emitsTypeNums));
codes.push((0, localTypes_1.genConstructorOverloads)('__VLS_ConstructorOverloads', scriptSetupRanges.emitsTypeNums));
}
else {
codeGen.push((0, localTypes_1.genConstructorOverloads)('__VLS_ConstructorOverloads'));
codes.push((0, localTypes_1.genConstructorOverloads)('__VLS_ConstructorOverloads'));
}
}
if (usedTypes.WithTemplateSlots) {
codeGen.push(`type __VLS_WithTemplateSlots<T, S> = T & { new(): { $slots: S } };\n`);
if (usedHelperTypes.WithTemplateSlots) {
codes.push(`type __VLS_WithTemplateSlots<T, S> = T & { new(): {
$slots: S;
$props: { [K in keyof JSX.ElementChildrenAttribute]: S; };
} };\n`);
}
if (usedPrettify) {
codes.push(`type __VLS_Prettify<T> = { [K in keyof T]: T[K]; } & {};\n`);
}
}
function writeScriptSrc() {
function generateSrc() {
if (!sfc.script?.src)

@@ -154,4 +159,4 @@ return;

src = src + '.js';
codeGen.push(`export * from `);
codeGen.push([
codes.push(`export * from `);
codes.push([
`'${src}'`,

@@ -183,6 +188,6 @@ 'script',

]);
codeGen.push(`;\n`);
codeGen.push(`export { default } from '${src}';\n`);
codes.push(`;\n`);
codes.push(`export { default } from '${src}';\n`);
}
function writeScriptContentBeforeExportDefault() {
function generateScriptContentBeforeExportDefault() {
if (!sfc.script)

@@ -192,3 +197,3 @@ return;

// fix https://github.com/johnsoncodehk/volar/issues/1127
codeGen.push([
codes.push([
'',

@@ -208,5 +213,5 @@ 'scriptSetup',

addVirtualCode('script', 0, scriptRanges.exportDefault.expression.start);
codeGen.push(vueCompilerOptions.optionsWrapper[0]);
codes.push(vueCompilerOptions.optionsWrapper[0]);
addVirtualCode('script', scriptRanges.exportDefault.expression.start, scriptRanges.exportDefault.expression.end);
codeGen.push(vueCompilerOptions.optionsWrapper[1]);
codes.push(vueCompilerOptions.optionsWrapper[1]);
addVirtualCode('script', scriptRanges.exportDefault.expression.end, sfc.script.content.length);

@@ -219,3 +224,3 @@ }

}
function writeScriptContentAfterExportDefault() {
function generateScriptContentAfterExportDefault() {
if (!sfc.script)

@@ -227,23 +232,3 @@ return;

}
function addVirtualCode(vueTag, start, end) {
codeGen.push([
sfc[vueTag].content.substring(start, end),
vueTag,
start,
language_core_1.FileRangeCapabilities.full, // diagnostic also working for setup() returns unused in template checking
]);
}
function addExtraReferenceVirtualCode(vueTag, start, end) {
codeGen.push([
sfc[vueTag].content.substring(start, end),
vueTag,
start,
{
references: true,
definition: true,
rename: true,
},
]);
}
function writeScriptSetupImportsSegment() {
function generateScriptSetupImports() {
if (!sfc.scriptSetup)

@@ -253,3 +238,3 @@ return;

return;
codeGen.push([
codes.push([
sfc.scriptSetup.content.substring(0, scriptSetupRanges.importSectionEndOffset),

@@ -261,265 +246,298 @@ 'scriptSetup',

}
function writeTemplateIfNoScriptSetup() {
if (!sfc.scriptSetup) {
writeTemplate();
function generateScriptSetupAndTemplate() {
if (!sfc.scriptSetup || !scriptSetupRanges) {
return;
}
}
function writeScriptSetupAndTemplate() {
if (sfc.scriptSetup && scriptSetupRanges) {
if (!scriptRanges?.exportDefault) {
// fix https://github.com/johnsoncodehk/volar/issues/1127
codeGen.push([
'',
'scriptSetup',
0,
{ diagnostic: true },
]);
codeGen.push('export default ');
if (!scriptRanges?.exportDefault) {
// fix https://github.com/johnsoncodehk/volar/issues/1127
codes.push([
'',
'scriptSetup',
0,
{ diagnostic: true },
]);
codes.push('export default ');
}
if (sfc.scriptSetup.generic) {
codes.push(`(<`);
codes.push([
sfc.scriptSetup.generic,
sfc.scriptSetup.name,
sfc.scriptSetup.genericOffset,
language_core_1.FileRangeCapabilities.full,
]);
if (!sfc.scriptSetup.generic.endsWith(',')) {
codes.push(`,`);
}
codeGen.push('(');
if (generateFunctionType && sfc.scriptSetup.generic) {
codeGen.push(`<`);
codeGen.push([
sfc.scriptSetup.generic,
sfc.scriptSetup.name,
sfc.scriptSetup.genericOffset,
language_core_1.FileRangeCapabilities.full,
]);
if (!sfc.scriptSetup.generic.endsWith(',')) {
codeGen.push(`,`);
}
codeGen.push(`>`);
codes.push(`>`);
codes.push('(\n');
if (scriptSetupRanges.propsRuntimeArg && scriptSetupRanges.defineProps) {
codes.push(`__VLS_props = (() => {\n`);
codes.push(`const __VLS_return = (await import('vue')).`);
addVirtualCode('scriptSetup', scriptSetupRanges.defineProps.start, scriptSetupRanges.defineProps.end);
codes.push(`;\n`);
codes.push(`return {} as typeof __VLS_return & import('vue').VNodeProps;\n`);
codes.push(`})()`);
}
codeGen.push('(');
if (generateFunctionType && scriptSetupRanges.propsTypeArg) {
codeGen.push('__VLS_props: ');
if (!vueCompilerOptions.strictTemplates) {
codeGen.push(`Record<string, unknown> & `);
else {
codes.push(`__VLS_props: import('vue').VNodeProps`);
if (scriptSetupRanges.slotsTypeArg) {
codes.push(` & { [K in keyof JSX.ElementChildrenAttribute]: `);
addVirtualCode('scriptSetup', scriptSetupRanges.slotsTypeArg.start, scriptSetupRanges.slotsTypeArg.end);
codes.push(`; }`);
}
addVirtualCode('scriptSetup', scriptSetupRanges.propsTypeArg.start, scriptSetupRanges.propsTypeArg.end);
if (scriptSetupRanges.propsTypeArg) {
codes.push(' & ');
addVirtualCode('scriptSetup', scriptSetupRanges.propsTypeArg.start, scriptSetupRanges.propsTypeArg.end);
}
}
codeGen.push(') => {\n');
codeGen.push('const __VLS_setup = async () => {\n');
if (generateFunctionType && scriptSetupRanges.propsTypeArg) {
addVirtualCode('scriptSetup', scriptSetupRanges.importSectionEndOffset, scriptSetupRanges.propsTypeArg.start);
codeGen.push('typeof __VLS_props');
addVirtualCode('scriptSetup', scriptSetupRanges.propsTypeArg.end);
codes.push(',\n');
codes.push('__VLS_ctx = (() => {\n');
generateSetupFunction(true);
codes.push('return {\n');
codes.push('attrs: {} as any,\n');
codes.push('slots: {} as typeof __VLS_setup extends () => Promise<{ slots: infer T }> ? T : never,\n');
//#region emit
codes.push('emit: ');
if (scriptSetupRanges.emitsTypeArg) {
codes.push('{} as ');
addVirtualCode('scriptSetup', scriptSetupRanges.emitsTypeArg.start, scriptSetupRanges.emitsTypeArg.end);
codes.push(',\n');
}
else {
addVirtualCode('scriptSetup', scriptSetupRanges.importSectionEndOffset);
else if (scriptSetupRanges.emitsRuntimeArg) {
codes.push(`(await import('vue')).defineEmits(`);
addVirtualCode('scriptSetup', scriptSetupRanges.emitsRuntimeArg.start, scriptSetupRanges.emitsRuntimeArg.end);
codes.push('),\n');
}
if (scriptSetupRanges.propsTypeArg && scriptSetupRanges.withDefaultsArg) {
// fix https://github.com/johnsoncodehk/volar/issues/1187
codeGen.push(`const __VLS_withDefaultsArg = (function <T>(t: T) { return t })(`);
addExtraReferenceVirtualCode('scriptSetup', scriptSetupRanges.withDefaultsArg.start, scriptSetupRanges.withDefaultsArg.end);
codeGen.push(`);\n`);
}
if (scriptRanges?.exportDefault && scriptRanges.exportDefault.expression.start !== scriptRanges.exportDefault.args.start) {
// use defineComponent() from user space code if it exist
codeGen.push(`const __VLS_publicComponent = `);
addVirtualCode('script', scriptRanges.exportDefault.expression.start, scriptRanges.exportDefault.args.start);
codeGen.push(`{\n`);
}
else {
codeGen.push(`const __VLS_publicComponent = (await import('${vueLibName}')).defineComponent({\n`);
codes.push('{} as any,\n');
}
if (!bypassDefineComponent) {
if (scriptSetupRanges.propsRuntimeArg || scriptSetupRanges.propsTypeArg) {
codeGen.push(`props: (`);
if (scriptSetupRanges.propsTypeArg) {
usedTypes.DefinePropsToOptions = true;
codeGen.push(`{} as `);
if (scriptSetupRanges.withDefaultsArg) {
usedTypes.mergePropDefaults = true;
codeGen.push(`__VLS_WithDefaults<`);
}
codeGen.push(`__VLS_TypePropsToRuntimeProps<`);
if (generateFunctionType) {
codeGen.push(`typeof __VLS_props`);
}
else {
addExtraReferenceVirtualCode('scriptSetup', scriptSetupRanges.propsTypeArg.start, scriptSetupRanges.propsTypeArg.end);
}
codeGen.push(`>`);
if (scriptSetupRanges.withDefaultsArg) {
codeGen.push(`, typeof __VLS_withDefaultsArg`);
codeGen.push(`>`);
}
//#endregion
//#region expose
codes.push('expose(__VLS_exposed: typeof __VLS_setup extends () => Promise<{ exposed: infer T }> ? T : never) { },\n');
//#endregion
codes.push('};\n');
codes.push('})(),\n');
codes.push(') => ({} as JSX.Element & { __ctx?: typeof __VLS_ctx, __props?: typeof __VLS_props }))');
}
else {
codes.push('(() => {\n');
generateSetupFunction(false);
codes.push(`return {} as typeof __VLS_setup extends () => Promise<infer T> ? T : never;\n`);
codes.push(`})()`);
}
if (scriptRanges?.exportDefault && scriptRanges.exportDefault.expression.end !== scriptRanges.exportDefault.end) {
addVirtualCode('script', scriptRanges.exportDefault.expression.end, scriptRanges.exportDefault.end);
}
codes.push(`;`);
// fix https://github.com/johnsoncodehk/volar/issues/1127
codes.push([
'',
'scriptSetup',
sfc.scriptSetup.content.length,
{ diagnostic: true },
]);
codes.push(`\n`);
}
function generateSetupFunction(functional) {
if (!scriptSetupRanges || !sfc.scriptSetup) {
return;
}
codes.push('const __VLS_setup = async () => {\n');
if (sfc.scriptSetup.generic && scriptSetupRanges.propsRuntimeArg && scriptSetupRanges.defineProps) {
addVirtualCode('scriptSetup', scriptSetupRanges.importSectionEndOffset, scriptSetupRanges.defineProps.start);
codes.push('__VLS_props');
addVirtualCode('scriptSetup', scriptSetupRanges.defineProps.end);
}
else if (sfc.scriptSetup.generic && scriptSetupRanges.propsTypeArg) {
addVirtualCode('scriptSetup', scriptSetupRanges.importSectionEndOffset, scriptSetupRanges.propsTypeArg.start);
codes.push('typeof __VLS_props');
addVirtualCode('scriptSetup', scriptSetupRanges.propsTypeArg.end);
}
else {
addVirtualCode('scriptSetup', scriptSetupRanges.importSectionEndOffset);
}
if (scriptSetupRanges.propsTypeArg && scriptSetupRanges.withDefaultsArg) {
// fix https://github.com/johnsoncodehk/volar/issues/1187
codes.push(`const __VLS_withDefaultsArg = (function <T>(t: T) { return t })(`);
addExtraReferenceVirtualCode('scriptSetup', scriptSetupRanges.withDefaultsArg.start, scriptSetupRanges.withDefaultsArg.end);
codes.push(`);\n`);
}
if (scriptRanges?.exportDefault && scriptRanges.exportDefault.expression.start !== scriptRanges.exportDefault.args.start) {
// use defineComponent() from user space code if it exist
codes.push(`const __VLS_publicComponent = `);
addVirtualCode('script', scriptRanges.exportDefault.expression.start, scriptRanges.exportDefault.args.start);
codes.push(`{\n`);
}
else {
codes.push(`const __VLS_publicComponent = (await import('${vueLibName}')).defineComponent({\n`);
}
if (!bypassDefineComponent) {
if (scriptSetupRanges.propsRuntimeArg || scriptSetupRanges.propsTypeArg) {
codes.push(`props: (`);
if (scriptSetupRanges.propsTypeArg) {
usedHelperTypes.DefinePropsToOptions = true;
codes.push(`{} as `);
if (scriptSetupRanges.withDefaultsArg) {
usedHelperTypes.mergePropDefaults = true;
codes.push(`__VLS_WithDefaults<`);
}
else if (scriptSetupRanges.propsRuntimeArg) {
addExtraReferenceVirtualCode('scriptSetup', scriptSetupRanges.propsRuntimeArg.start, scriptSetupRanges.propsRuntimeArg.end);
codes.push(`__VLS_TypePropsToRuntimeProps<`);
if (functional) {
codes.push(`typeof __VLS_props`);
}
codeGen.push(`),\n`);
else {
addExtraReferenceVirtualCode('scriptSetup', scriptSetupRanges.propsTypeArg.start, scriptSetupRanges.propsTypeArg.end);
}
codes.push(`>`);
if (scriptSetupRanges.withDefaultsArg) {
codes.push(`, typeof __VLS_withDefaultsArg`);
codes.push(`>`);
}
}
if (scriptSetupRanges.emitsTypeArg) {
usedTypes.ConstructorOverloads = true;
codeGen.push(`emits: ({} as __VLS_UnionToIntersection<__VLS_ConstructorOverloads<`);
addExtraReferenceVirtualCode('scriptSetup', scriptSetupRanges.emitsTypeArg.start, scriptSetupRanges.emitsTypeArg.end);
codeGen.push(`>>),\n`);
}
else if (scriptSetupRanges.emitsRuntimeArg) {
codeGen.push(`emits: (`);
addExtraReferenceVirtualCode('scriptSetup', scriptSetupRanges.emitsRuntimeArg.start, scriptSetupRanges.emitsRuntimeArg.end);
codeGen.push(`),\n`);
}
}
codeGen.push(`setup() {\n`);
codeGen.push(`return {\n`);
if (bypassDefineComponent) {
// fill $props
if (scriptSetupRanges.propsTypeArg) {
// NOTE: defineProps is inaccurate for $props
codeGen.push(`$props: (await import('./__VLS_types.js')).makeOptional(defineProps<`);
addExtraReferenceVirtualCode('scriptSetup', scriptSetupRanges.propsTypeArg.start, scriptSetupRanges.propsTypeArg.end);
codeGen.push(`>()),\n`);
}
else if (scriptSetupRanges.propsRuntimeArg) {
// NOTE: defineProps is inaccurate for $props
codeGen.push(`$props: (await import('./__VLS_types.js')).makeOptional(defineProps(`);
addExtraReferenceVirtualCode('scriptSetup', scriptSetupRanges.propsRuntimeArg.start, scriptSetupRanges.propsRuntimeArg.end);
codeGen.push(`)),\n`);
}
// fill $emit
if (scriptSetupRanges.emitsAssignName) {
codeGen.push(`$emit: ${scriptSetupRanges.emitsAssignName},\n`);
}
else if (scriptSetupRanges.emitsTypeArg) {
codeGen.push(`$emit: defineEmits<`);
addExtraReferenceVirtualCode('scriptSetup', scriptSetupRanges.emitsTypeArg.start, scriptSetupRanges.emitsTypeArg.end);
codeGen.push(`>(),\n`);
}
else if (scriptSetupRanges.emitsRuntimeArg) {
codeGen.push(`$emit: defineEmits(`);
addExtraReferenceVirtualCode('scriptSetup', scriptSetupRanges.emitsRuntimeArg.start, scriptSetupRanges.emitsRuntimeArg.end);
codeGen.push(`),\n`);
}
codes.push(`),\n`);
}
if (scriptSetupRanges.exposeTypeArg) {
codeGen.push(`...({} as `);
addExtraReferenceVirtualCode('scriptSetup', scriptSetupRanges.exposeTypeArg.start, scriptSetupRanges.exposeTypeArg.end);
codeGen.push(`),\n`);
if (scriptSetupRanges.emitsTypeArg) {
usedHelperTypes.ConstructorOverloads = true;
codes.push(`emits: ({} as __VLS_UnionToIntersection<__VLS_ConstructorOverloads<`);
addExtraReferenceVirtualCode('scriptSetup', scriptSetupRanges.emitsTypeArg.start, scriptSetupRanges.emitsTypeArg.end);
codes.push(`>>),\n`);
}
else if (scriptSetupRanges.exposeRuntimeArg) {
codeGen.push(`...(`);
addExtraReferenceVirtualCode('scriptSetup', scriptSetupRanges.exposeRuntimeArg.start, scriptSetupRanges.exposeRuntimeArg.end);
codeGen.push(`),\n`);
else if (scriptSetupRanges.emitsRuntimeArg) {
codes.push(`emits: (`);
addExtraReferenceVirtualCode('scriptSetup', scriptSetupRanges.emitsRuntimeArg.start, scriptSetupRanges.emitsRuntimeArg.end);
codes.push(`),\n`);
}
codeGen.push(`};\n`);
codeGen.push(`},\n`);
if (scriptRanges?.exportDefault?.args) {
addVirtualCode('script', scriptRanges.exportDefault.args.start + 1, scriptRanges.exportDefault.args.end - 1);
}
codes.push(`setup() {\n`);
codes.push(`return {\n`);
if (bypassDefineComponent) {
// fill $props
if (scriptSetupRanges.propsTypeArg) {
// NOTE: defineProps is inaccurate for $props
codes.push(`$props: (await import('./__VLS_types.js')).makeOptional(defineProps<`);
addExtraReferenceVirtualCode('scriptSetup', scriptSetupRanges.propsTypeArg.start, scriptSetupRanges.propsTypeArg.end);
codes.push(`>()),\n`);
}
codeGen.push(`});\n`);
writeTemplate();
if (generateFunctionType) {
codeGen.push(`return {} as Omit<import('./__VLS_types.js').Element, 'props' | 'children'> & Omit<InstanceType<typeof __VLS_publicComponent>, '$slots' | '$emit'>`);
codeGen.push(` & {\n`);
if (scriptSetupRanges.propsTypeArg) {
codeGen.push(`props: typeof __VLS_props,\n`);
}
else {
codeGen.push(`props: InstanceType<typeof __VLS_publicComponent>['$props'],\n`);
}
codeGen.push(`$emit: `);
if (scriptSetupRanges.emitsTypeArg) {
addVirtualCode('scriptSetup', scriptSetupRanges.emitsTypeArg.start, scriptSetupRanges.emitsTypeArg.end);
}
else {
codeGen.push(`InstanceType<typeof __VLS_publicComponent>['$emit']`);
}
codeGen.push(`,\n`);
if (htmlGen?.hasSlot) {
codeGen.push(`children: ReturnType<typeof __VLS_template>,\n`);
}
else {
codeGen.push(`children: {},\n`);
}
codeGen.push(`};\n`);
else if (scriptSetupRanges.propsRuntimeArg) {
// NOTE: defineProps is inaccurate for $props
codes.push(`$props: (await import('./__VLS_types.js')).makeOptional(defineProps(`);
addExtraReferenceVirtualCode('scriptSetup', scriptSetupRanges.propsRuntimeArg.start, scriptSetupRanges.propsRuntimeArg.end);
codes.push(`)),\n`);
}
// fill $emit
if (scriptSetupRanges.emitsAssignName) {
codes.push(`$emit: ${scriptSetupRanges.emitsAssignName},\n`);
}
else if (scriptSetupRanges.emitsTypeArg) {
codes.push(`$emit: defineEmits<`);
addExtraReferenceVirtualCode('scriptSetup', scriptSetupRanges.emitsTypeArg.start, scriptSetupRanges.emitsTypeArg.end);
codes.push(`>(),\n`);
}
else if (scriptSetupRanges.emitsRuntimeArg) {
codes.push(`$emit: defineEmits(`);
addExtraReferenceVirtualCode('scriptSetup', scriptSetupRanges.emitsRuntimeArg.start, scriptSetupRanges.emitsRuntimeArg.end);
codes.push(`),\n`);
}
}
if (scriptSetupRanges.exposeRuntimeArg) {
codes.push(`...(`);
addExtraReferenceVirtualCode('scriptSetup', scriptSetupRanges.exposeRuntimeArg.start, scriptSetupRanges.exposeRuntimeArg.end);
codes.push(`),\n`);
}
codes.push(`};\n`);
codes.push(`},\n`);
if (scriptRanges?.exportDefault?.args) {
addVirtualCode('script', scriptRanges.exportDefault.args.start + 1, scriptRanges.exportDefault.args.end - 1);
}
codes.push(`});\n`);
generateTemplate();
if (functional) {
codes.push('return {\n');
codes.push('slots: __VLS_template(),\n');
codes.push('exposed: ');
if (scriptSetupRanges.exposeRuntimeArg) {
addVirtualCode('scriptSetup', scriptSetupRanges.exposeRuntimeArg.start, scriptSetupRanges.exposeRuntimeArg.end);
}
else {
if (!vueCompilerOptions.skipTemplateCodegen && htmlGen?.hasSlot) {
usedTypes.WithTemplateSlots = true;
codeGen.push(`return {} as __VLS_WithTemplateSlots<typeof __VLS_publicComponent, ReturnType<typeof __VLS_template>>;\n`);
}
else {
codeGen.push(`return {} as typeof __VLS_publicComponent;\n`);
}
codes.push(`{}`);
}
codeGen.push(`};\n`);
codeGen.push(`return {} as typeof __VLS_setup extends () => Promise<infer T> ? T : never;\n`);
codeGen.push(`})`);
if (!generateFunctionType) {
codeGen.push(`({} as any)`);
codes.push(',\n');
codes.push('};\n');
}
else {
if (!vueCompilerOptions.skipTemplateCodegen && htmlGen?.hasSlot) {
usedHelperTypes.WithTemplateSlots = true;
codes.push(`return {} as __VLS_WithTemplateSlots<typeof __VLS_publicComponent, ReturnType<typeof __VLS_template>>;\n`);
}
if (scriptRanges?.exportDefault && scriptRanges.exportDefault.expression.end !== scriptRanges.exportDefault.end) {
addVirtualCode('script', scriptRanges.exportDefault.expression.end, scriptRanges.exportDefault.end);
else {
codes.push(`return {} as typeof __VLS_publicComponent;\n`);
}
codeGen.push(`;`);
// fix https://github.com/johnsoncodehk/volar/issues/1127
codeGen.push([
'',
'scriptSetup',
sfc.scriptSetup.content.length,
{ diagnostic: true },
]);
codeGen.push(`\n`);
}
codes.push(`};\n`);
}
function writeTemplate() {
function generateTemplate() {
generatedTemplate = true;
if (!vueCompilerOptions.skipTemplateCodegen) {
writeExportOptions();
writeConstNameOption();
codeGen.push(`function __VLS_template() {\n`);
const templateGened = writeTemplateContext();
codeGen.push(`}\n`);
writeComponentForTemplateUsage(templateGened.cssIds);
generateExportOptions();
generateConstNameOption();
if (scriptSetupRanges?.slotsTypeArg && sfc.scriptSetup) {
codes.push(`var __VLS_slots!: `);
codes.push([
sfc.scriptSetup.content.substring(scriptSetupRanges.slotsTypeArg.start, scriptSetupRanges.slotsTypeArg.end),
sfc.scriptSetup.name,
[scriptSetupRanges.slotsTypeArg.start, scriptSetupRanges.slotsTypeArg.end],
language_core_1.FileRangeCapabilities.full,
]);
codes.push(';\n');
}
;
codes.push(`function __VLS_template() {\n`);
const templateGened = generateTemplateContext();
codes.push(`}\n`);
generateComponentForTemplateUsage(templateGened.cssIds);
}
else {
codeGen.push(`function __VLS_template() {\n`);
codes.push(`function __VLS_template() {\n`);
const templateUsageVars = [...getTemplateUsageVars()];
codeGen.push(`// @ts-ignore\n`);
codeGen.push(`[${templateUsageVars.join(', ')}]\n`);
codeGen.push(`return {};\n`);
codeGen.push(`}\n`);
codes.push(`// @ts-ignore\n`);
codes.push(`[${templateUsageVars.join(', ')}]\n`);
codes.push(`return {};\n`);
codes.push(`}\n`);
}
}
function writeComponentForTemplateUsage(cssIds) {
function generateComponentForTemplateUsage(cssIds) {
if (sfc.scriptSetup && scriptSetupRanges) {
codeGen.push(`const __VLS_internalComponent = (await import('${vueLibName}')).defineComponent({\n`);
codeGen.push(`setup() {\n`);
codeGen.push(`return {\n`);
codes.push(`const __VLS_internalComponent = (await import('${vueLibName}')).defineComponent({\n`);
codes.push(`setup() {\n`);
codes.push(`return {\n`);
// fill ctx from props
if (bypassDefineComponent) {
if (scriptSetupRanges.propsAssignName) {
codeGen.push(`...${scriptSetupRanges.propsAssignName},\n`);
codes.push(`...${scriptSetupRanges.propsAssignName},\n`);
}
else if (scriptSetupRanges.withDefaultsArg && scriptSetupRanges.propsTypeArg) {
codeGen.push(`...withDefaults(defineProps<`);
codes.push(`...withDefaults(defineProps<`);
addExtraReferenceVirtualCode('scriptSetup', scriptSetupRanges.propsTypeArg.start, scriptSetupRanges.propsTypeArg.end);
codeGen.push(`>(), `);
codes.push(`>(), `);
addExtraReferenceVirtualCode('scriptSetup', scriptSetupRanges.withDefaultsArg.start, scriptSetupRanges.withDefaultsArg.end);
codeGen.push(`),\n`);
codes.push(`),\n`);
}
else if (scriptSetupRanges.propsRuntimeArg) {
codeGen.push(`...defineProps(`);
codes.push(`...defineProps(`);
addExtraReferenceVirtualCode('scriptSetup', scriptSetupRanges.propsRuntimeArg.start, scriptSetupRanges.propsRuntimeArg.end);
codeGen.push(`),\n`);
codes.push(`),\n`);
}
}
// bindings
const bindingsArr = [];
bindingsArr.push({
bindings: scriptSetupRanges.bindings,
content: sfc.scriptSetup.content,
vueTag: 'scriptSetup',
});
if (scriptRanges && sfc.script) {
bindingsArr.push({
bindings: scriptRanges.bindings,
content: sfc.script.content,
vueTag: 'script',
});
}
const templateUsageVars = getTemplateUsageVars();
for (const { bindings, content } of bindingsArr) {
for (const [content, bindings] of [
[sfc.scriptSetup.content, scriptSetupRanges.bindings],
scriptRanges && sfc.script
? [sfc.script.content, scriptRanges.bindings]
: ['', []],
]) {
for (const expose of bindings) {

@@ -530,10 +548,10 @@ const varName = content.substring(expose.start, expose.end);

}
const templateStart = (0, source_map_1.getLength)(codeGen);
codeGen.push(varName);
const templateEnd = (0, source_map_1.getLength)(codeGen);
codeGen.push(`: `);
const scriptStart = (0, source_map_1.getLength)(codeGen);
codeGen.push(varName);
const scriptEnd = (0, source_map_1.getLength)(codeGen);
codeGen.push(',\n');
const templateStart = (0, source_map_1.getLength)(codes);
codes.push(varName);
const templateEnd = (0, source_map_1.getLength)(codes);
codes.push(`: `);
const scriptStart = (0, source_map_1.getLength)(codes);
codes.push(varName);
const scriptEnd = (0, source_map_1.getLength)(codes);
codes.push(',\n');
mirrorBehaviorMappings.push({

@@ -549,19 +567,19 @@ sourceRange: [scriptStart, scriptEnd],

}
codeGen.push(`};\n`); // return {
codeGen.push(`},\n`); // setup() {
codeGen.push(`});\n`); // defineComponent({
codes.push(`};\n`); // return {
codes.push(`},\n`); // setup() {
codes.push(`});\n`); // defineComponent({
}
else if (sfc.script) {
codeGen.push(`let __VLS_internalComponent!: typeof import('./${path_1.posix.basename(fileName)}')['default'];\n`);
codes.push(`let __VLS_internalComponent!: typeof import('./${path_1.posix.basename(fileName)}')['default'];\n`);
}
else {
codeGen.push(`const __VLS_internalComponent = (await import('${vueLibName}')).defineComponent({});\n`);
codes.push(`const __VLS_internalComponent = (await import('${vueLibName}')).defineComponent({});\n`);
}
}
function writeExportOptions() {
codeGen.push(`\n`);
codeGen.push(`const __VLS_componentsOption = `);
function generateExportOptions() {
codes.push(`\n`);
codes.push(`const __VLS_componentsOption = `);
if (sfc.script && scriptRanges?.exportDefault?.componentsOption) {
const componentsOption = scriptRanges.exportDefault.componentsOption;
codeGen.push([
codes.push([
sfc.script.content.substring(componentsOption.start, componentsOption.end),

@@ -577,70 +595,77 @@ 'script',

else {
codeGen.push('{}');
codes.push('{}');
}
codeGen.push(`;\n`);
codes.push(`;\n`);
}
function writeConstNameOption() {
codeGen.push(`\n`);
function generateConstNameOption() {
codes.push(`\n`);
if (sfc.script && scriptRanges?.exportDefault?.nameOption) {
const nameOption = scriptRanges.exportDefault.nameOption;
codeGen.push(`const __VLS_name = `);
codeGen.push(`${sfc.script.content.substring(nameOption.start, nameOption.end)} as const`);
codeGen.push(`;\n`);
codes.push(`const __VLS_name = `);
codes.push(`${sfc.script.content.substring(nameOption.start, nameOption.end)} as const`);
codes.push(`;\n`);
}
else if (sfc.scriptSetup) {
codeGen.push(`let __VLS_name!: '${path_1.posix.basename(fileName.substring(0, fileName.lastIndexOf('.')))}';\n`);
codes.push(`let __VLS_name!: '${path_1.posix.basename(fileName.substring(0, fileName.lastIndexOf('.')))}';\n`);
}
else {
codeGen.push(`const __VLS_name = undefined;\n`);
codes.push(`const __VLS_name = undefined;\n`);
}
}
function writeTemplateContext() {
function generateTemplateContext() {
const useGlobalThisTypeInCtx = fileName.endsWith('.html');
codeGen.push(`let __VLS_any: any;\n`);
codeGen.push(`let __VLS_ctx!: ${useGlobalThisTypeInCtx ? 'typeof globalThis &' : ''}`);
codes.push(`let __VLS_ctx!: ${useGlobalThisTypeInCtx ? 'typeof globalThis &' : ''}`);
if (sfc.scriptSetup) {
codeGen.push(`InstanceType<import('./__VLS_types.js').PickNotAny<typeof __VLS_publicComponent, new () => {}>> & `);
codes.push(`InstanceType<import('./__VLS_types.js').PickNotAny<typeof __VLS_publicComponent, new () => {}>> & `);
}
codeGen.push(`InstanceType<import('./__VLS_types.js').PickNotAny<typeof __VLS_internalComponent, new () => {}>> & {\n`);
codes.push(`InstanceType<import('./__VLS_types.js').PickNotAny<typeof __VLS_internalComponent, new () => {}>> & {\n`);
/* CSS Module */
for (const cssModule of cssModuleClasses) {
codeGen.push(`${cssModule.style.module}: Record<string, string> & import('./__VLS_types.js').Prettify<{}`);
codes.push(`${cssModule.style.module}: Record<string, string> & import('./__VLS_types.js').Prettify<{}`);
for (const classNameRange of cssModule.classNameRanges) {
writeCssClassProperty(cssModule.index, cssModule.style.content.substring(classNameRange.start + 1, classNameRange.end), classNameRange, 'string', false);
generateCssClassProperty(cssModule.index, cssModule.style.content.substring(classNameRange.start + 1, classNameRange.end), classNameRange, 'string', false);
}
codeGen.push('>;\n');
codes.push('>;\n');
}
codeGen.push(`};\n`);
codes.push(`};\n`);
/* Components */
codeGen.push('/* Components */\n');
codeGen.push(`let __VLS_localComponents!: NonNullable<typeof __VLS_internalComponent extends { components: infer C } ? C : {}> & typeof __VLS_componentsOption & typeof __VLS_ctx;\n`);
codeGen.push(`let __VLS_otherComponents!: typeof __VLS_localComponents & import('./__VLS_types.js').GlobalComponents;\n`);
codeGen.push(`let __VLS_own!: import('./__VLS_types.js').SelfComponent<typeof __VLS_name, typeof __VLS_internalComponent & typeof __VLS_publicComponent & (new () => { ${(0, shared_2.getSlotsPropertyName)(vueCompilerOptions.target ?? 3)}: typeof __VLS_slots })>;\n`);
codeGen.push(`let __VLS_components!: typeof __VLS_otherComponents & Omit<typeof __VLS_own, keyof typeof __VLS_otherComponents>;\n`);
codes.push('/* Components */\n');
codes.push(`let __VLS_localComponents!: NonNullable<typeof __VLS_internalComponent extends { components: infer C } ? C : {}> & typeof __VLS_componentsOption & typeof __VLS_ctx;\n`);
codes.push(`let __VLS_otherComponents!: typeof __VLS_localComponents & import('./__VLS_types.js').GlobalComponents;\n`);
codes.push(`let __VLS_own!: import('./__VLS_types.js').SelfComponent<typeof __VLS_name, typeof __VLS_internalComponent & typeof __VLS_publicComponent & (new () => { ${(0, shared_2.getSlotsPropertyName)(vueCompilerOptions.target ?? 3)}: typeof __VLS_slots })>;\n`);
codes.push(`let __VLS_components!: typeof __VLS_otherComponents & Omit<typeof __VLS_own, keyof typeof __VLS_otherComponents>;\n`);
/* Style Scoped */
codeGen.push('/* Style Scoped */\n');
codeGen.push('type __VLS_StyleScopedClasses = {}');
codes.push('/* Style Scoped */\n');
codes.push('type __VLS_StyleScopedClasses = {}');
for (const scopedCss of cssScopedClasses) {
for (const classNameRange of scopedCss.classNameRanges) {
writeCssClassProperty(scopedCss.index, scopedCss.style.content.substring(classNameRange.start + 1, classNameRange.end), classNameRange, 'boolean', true);
generateCssClassProperty(scopedCss.index, scopedCss.style.content.substring(classNameRange.start + 1, classNameRange.end), classNameRange, 'boolean', true);
}
}
codeGen.push(';\n');
codeGen.push('let __VLS_styleScopedClasses!: __VLS_StyleScopedClasses | keyof __VLS_StyleScopedClasses | (keyof __VLS_StyleScopedClasses)[];\n');
codeGen.push(`/* CSS variable injection */\n`);
const cssIds = writeCssVars();
codeGen.push(`/* CSS variable injection end */\n`);
codes.push(';\n');
codes.push('let __VLS_styleScopedClasses!: __VLS_StyleScopedClasses | keyof __VLS_StyleScopedClasses | (keyof __VLS_StyleScopedClasses)[];\n');
codes.push(`/* CSS variable injection */\n`);
const cssIds = generateCssVars();
codes.push(`/* CSS variable injection end */\n`);
if (htmlGen) {
for (const s of htmlGen.codeGen) {
codeGen.push(s);
for (const s of htmlGen.codes) {
codes.push(s);
}
}
if (!htmlGen) {
codeGen.push(`const __VLS_slots = {};\n`);
codes.push(`// no template\n`);
if (scriptSetupRanges?.slotsTypeArg && sfc.scriptSetup) {
codes.push(`let __VLS_slots!: `);
addExtraReferenceVirtualCode('scriptSetup', scriptSetupRanges.slotsTypeArg.start, scriptSetupRanges.slotsTypeArg.end);
codes.push(`;\n`);
}
else {
codes.push(`const __VLS_slots = {};\n`);
}
}
codeGen.push(`return __VLS_slots;\n`);
codes.push(`return __VLS_slots;\n`);
return { cssIds };
function writeCssClassProperty(styleIndex, className, classRange, propertyType, optional) {
codeGen.push(`\n & { `);
codeGen.push([
function generateCssClassProperty(styleIndex, className, classRange, propertyType, optional) {
codes.push(`\n & { `);
codes.push([
'',

@@ -654,4 +679,4 @@ 'style_' + styleIndex,

]);
codeGen.push(`'`);
codeGen.push([
codes.push(`'`);
codes.push([
className,

@@ -663,9 +688,9 @@ 'style_' + styleIndex,

rename: {
normalize: beforeCssRename,
apply: doCssRename,
normalize: normalizeCssRename,
apply: applyCssRename,
},
},
]);
codeGen.push(`'`);
codeGen.push([
codes.push(`'`);
codes.push([
'',

@@ -676,6 +701,6 @@ 'style_' + styleIndex,

]);
codeGen.push(`${optional ? '?' : ''}: ${propertyType}`);
codeGen.push(` }`);
codes.push(`${optional ? '?' : ''}: ${propertyType}`);
codes.push(` }`);
}
function writeCssVars() {
function generateCssVars() {
const emptyLocalVars = {};

@@ -688,6 +713,6 @@ const identifiers = new Set();

if (fragOffset === undefined) {
codeGen.push(frag);
codes.push(frag);
}
else {
codeGen.push([
codes.push([
frag,

@@ -702,3 +727,3 @@ cssVar.style.name,

}, emptyLocalVars, identifiers, vueCompilerOptions);
codeGen.push(';\n');
codes.push(';\n');
}

@@ -736,10 +761,30 @@ }

}
function addVirtualCode(vueTag, start, end) {
codes.push([
sfc[vueTag].content.substring(start, end),
vueTag,
start,
language_core_1.FileRangeCapabilities.full, // diagnostic also working for setup() returns unused in template checking
]);
}
function addExtraReferenceVirtualCode(vueTag, start, end) {
codes.push([
sfc[vueTag].content.substring(start, end),
vueTag,
start,
{
references: true,
definition: true,
rename: true,
},
]);
}
}
exports.generate = generate;
function beforeCssRename(newName) {
function normalizeCssRename(newName) {
return newName.startsWith('.') ? newName.slice(1) : newName;
}
function doCssRename(newName) {
function applyCssRename(newName) {
return '.' + newName;
}
//# sourceMappingURL=script.js.map

@@ -5,6 +5,6 @@ import { Segment } from '@volar/source-map';

import { VueCompilerOptions } from '../types';
export declare function generate(ts: typeof import('typescript/lib/tsserverlibrary'), vueCompilerOptions: VueCompilerOptions, sourceTemplate: string, sourceLang: string, templateAst: CompilerDOM.RootNode, hasScriptSetup: boolean, cssScopedClasses?: string[]): {
codeGen: Segment<FileRangeCapabilities>[];
formatCodeGen: Segment<FileRangeCapabilities>[];
cssCodeGen: Segment<FileRangeCapabilities>[];
export declare function generate(ts: typeof import('typescript/lib/tsserverlibrary'), vueCompilerOptions: VueCompilerOptions, sourceTemplate: string, sourceLang: string, templateAst: CompilerDOM.RootNode, hasScriptSetupSlots: boolean, cssScopedClasses?: string[]): {
codes: Segment<FileRangeCapabilities>[];
formatCodes: Segment<FileRangeCapabilities>[];
cssCodes: Segment<FileRangeCapabilities>[];
tagNames: Record<string, number[]>;

@@ -11,0 +11,0 @@ identifiers: Set<string>;

@@ -11,5 +11,7 @@ import type * as ts from 'typescript/lib/tsserverlibrary';

withDefaultsArg: TextRange | undefined;
defineProps: TextRange | undefined;
propsAssignName: string | undefined;
propsRuntimeArg: TextRange | undefined;
propsTypeArg: TextRange | undefined;
slotsTypeArg: TextRange | undefined;
emitsAssignName: string | undefined;

@@ -20,3 +22,2 @@ emitsRuntimeArg: TextRange | undefined;

exposeRuntimeArg: TextRange | undefined;
exposeTypeArg: TextRange | undefined;
};

@@ -23,0 +24,0 @@ export declare function parseBindingRanges(ts: typeof import('typescript/lib/tsserverlibrary'), sourceFile: ts.SourceFile, isType: boolean): TextRange[];

@@ -10,4 +10,6 @@ "use strict";

let propsAssignName;
let defineProps;
let propsRuntimeArg;
let propsTypeArg;
let slotsTypeArg;
let emitsAssignName;

@@ -17,3 +19,2 @@ let emitsRuntimeArg;

let exposeRuntimeArg;
let exposeTypeArg;
let emitsTypeNums = -1;

@@ -44,5 +45,7 @@ const bindings = parseBindingRanges(ts, ast, false);

withDefaultsArg,
defineProps,
propsAssignName,
propsRuntimeArg,
propsTypeArg,
slotsTypeArg,
emitsAssignName,

@@ -53,3 +56,2 @@ emitsRuntimeArg,

exposeRuntimeArg,
exposeTypeArg,
};

@@ -64,4 +66,8 @@ function _getStartEnd(node) {

if (vueCompilerOptions.macros.defineProps.includes(callText)
|| vueCompilerOptions.macros.defineSlots.includes(callText)
|| vueCompilerOptions.macros.defineEmits.includes(callText)
|| vueCompilerOptions.macros.defineExpose.includes(callText)) {
if (vueCompilerOptions.macros.defineProps.includes(callText)) {
defineProps = _getStartEnd(node);
}
if (node.arguments.length) {

@@ -93,2 +99,5 @@ const runtimeArg = node.arguments[0];

}
if (vueCompilerOptions.macros.defineSlots.includes(callText)) {
slotsTypeArg = _getStartEnd(typeArg);
}
else if (vueCompilerOptions.macros.defineEmits.includes(callText)) {

@@ -103,5 +112,2 @@ emitsTypeArg = _getStartEnd(typeArg);

}
else if (vueCompilerOptions.macros.defineExpose.includes(callText)) {
exposeTypeArg = _getStartEnd(typeArg);
}
}

@@ -108,0 +114,0 @@ }

@@ -17,8 +17,8 @@ "use strict";

const sfcBlockReg = /\<(script|style)\b[\s\S]*?\>([\s\S]*?)\<\/\1\>/g;
const codeGen = [];
const codes = [];
for (const match of content.matchAll(sfcBlockReg)) {
if (match.index !== undefined) {
const matchText = match[0];
codeGen.push([matchText, undefined, match.index]);
codeGen.push('\n\n');
codes.push([matchText, undefined, match.index]);
codes.push('\n\n');
content = content.substring(0, match.index) + ' '.repeat(matchText.length) + content.substring(match.index + matchText.length);

@@ -32,7 +32,7 @@ }

.replace(/\[[\s\S]*?\]\([\s\S]*?\)/g, match => ' '.repeat(match.length));
codeGen.push('<template>\n');
codeGen.push([content, undefined, 0]);
codeGen.push('\n</template>');
const file2VueSourceMap = new source_map_1.SourceMap((0, source_map_1.buildMappings)(codeGen));
const sfc = (0, parseSfc_1.parse)((0, source_map_1.toString)(codeGen));
codes.push('<template>\n');
codes.push([content, undefined, 0]);
codes.push('\n</template>');
const file2VueSourceMap = new source_map_1.SourceMap((0, source_map_1.buildMappings)(codes));
const sfc = (0, parseSfc_1.parse)((0, source_map_1.toString)(codes));
if (sfc.descriptor.template) {

@@ -39,0 +39,0 @@ transformRange(sfc.descriptor.template);

@@ -136,2 +136,3 @@ "use strict";

function tryUpdateNodeLoc(loc) {
delete loc.__endOffset;
if (withinChangeRange(loc)) {

@@ -142,2 +143,3 @@ loc.source =

+ loc.source.substring(change.end - loc.start.offset);
loc.__endOffset = loc.end.offset;
loc.end.offset += lengthDiff;

@@ -147,2 +149,3 @@ return true;

else if (change.end <= loc.start.offset) {
loc.__endOffset = loc.end.offset;
loc.start.offset += lengthDiff;

@@ -158,3 +161,4 @@ loc.end.offset += lengthDiff;

function withinChangeRange(loc) {
return change.start >= loc.start.offset && change.end <= loc.end.offset;
const originalLocEnd = loc.__endOffset ?? loc.end.offset;
return change.start >= loc.start.offset && change.end <= originalLocEnd;
}

@@ -161,0 +165,0 @@ },

@@ -42,3 +42,3 @@ "use strict";

if (tsx) {
embeddedFile.content = [...tsx.codeGen];
embeddedFile.content = [...tsx.codes];
embeddedFile.extraMappings = [...tsx.extraMappings];

@@ -59,3 +59,3 @@ embeddedFile.mirrorBehaviorMappings = [...tsx.mirrorBehaviorMappings];

if (_tsx.htmlGen.value) {
embeddedFile.content = [..._tsx.htmlGen.value.formatCodeGen];
embeddedFile.content = [..._tsx.htmlGen.value.formatCodes];
}

@@ -79,3 +79,3 @@ for (const cssVar of _tsx.cssVars.value) {

if (_tsx.htmlGen.value) {
embeddedFile.content = [..._tsx.htmlGen.value.cssCodeGen];
embeddedFile.content = [..._tsx.htmlGen.value.cssCodes];
}

@@ -120,8 +120,11 @@ }

const htmlGen = (0, reactivity_1.computed)(() => {
const templateAst = _sfc.templateAst;
if (!templateAst)
if (!_sfc.templateAst)
return;
return templateGen.generate(ts, vueCompilerOptions, _sfc.template?.content ?? '', _sfc.template?.lang ?? 'html', templateAst, !!_sfc.scriptSetup, Object.values(cssScopedClasses.value).map(style => style.classNames).flat());
return templateGen.generate(ts, vueCompilerOptions, _sfc.template?.content ?? '', _sfc.template?.lang ?? 'html', _sfc.templateAst, hasScriptSetupSlots.value, Object.values(cssScopedClasses.value).map(style => style.classNames).flat());
});
const tsxGen = (0, reactivity_1.computed)(() => (0, script_1.generate)(ts, fileName, _sfc, lang.value, scriptRanges.value, scriptSetupRanges.value, cssVars.value, cssModuleClasses.value, cssScopedClasses.value, htmlGen.value, compilerOptions, vueCompilerOptions));
const hasScriptSetupSlots = (0, reactivity_1.shallowRef)(false); // remove when https://github.com/vuejs/core/pull/5912 merged
const tsxGen = (0, reactivity_1.computed)(() => {
hasScriptSetupSlots.value = !!scriptSetupRanges.value?.slotsTypeArg;
return (0, script_1.generate)(ts, fileName, _sfc, lang.value, scriptRanges.value, scriptSetupRanges.value, cssVars.value, cssModuleClasses.value, cssScopedClasses.value, htmlGen.value, compilerOptions, vueCompilerOptions);
});
return {

@@ -128,0 +131,0 @@ lang,

@@ -26,2 +26,3 @@ import * as embedded from '@volar/language-core';

defineProps: string[];
defineSlots: string[];
defineEmits: string[];

@@ -28,0 +29,0 @@ defineExpose: string[];

@@ -8,10 +8,4 @@ "use strict";

const libName = (0, shared_1.getVueLibraryName)(vueVersion);
const slots = (0, shared_1.getSlotsPropertyName)(vueVersion);
return `
// @ts-nocheck
import type {
FunctionalComponent,
EmitsOptions,
DefineComponent,
SetupContext,
ObjectDirective,

@@ -27,3 +21,2 @@ FunctionDirective,

export type PickNotAny<A, B> = IsAny<A> extends true ? B : A;
type AnyArray<T = any> = T[] | readonly T[];
type ForableSource<T> = [

@@ -63,24 +56,21 @@ T extends { [Symbol.iterator](): Iterator<infer T1> } ? T1 : T[keyof T], // item

// TODO: make it stricter between class component type and functional component type
export type ExtractComponentSlots<T> =
IsAny<T> extends true ? Record<string, any>
: T extends { ${slots}?: infer S } ? S
: T extends { children?: infer S } ? S
: T extends { [K in keyof PickNotAny<JSX.ElementChildrenAttribute, {}>]?: infer S } ? S
: Record<string, any>;
export type SelfComponent<N, C> = string extends N ? {} : N extends string ? { [P in N]: C } : {};
export type WithComponent<N0 extends string, Components, N1, N2 = unknown, N3 = unknown> =
N1 extends keyof Components ? { [K in N0]: Components[N1] } :
N2 extends keyof Components ? { [K in N0]: Components[N2] } :
N3 extends keyof Components ? { [K in N0]: Components[N3] } :
${vueCompilerOptions.strictTemplates ? '{}' : '{ [K in N0]: any }'};
export type FillingEventArg_ParametersLength<E extends (...args: any) => any> = IsAny<Parameters<E>> extends true ? -1 : Parameters<E>['length'];
export type FillingEventArg<E> = E extends (...args: any) => any ? FillingEventArg_ParametersLength<E> extends 0 ? ($event?: undefined) => ReturnType<E> : E : E;
export type ReturnVoid<T> = T extends (...payload: infer P) => any ? (...payload: P) => void : (...args: any) => void;
export type EmitEvent2<F, E> =
export type EmitEvent<F, E> =
F extends {
(event: E, ...payload: infer P): infer R
(event: E, ...payload: infer P): any
} ? (...payload: P) => void
: F extends {
(event: E, ...payload: infer P): infer R
(event: E, ...payload: infer P): any
(...args: any): any
} ? (...payload: P) => void
: F extends {
(event: E, ...payload: infer P): infer R
(event: E, ...payload: infer P): any
(...args: any): any

@@ -90,3 +80,3 @@ (...args: any): any

: F extends {
(event: E, ...payload: infer P): infer R
(event: E, ...payload: infer P): any
(...args: any): any

@@ -97,42 +87,18 @@ (...args: any): any

: unknown | '[Type Warning] Volar could not infer $emit event more than 4 overloads without DefineComponent. see https://github.com/johnsoncodehk/volar/issues/60';
export type EmitEvent<T, E> =
T extends DefineComponent<infer _, any, any, any, any, any, any, infer E2> ? EmitEvent_3<E2, E>
: T extends FunctionalComponent<infer _, infer E2> ? EmitEvent_3<E2, E>
: T extends FunctionalComponent<infer _, infer E> ? EmitEvent2<SetupContext<E>['emit'], E>
: unknown;
export type EmitEvent_3<E2, E> =
EmitsOptions extends E2 ? unknown
: E2 extends AnyArray<infer K> ? (E extends K ? (...args: any) => void : unknown) // emits: ['event-1', 'event-2']
: E extends keyof E2 ? ReturnVoid<E2[E]> // emits: { 'event-1': () => true, 'event-2': () => true }
: unknown
export type FirstFunction<F0 = void, F1 = void, F2 = void, F3 = void, F4 = void> =
NonNullable<F0> extends (Function | AnyArray<Function>) ? F0 :
NonNullable<F1> extends (Function | AnyArray<Function>) ? F1 :
NonNullable<F2> extends (Function | AnyArray<Function>) ? F2 :
NonNullable<F3> extends (Function | AnyArray<Function>) ? F3 :
NonNullable<F4> extends (Function | AnyArray<Function>) ? F4 :
unknown;
export type SelfComponent<N, C> = string extends N ? {} : N extends string ? { [P in N]: C } : {};
export type WithComponent<N0 extends string, Components, N1, N2 = unknown, N3 = unknown> =
N1 extends keyof Components ? { [K in N0]: Components[N1] } :
N2 extends keyof Components ? { [K in N0]: Components[N2] } :
N3 extends keyof Components ? { [K in N0]: Components[N3] } :
${vueCompilerOptions.strictTemplates ? '{}' : '{ [K in N0]: any }'};
export declare function asFunctionalComponent<T>(t: T):
T extends new (...args: any) => { $props: infer Props } ? (_: ${vueCompilerOptions.strictTemplates ? '' : 'Record<string, unknown> &'} Props) => any
: T extends (props: infer Props, ...args: any) => any ? T
: T extends (...args: any) => { props: infer Props } ? (_: ${vueCompilerOptions.strictTemplates ? '' : 'Record<string, unknown> &'} Props) => any
: T extends new (...args: any) => any ? (_: ${vueCompilerOptions.strictTemplates ? '' : 'Record<string, unknown> &'} {}) => any
: T extends (...args: any) => any ? (_: ${vueCompilerOptions.strictTemplates ? '' : 'Record<string, unknown> &'} {}) => any
: (_: T) => any; // IntrinsicElement
export type InstanceProps<I, C> = I extends { $props: infer Props } ? Props & Record<string, unknown> : C & Record<string, unknown>;
export type EventObject<I, K1 extends string, C, E1> = {
[K in K1]: FillingEventArg<
FirstFunction<
EmitEvent<C, K1>,
E1,
I extends { $emit: infer Emit } ? EmitEvent2<Emit, K1> : unknown
>
export declare function asFunctionalComponent<T, K>(t: T, instance?: K):
T extends (...args: any) => any ? T
: K extends { $props?: infer Props, $slots?: infer Slots, $emit?: infer Emit }
? (props: Props, ctx?: { attrs?: any, expose?: any, slots?: Slots, emit?: Emit }) => JSX.Element & { __ctx?: typeof ctx, __props?: typeof props }
: (_: T) => { __ctx?: { attrs?: undefined, expose?: undefined, slots?: undefined, emit?: undefined }, __props?: T }; // IntrinsicElement
export declare function pickEvent<Emit, K, E>(emit: Emit, emitKey: K, event: E): FillingEventArg<
PickNotAny<
asFunctionOrAny<E>,
asFunctionOrAny<EmitEvent<Emit, K>>
>
};
>;
export declare function pickFunctionalComponentCtx<T, K>(comp: T, compInstance: K): PickNotAny<
K extends { __ctx?: infer Ctx } ? Ctx : any,
T extends (props: any, ctx: infer Ctx) => any ? Ctx : any
>;
type asFunctionOrAny<F> = ((...args: any) => any) extends F ? F : any;
`.trim();

@@ -144,3 +110,4 @@ }

function genConstructorOverloads(name = 'ConstructorOverloads', nums) {
let code = `type ${name}<T> =\n`;
let code = '';
code += `type ${name}<T> =\n`;
if (nums === undefined) {

@@ -147,0 +114,0 @@ for (let i = 8; i >= 1; i--) {

@@ -83,12 +83,10 @@ "use strict";

if (target === 'auto') {
try {
const resolvedPath = resolvePath('vue/package.json');
if (resolvedPath) {
const vuePackageJson = require(resolvedPath);
const versionNumbers = vuePackageJson.version.split('.');
result.target = Number(versionNumbers[0] + '.' + versionNumbers[1]);
}
const resolvedPath = resolvePath('vue/package.json');
if (resolvedPath) {
const vuePackageJson = require(resolvedPath);
const versionNumbers = vuePackageJson.version.split('.');
result.target = Number(versionNumbers[0] + '.' + versionNumbers[1]);
}
catch (error) {
console.warn('Load vue package.json failed', error);
else {
// console.warn('Load vue/package.json failed from', folder);
}

@@ -132,7 +130,7 @@ }

else {
console.warn('failed to resolve path:', scriptPath, 'require.resolve is not supported in web');
// console.warn('failed to resolve path:', scriptPath, 'require.resolve is not supported in web');
}
}
catch (error) {
console.warn(error);
// console.warn(error);
}

@@ -186,2 +184,3 @@ }

defineProps: ['defineProps'],
defineSlots: ['defineSlots'],
defineEmits: ['defineEmits'],

@@ -188,0 +187,0 @@ defineExpose: ['defineExpose'],

{
"name": "@volar/vue-language-core",
"version": "1.3.8",
"version": "1.3.9",
"main": "out/index.js",

@@ -16,8 +16,8 @@ "license": "MIT",

"dependencies": {
"@volar/language-core": "1.4.0-alpha.5",
"@volar/source-map": "1.4.0-alpha.5",
"@vue/compiler-dom": "^3.2.47",
"@vue/compiler-sfc": "^3.2.47",
"@vue/reactivity": "^3.2.47",
"@vue/shared": "^3.2.47",
"@volar/language-core": "1.4.0-alpha.6",
"@volar/source-map": "1.4.0-alpha.6",
"@vue/compiler-dom": "3.3.0-alpha.6",
"@vue/compiler-sfc": "3.3.0-alpha.6",
"@vue/reactivity": "3.3.0-alpha.6",
"@vue/shared": "3.3.0-alpha.6",
"minimatch": "^6.1.6",

@@ -30,3 +30,3 @@ "muggle-string": "^0.2.2",

},
"gitHead": "82721965355e6d0810130ec140d4d2f909d649c6"
"gitHead": "592faa8030c9b3cd86480e412f14a16d71c8547b"
}

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc