@vue/language-core 3.0.0-alpha.0 → 3.0.0-alpha.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/lib/codegen/globalTypes.js +47 -29
  2. package/lib/codegen/script/component.js +21 -9
  3. package/lib/codegen/script/index.js +1 -1
  4. package/lib/codegen/script/scriptSetup.js +1 -10
  5. package/lib/codegen/script/src.js +4 -3
  6. package/lib/codegen/script/styleModulesType.d.ts +4 -0
  7. package/lib/codegen/script/styleModulesType.js +34 -0
  8. package/lib/codegen/script/template.js +3 -5
  9. package/lib/codegen/template/context.d.ts +26 -17
  10. package/lib/codegen/template/context.js +87 -53
  11. package/lib/codegen/template/element.d.ts +2 -2
  12. package/lib/codegen/template/element.js +19 -27
  13. package/lib/codegen/template/elementChildren.d.ts +1 -1
  14. package/lib/codegen/template/elementChildren.js +4 -6
  15. package/lib/codegen/template/elementDirectives.js +1 -3
  16. package/lib/codegen/template/elementEvents.d.ts +1 -1
  17. package/lib/codegen/template/elementEvents.js +13 -10
  18. package/lib/codegen/template/elementProps.js +1 -1
  19. package/lib/codegen/template/index.js +20 -7
  20. package/lib/codegen/template/interpolation.d.ts +1 -1
  21. package/lib/codegen/template/interpolation.js +52 -52
  22. package/lib/codegen/template/slotOutlet.js +1 -2
  23. package/lib/codegen/template/templateChild.d.ts +1 -1
  24. package/lib/codegen/template/templateChild.js +12 -46
  25. package/lib/codegen/template/vFor.js +5 -10
  26. package/lib/codegen/template/vIf.js +2 -10
  27. package/lib/codegen/template/vSlot.d.ts +1 -2
  28. package/lib/codegen/template/vSlot.js +111 -59
  29. package/lib/codegen/utils/index.d.ts +1 -2
  30. package/lib/codegen/utils/index.js +0 -16
  31. package/lib/parsers/scriptSetupRanges.js +8 -6
  32. package/lib/plugins/vue-template-inline-css.js +1 -1
  33. package/lib/plugins/vue-template-inline-ts.js +2 -2
  34. package/lib/plugins/vue-tsx.d.ts +25 -16
  35. package/lib/plugins/vue-tsx.js +31 -19
  36. package/lib/types.d.ts +2 -1
  37. package/lib/utils/forEachElementNode.d.ts +1 -0
  38. package/lib/utils/forEachElementNode.js +3 -0
  39. package/lib/utils/ts.js +1 -0
  40. package/package.json +2 -2
@@ -13,7 +13,7 @@ function getGlobalTypesFileName({ lib, target, checkUnknownProps, checkUnknownEv
13
13
  ].map(v => (typeof v === 'boolean' ? Number(v) : v)).join('_') + '.d.ts';
14
14
  }
15
15
  function generateGlobalTypes({ lib, target, checkUnknownProps, checkUnknownEvents, checkUnknownComponents, }) {
16
- const fnPropsType = `(K extends { $props: infer Props } ? Props : any)${checkUnknownProps ? '' : ' & Record<string, unknown>'}`;
16
+ const fnPropsType = `(T extends { $props: infer Props } ? Props : {})${checkUnknownProps ? '' : ' & Record<string, unknown>'}`;
17
17
  let text = ``;
18
18
  if (target < 3.5) {
19
19
  text += `
@@ -51,10 +51,31 @@ function generateGlobalTypes({ lib, target, checkUnknownProps, checkUnknownEvent
51
51
  N2 extends keyof __VLS_GlobalComponents ? N2 extends N0 ? Pick<__VLS_GlobalComponents, N0 extends keyof __VLS_GlobalComponents ? N0 : never> : { [K in N0]: __VLS_GlobalComponents[N2] } :
52
52
  N3 extends keyof __VLS_GlobalComponents ? N3 extends N0 ? Pick<__VLS_GlobalComponents, N0 extends keyof __VLS_GlobalComponents ? N0 : never> : { [K in N0]: __VLS_GlobalComponents[N3] } :
53
53
  ${checkUnknownComponents ? '{}' : '{ [K in N0]: unknown }'};
54
- type __VLS_FunctionalComponentProps<T, K> =
55
- '__ctx' extends keyof __VLS_PickNotAny<K, {}> ? K extends { __ctx?: { props?: infer P } } ? NonNullable<P> : never
56
- : T extends (props: infer P, ...args: any) => any ? P :
57
- {};
54
+ type __VLS_FunctionalComponentCtx<T, K> = __VLS_PickNotAny<'__ctx' extends keyof __VLS_PickNotAny<K, {}>
55
+ ? K extends { __ctx?: infer Ctx } ? NonNullable<Ctx> : never : any
56
+ , T extends (props: any, ctx: infer Ctx) => any ? Ctx : any
57
+ >;
58
+ type __VLS_FunctionalComponentProps<T, K> = '__ctx' extends keyof __VLS_PickNotAny<K, {}>
59
+ ? K extends { __ctx?: { props?: infer P } } ? NonNullable<P> : never
60
+ : T extends (props: infer P, ...args: any) => any ? P
61
+ : {};
62
+ type __VLS_FunctionalComponent<T> = (props: ${fnPropsType}, ctx?: any) => __VLS_Element & {
63
+ __ctx?: {
64
+ attrs?: any,
65
+ slots?: T extends { ${(0, shared_1.getSlotsPropertyName)(target)}: infer Slots } ? Slots : Record<string, any>,
66
+ emit?: T extends { $emit: infer Emit } ? Emit : {},
67
+ props?: ${fnPropsType},
68
+ expose?: (exposed: T) => void,
69
+ }
70
+ };
71
+ type __VLS_NormalizeSlotReturns<S, R = NonNullable<S> extends (...args: any) => infer K ? K : any> = R extends any[] ? {
72
+ [K in keyof R]: R[K] extends infer V
73
+ ? V extends Element ? V
74
+ : V extends new (...args: any) => infer R ? ReturnType<__VLS_FunctionalComponent<R>>
75
+ : V extends (...args: any) => infer R ? R
76
+ : any
77
+ : never
78
+ } : R;
58
79
  type __VLS_IsFunction<T, K> = K extends keyof T
59
80
  ? __VLS_IsAny<T[K]> extends false
60
81
  ? unknown extends T[K]
@@ -62,13 +83,13 @@ function generateGlobalTypes({ lib, target, checkUnknownProps, checkUnknownEvent
62
83
  : true
63
84
  : false
64
85
  : false;
65
- type __VLS_NormalizeComponentEvent<Props, Events, onEvent extends keyof Props, Event extends keyof Events, CamelizedEvent extends keyof Events> = (
86
+ type __VLS_NormalizeComponentEvent<Props, Emits, onEvent extends keyof Props, Event extends keyof Emits, CamelizedEvent extends keyof Emits> = (
66
87
  __VLS_IsFunction<Props, onEvent> extends true
67
88
  ? Props
68
- : __VLS_IsFunction<Events, Event> extends true
69
- ? { [K in onEvent]?: Events[Event] }
70
- : __VLS_IsFunction<Events, CamelizedEvent> extends true
71
- ? { [K in onEvent]?: Events[CamelizedEvent] }
89
+ : __VLS_IsFunction<Emits, Event> extends true
90
+ ? { [K in onEvent]?: Emits[Event] }
91
+ : __VLS_IsFunction<Emits, CamelizedEvent> extends true
92
+ ? { [K in onEvent]?: Emits[CamelizedEvent] }
72
93
  : Props
73
94
  )${checkUnknownEvents ? '' : ' & Record<string, unknown>'};
74
95
  // fix https://github.com/vuejs/language-tools/issues/926
@@ -94,11 +115,16 @@ function generateGlobalTypes({ lib, target, checkUnknownProps, checkUnknownEvent
94
115
  }
95
116
  >
96
117
  >;
118
+ type __VLS_ResolveEmits<
119
+ Comp,
120
+ Emits,
121
+ TypeEmits = ${target >= 3.6 ? `Comp extends { __typeEmits?: infer T } ? unknown extends T ? {} : import('${lib}').ShortEmitsToObject<T> : {}` : `{}`},
122
+ NormalizedEmits = __VLS_NormalizeEmits<Emits> extends infer E ? string extends keyof E ? {} : E : never,
123
+ > = __VLS_SpreadMerge<NormalizedEmits, TypeEmits>;
124
+ type __VLS_ResolveDirectives<T> = {
125
+ [K in Exclude<keyof T, keyof __VLS_GlobalDirectives> & string as \`v\${Capitalize<K>}\`]: T[K];
126
+ };
97
127
  type __VLS_PrettifyGlobal<T> = { [K in keyof T]: T[K]; } & {};
98
- type __VLS_PickFunctionalComponentCtx<T, K> = NonNullable<__VLS_PickNotAny<
99
- '__ctx' extends keyof __VLS_PickNotAny<K, {}> ? K extends { __ctx?: infer Ctx } ? Ctx : never : any
100
- , T extends (props: any, ctx: infer Ctx) => any ? Ctx : any
101
- >>;
102
128
  type __VLS_UseTemplateRef<T> = Readonly<import('${lib}').ShallowRef<T | null>>;
103
129
 
104
130
  function __VLS_getVForSourceType<T extends number | string | any[] | Iterable<any>>(source: T): [
@@ -114,10 +140,8 @@ function generateGlobalTypes({ lib, target, checkUnknownProps, checkUnknownEvent
114
140
  key: keyof T,
115
141
  index: number,
116
142
  ][];
117
- // @ts-ignore
118
- function __VLS_getSlotParams<T>(slot: T): Parameters<__VLS_PickNotAny<NonNullable<T>, (...args: any[]) => any>>;
119
- // @ts-ignore
120
- function __VLS_getSlotParam<T>(slot: T): Parameters<__VLS_PickNotAny<NonNullable<T>, (...args: any[]) => any>>[0];
143
+ function __VLS_getSlotParameters<S, D extends S>(slot: S, decl?: D):
144
+ __VLS_PickNotAny<NonNullable<D>, (...args: any) => any> extends (...args: infer P) => any ? P : any[];
121
145
  function __VLS_asFunctionalDirective<T>(dir: T): T extends import('${lib}').ObjectDirective
122
146
  ? NonNullable<T['created' | 'beforeMount' | 'mounted' | 'beforeUpdate' | 'updated' | 'beforeUnmount' | 'unmounted']>
123
147
  : T extends (...args: any) => any
@@ -125,19 +149,13 @@ function generateGlobalTypes({ lib, target, checkUnknownProps, checkUnknownEvent
125
149
  : (arg1: unknown, arg2: unknown, arg3: unknown, arg4: unknown) => void;
126
150
  function __VLS_makeOptional<T>(t: T): { [K in keyof T]?: T[K] };
127
151
  function __VLS_asFunctionalComponent<T, K = T extends new (...args: any) => any ? InstanceType<T> : unknown>(t: T, instance?: K):
128
- T extends new (...args: any) => any
129
- ? (props: ${fnPropsType}, ctx?: any) => __VLS_Element & {
130
- __ctx?: {
131
- attrs?: any;
132
- slots?: K extends { ${(0, shared_1.getSlotsPropertyName)(target)}: infer Slots } ? Slots : any;
133
- emit?: K extends { $emit: infer Emit } ? Emit : any;
134
- expose?(exposed: K): void;
135
- props?: ${fnPropsType};
136
- }
137
- }
152
+ T extends new (...args: any) => any ? __VLS_FunctionalComponent<K>
138
153
  : T extends () => any ? (props: {}, ctx?: any) => ReturnType<T>
154
+ ${(target === 2.7
155
+ ? `: T extends import('vue').AsyncComponent ? (props: {}, ctx?: any) => any`
156
+ : ``)}
139
157
  : T extends (...args: any) => any ? T
140
- : (_: {}${checkUnknownProps ? '' : ' & Record<string, unknown>'}, ctx?: any) => { __ctx?: { attrs?: any, expose?: any, slots?: any, emit?: any, props?: {}${checkUnknownProps ? '' : ' & Record<string, unknown>'} } };
158
+ : __VLS_FunctionalComponent<{}>;
141
159
  function __VLS_functionalComponentArgsRest<T extends (...args: any) => any>(t: T): 2 extends Parameters<T>['length'] ? [any] : [];
142
160
  function __VLS_asFunctionalElement<T>(tag: T, endTag?: T): (attrs: T${checkUnknownComponents ? '' : ' & Record<string, unknown>'}) => void;
143
161
  function __VLS_asFunctionalSlot<S>(slot: S): S extends () => infer R ? (props: {}) => R : NonNullable<S>;
@@ -111,15 +111,23 @@ function* generateEmitsOption(options, scriptSetupRanges) {
111
111
  function* generatePropsOption(options, ctx, scriptSetup, scriptSetupRanges, hasEmitsOption, inheritAttrs) {
112
112
  const codes = [];
113
113
  if (ctx.generatedPropsType) {
114
- codes.push({
115
- optionExp: [
116
- `{} as `,
117
- scriptSetupRanges.withDefaults?.arg ? `${ctx.localTypes.WithDefaults}<` : '',
118
- `${ctx.localTypes.TypePropsToOption}<__VLS_PublicProps>`,
119
- scriptSetupRanges.withDefaults?.arg ? `, typeof __VLS_withDefaultsArg>` : '',
120
- ].join(''),
121
- typeOptionExp: `{} as __VLS_PublicProps`,
122
- });
114
+ if (options.vueCompilerOptions.target >= 3.6) {
115
+ codes.push({
116
+ optionExp: '{}',
117
+ typeOptionExp: `{} as __VLS_PublicProps`,
118
+ });
119
+ }
120
+ else {
121
+ codes.push({
122
+ optionExp: [
123
+ `{} as `,
124
+ scriptSetupRanges.withDefaults?.arg ? `${ctx.localTypes.WithDefaults}<` : '',
125
+ `${ctx.localTypes.TypePropsToOption}<__VLS_PublicProps>`,
126
+ scriptSetupRanges.withDefaults?.arg ? `, typeof __VLS_withDefaultsArg>` : '',
127
+ ].join(''),
128
+ typeOptionExp: `{} as __VLS_PublicProps`,
129
+ });
130
+ }
123
131
  }
124
132
  if (scriptSetupRanges.defineProps?.arg) {
125
133
  const { arg } = scriptSetupRanges.defineProps;
@@ -146,6 +154,10 @@ function* generatePropsOption(options, ctx, scriptSetup, scriptSetupRanges, hasE
146
154
  const useTypeOption = options.vueCompilerOptions.target >= 3.5 && codes.every(code => code.typeOptionExp);
147
155
  const useOption = !useTypeOption || scriptSetupRanges.withDefaults;
148
156
  if (useTypeOption) {
157
+ if (options.vueCompilerOptions.target >= 3.6
158
+ && scriptSetupRanges.withDefaults?.arg) {
159
+ yield `__defaults: __VLS_withDefaultsArg,${utils_1.newLine}`;
160
+ }
149
161
  if (codes.length === 1) {
150
162
  yield `__typeProps: `;
151
163
  yield codes[0].typeOptionExp;
@@ -27,7 +27,7 @@ function* generateScript(options) {
27
27
  }
28
28
  }
29
29
  else {
30
- yield `/* placeholder */`;
30
+ yield `/// <reference path="./__VLS_fake.d.ts" />`;
31
31
  }
32
32
  if (options.sfc.script?.src) {
33
33
  yield* (0, src_1.generateSrc)(options.sfc.script.src);
@@ -78,15 +78,6 @@ function* generateScriptSetup(options, ctx, scriptSetup, scriptSetupRanges) {
78
78
  }
79
79
  function* generateSetupFunction(options, ctx, scriptSetup, scriptSetupRanges, syntax) {
80
80
  let setupCodeModifies = [];
81
- for (const { comments } of scriptSetupRanges.defineProp) {
82
- if (comments) {
83
- setupCodeModifies.push([
84
- [``],
85
- comments.start,
86
- comments.end,
87
- ]);
88
- }
89
- }
90
81
  if (scriptSetupRanges.defineProps) {
91
82
  const { name, statement, callExp, typeArg } = scriptSetupRanges.defineProps;
92
83
  setupCodeModifies.push(...generateDefineWithType(scriptSetup, statement, scriptSetupRanges.withDefaults?.callExp ?? callExp, typeArg, name, `__VLS_props`, `__VLS_Props`));
@@ -405,7 +396,7 @@ function* generateComponentProps(options, ctx, scriptSetup, scriptSetupRanges) {
405
396
  for (const defineProp of scriptSetupRanges.defineProp) {
406
397
  const [propName, localName] = getPropAndLocalName(scriptSetup, defineProp);
407
398
  if (defineProp.comments) {
408
- yield (0, utils_1.generateSfcBlockSection)(scriptSetup, defineProp.comments.start, defineProp.comments.end, codeFeatures_1.codeFeatures.all);
399
+ yield scriptSetup.content.slice(defineProp.comments.start, defineProp.comments.end);
409
400
  yield utils_1.newLine;
410
401
  }
411
402
  if (defineProp.isModel && !defineProp.name) {
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.generateSrc = generateSrc;
4
4
  const codeFeatures_1 = require("../codeFeatures");
5
5
  const utils_1 = require("../utils");
6
+ const wrapWith_1 = require("../utils/wrapWith");
6
7
  function* generateSrc(src) {
7
8
  if (src === true) {
8
9
  return;
@@ -21,10 +22,10 @@ function* generateSrc(src) {
21
22
  text = text + '.js';
22
23
  }
23
24
  yield `export * from `;
24
- yield* (0, utils_1.generateSfcBlockAttrValue)(src, text, {
25
+ yield* (0, wrapWith_1.wrapWith)(src.offset, src.offset + src.text.length, 'main', {
25
26
  ...codeFeatures_1.codeFeatures.all,
26
- ...text === src.text ? codeFeatures_1.codeFeatures.navigation : codeFeatures_1.codeFeatures.navigationWithoutRename,
27
- });
27
+ ...text !== src.text ? codeFeatures_1.codeFeatures.navigationWithoutRename : {},
28
+ }, `'`, [text.slice(0, src.text.length), 'main', src.offset, utils_1.combineLastMapping], text.slice(src.text.length), `'`);
28
29
  yield utils_1.endOfLine;
29
30
  yield `export { default } from '${text}'${utils_1.endOfLine}`;
30
31
  }
@@ -0,0 +1,4 @@
1
+ import type { Code } from '../../types';
2
+ import type { ScriptCodegenContext } from './context';
3
+ import type { ScriptCodegenOptions } from './index';
4
+ export declare function generateStyleModulesType(options: ScriptCodegenOptions, ctx: ScriptCodegenContext): Generator<Code>;
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.generateStyleModulesType = generateStyleModulesType;
4
+ const codeFeatures_1 = require("../codeFeatures");
5
+ const utils_1 = require("../utils");
6
+ const template_1 = require("./template");
7
+ function* generateStyleModulesType(options, ctx) {
8
+ const styles = options.sfc.styles.map((style, i) => [style, i]).filter(([style]) => style.module);
9
+ if (!styles.length && !options.scriptSetupRanges?.useCssModule.length) {
10
+ return;
11
+ }
12
+ yield `type __VLS_StyleModules = {${utils_1.newLine}`;
13
+ for (const [style, i] of styles) {
14
+ const { name, offset } = style.module;
15
+ if (offset) {
16
+ yield [
17
+ name,
18
+ 'main',
19
+ offset + 1,
20
+ codeFeatures_1.codeFeatures.all
21
+ ];
22
+ }
23
+ else {
24
+ yield name;
25
+ }
26
+ yield `: Record<string, string> & ${ctx.localTypes.PrettifyLocal}<{}`;
27
+ for (const className of style.classNames) {
28
+ yield* (0, template_1.generateCssClassProperty)(i, className.text, className.offset, 'string', false);
29
+ }
30
+ yield `>${utils_1.endOfLine}`;
31
+ }
32
+ yield `}${utils_1.endOfLine}`;
33
+ }
34
+ //# sourceMappingURL=styleModulesType.js.map
@@ -51,7 +51,7 @@ function* generateTemplateElements() {
51
51
  yield `let __VLS_elements!: __VLS_IntrinsicElements${utils_1.endOfLine}`;
52
52
  }
53
53
  function* generateTemplateComponents(options) {
54
- const types = [];
54
+ const types = [`typeof __VLS_ctx`];
55
55
  if (options.sfc.script && options.scriptRanges?.exportDefault?.componentsOption) {
56
56
  const { componentsOption } = options.scriptRanges.exportDefault;
57
57
  yield `const __VLS_componentsOption = `;
@@ -64,7 +64,6 @@ function* generateTemplateComponents(options) {
64
64
  yield utils_1.endOfLine;
65
65
  types.push(`typeof __VLS_componentsOption`);
66
66
  }
67
- types.push(`typeof __VLS_ctx`);
68
67
  yield `type __VLS_LocalComponents =`;
69
68
  for (const type of types) {
70
69
  yield ` & `;
@@ -74,7 +73,7 @@ function* generateTemplateComponents(options) {
74
73
  yield `let __VLS_components!: __VLS_LocalComponents & __VLS_GlobalComponents${utils_1.endOfLine}`;
75
74
  }
76
75
  function* generateTemplateDirectives(options) {
77
- const types = [];
76
+ const types = [`typeof __VLS_ctx`];
78
77
  if (options.sfc.script && options.scriptRanges?.exportDefault?.directivesOption) {
79
78
  const { directivesOption } = options.scriptRanges.exportDefault;
80
79
  yield `const __VLS_directivesOption = `;
@@ -85,9 +84,8 @@ function* generateTemplateDirectives(options) {
85
84
  codeFeatures_1.codeFeatures.navigation,
86
85
  ];
87
86
  yield utils_1.endOfLine;
88
- types.push(`typeof __VLS_directivesOption`);
87
+ types.push(`__VLS_ResolveDirectives<typeof __VLS_directivesOption>`);
89
88
  }
90
- types.push(`typeof __VLS_ctx`);
91
89
  yield `type __VLS_LocalDirectives =`;
92
90
  for (const type of types) {
93
91
  yield ` & `;
@@ -1,4 +1,4 @@
1
- import type * as CompilerDOM from '@vue/compiler-dom';
1
+ import * as CompilerDOM from '@vue/compiler-dom';
2
2
  import type { Code, VueCodeInformation } from '../../types';
3
3
  import { InlayHintInfo } from '../inlayHints';
4
4
  import type { TemplateCodegenOptions } from './index';
@@ -101,6 +101,17 @@ export type TemplateCodegenContext = ReturnType<typeof createTemplateCodegenCont
101
101
  * and additionally how we use that to determine whether to propagate diagnostics back upward.
102
102
  */
103
103
  export declare function createTemplateCodegenContext(options: Pick<TemplateCodegenOptions, 'scriptSetupBindingNames'>): {
104
+ readonly currentInfo: {
105
+ ignoreError?: boolean;
106
+ expectError?: {
107
+ token: number;
108
+ node: CompilerDOM.CommentNode;
109
+ };
110
+ generic?: {
111
+ content: string;
112
+ offset: number;
113
+ };
114
+ };
104
115
  codeFeatures: {
105
116
  all: VueCodeInformation;
106
117
  none: VueCodeInformation;
@@ -120,6 +131,7 @@ export declare function createTemplateCodegenContext(options: Pick<TemplateCodeg
120
131
  withoutHighlightAndCompletionAndNavigation: VueCodeInformation;
121
132
  };
122
133
  resolveCodeFeatures: (features: VueCodeInformation) => VueCodeInformation;
134
+ inVFor: boolean;
123
135
  slots: {
124
136
  name: string;
125
137
  offset?: number;
@@ -133,10 +145,6 @@ export declare function createTemplateCodegenContext(options: Pick<TemplateCodeg
133
145
  }[];
134
146
  dollarVars: Set<string>;
135
147
  accessExternalVariables: Map<string, Set<number>>;
136
- lastGenericComment: {
137
- content: string;
138
- offset: number;
139
- } | undefined;
140
148
  blockConditions: string[];
141
149
  scopedClasses: {
142
150
  source: string;
@@ -150,23 +158,24 @@ export declare function createTemplateCodegenContext(options: Pick<TemplateCodeg
150
158
  templateRefs: Map<string, {
151
159
  typeExp: string;
152
160
  offset: number;
153
- }>;
161
+ }[]>;
154
162
  currentComponent: {
155
163
  ctxVar: string;
164
+ childTypes: string[];
156
165
  used: boolean;
157
166
  } | undefined;
158
167
  singleRootElTypes: string[];
159
168
  singleRootNodes: Set<CompilerDOM.ElementNode | null>;
169
+ addTemplateRef(name: string, typeExp: string, offset: number): void;
160
170
  accessExternalVariable(name: string, offset?: number): void;
161
- hasLocalVariable: (name: string) => boolean;
162
- addLocalVariable: (name: string) => void;
163
- removeLocalVariable: (name: string) => void;
164
- getInternalVariable: () => string;
165
- getHoistVariable: (originalVar: string) => string;
166
- generateHoistVariables: () => Generator<string, void, unknown>;
167
- generateConditionGuards: () => Generator<string, void, unknown>;
168
- ignoreError: () => Generator<Code>;
169
- expectError: (prevNode: CompilerDOM.CommentNode) => Generator<Code>;
170
- resetDirectiveComments: (endStr: string) => Generator<Code>;
171
- generateAutoImportCompletion: () => Generator<Code>;
171
+ hasLocalVariable(name: string): boolean;
172
+ addLocalVariable(name: string): void;
173
+ removeLocalVariable(name: string): void;
174
+ getInternalVariable(): string;
175
+ getHoistVariable(originalVar: string): string;
176
+ generateHoistVariables(): Generator<string, void, unknown>;
177
+ generateConditionGuards(): Generator<string, void, unknown>;
178
+ generateAutoImportCompletion(): Generator<Code>;
179
+ enter(node: CompilerDOM.RootNode | CompilerDOM.TemplateChildNode | CompilerDOM.SimpleExpressionNode): boolean;
180
+ exit(): Generator<Code>;
172
181
  };
@@ -1,9 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.createTemplateCodegenContext = createTemplateCodegenContext;
4
+ const CompilerDOM = require("@vue/compiler-dom");
4
5
  const codeFeatures_1 = require("../codeFeatures");
5
6
  const utils_1 = require("../utils");
6
7
  const wrapWith_1 = require("../utils/wrapWith");
8
+ const commentDirectiveRegex = /^<!--\s*@vue-(?<name>[-\w]+)\b(?<content>[\s\S]*)-->$/;
7
9
  /**
8
10
  * Creates and returns a Context object used for generating type-checkable TS code
9
11
  * from the template section of a .vue file.
@@ -102,13 +104,11 @@ const wrapWith_1 = require("../utils/wrapWith");
102
104
  * and additionally how we use that to determine whether to propagate diagnostics back upward.
103
105
  */
104
106
  function createTemplateCodegenContext(options) {
105
- let ignoredError = false;
106
- let expectErrorToken;
107
- let lastGenericComment;
108
107
  let variableId = 0;
109
108
  function resolveCodeFeatures(features) {
110
- if (features.verification) {
111
- if (ignoredError) {
109
+ if (features.verification && stack.length) {
110
+ const data = stack[stack.length - 1];
111
+ if (data.ignoreError) {
112
112
  // We are currently in a region of code covered by a @vue-ignore directive, so don't
113
113
  // even bother performing any type-checking: set verification to false.
114
114
  return {
@@ -116,17 +116,16 @@ function createTemplateCodegenContext(options) {
116
116
  verification: false,
117
117
  };
118
118
  }
119
- if (expectErrorToken) {
119
+ if (data.expectError !== undefined) {
120
120
  // We are currently in a region of code covered by a @vue-expect-error directive. We need to
121
121
  // keep track of the number of errors encountered within this region so that we can know whether
122
122
  // we will need to propagate an "unused ts-expect-error" diagnostic back to the original
123
123
  // .vue file or not.
124
- const token = expectErrorToken;
125
124
  return {
126
125
  ...features,
127
126
  verification: {
128
127
  shouldReport: () => {
129
- token.errors++;
128
+ data.expectError.token++;
130
129
  return false;
131
130
  },
132
131
  },
@@ -148,7 +147,12 @@ function createTemplateCodegenContext(options) {
148
147
  const bindingAttrLocs = [];
149
148
  const inheritedAttrVars = new Set();
150
149
  const templateRefs = new Map();
150
+ const stack = [];
151
+ const commentBuffer = [];
151
152
  return {
153
+ get currentInfo() {
154
+ return stack[stack.length - 1];
155
+ },
152
156
  codeFeatures: new Proxy(codeFeatures_1.codeFeatures, {
153
157
  get(target, key) {
154
158
  const data = target[key];
@@ -156,11 +160,11 @@ function createTemplateCodegenContext(options) {
156
160
  },
157
161
  }),
158
162
  resolveCodeFeatures,
163
+ inVFor: false,
159
164
  slots,
160
165
  dynamicSlots,
161
166
  dollarVars,
162
167
  accessExternalVariables,
163
- lastGenericComment,
164
168
  blockConditions,
165
169
  scopedClasses,
166
170
  emptyClassOffsets,
@@ -171,6 +175,13 @@ function createTemplateCodegenContext(options) {
171
175
  currentComponent: undefined,
172
176
  singleRootElTypes: [],
173
177
  singleRootNodes: new Set(),
178
+ addTemplateRef(name, typeExp, offset) {
179
+ let refs = templateRefs.get(name);
180
+ if (!refs) {
181
+ templateRefs.set(name, refs = []);
182
+ }
183
+ refs.push({ typeExp, offset });
184
+ },
174
185
  accessExternalVariable(name, offset) {
175
186
  let arr = accessExternalVariables.get(name);
176
187
  if (!arr) {
@@ -180,26 +191,26 @@ function createTemplateCodegenContext(options) {
180
191
  arr.add(offset);
181
192
  }
182
193
  },
183
- hasLocalVariable: (name) => {
194
+ hasLocalVariable(name) {
184
195
  return !!localVars.get(name);
185
196
  },
186
- addLocalVariable: (name) => {
197
+ addLocalVariable(name) {
187
198
  localVars.set(name, (localVars.get(name) ?? 0) + 1);
188
199
  },
189
- removeLocalVariable: (name) => {
200
+ removeLocalVariable(name) {
190
201
  localVars.set(name, localVars.get(name) - 1);
191
202
  },
192
- getInternalVariable: () => {
203
+ getInternalVariable() {
193
204
  return `__VLS_${variableId++}`;
194
205
  },
195
- getHoistVariable: (originalVar) => {
206
+ getHoistVariable(originalVar) {
196
207
  let name = hoistVars.get(originalVar);
197
208
  if (name === undefined) {
198
209
  hoistVars.set(originalVar, name = `__VLS_${variableId++}`);
199
210
  }
200
211
  return name;
201
212
  },
202
- generateHoistVariables: function* () {
213
+ *generateHoistVariables() {
203
214
  // trick to avoid TS 4081 (#5186)
204
215
  if (hoistVars.size) {
205
216
  yield `// @ts-ignore${utils_1.newLine}`;
@@ -210,47 +221,12 @@ function createTemplateCodegenContext(options) {
210
221
  yield utils_1.endOfLine;
211
222
  }
212
223
  },
213
- generateConditionGuards: function* () {
224
+ *generateConditionGuards() {
214
225
  for (const condition of blockConditions) {
215
226
  yield `if (!${condition}) return${utils_1.endOfLine}`;
216
227
  }
217
228
  },
218
- ignoreError: function* () {
219
- if (!ignoredError) {
220
- ignoredError = true;
221
- yield `// @vue-ignore start${utils_1.newLine}`;
222
- }
223
- },
224
- expectError: function* (prevNode) {
225
- if (!expectErrorToken) {
226
- expectErrorToken = {
227
- errors: 0,
228
- node: prevNode,
229
- };
230
- yield `// @vue-expect-error start${utils_1.newLine}`;
231
- }
232
- },
233
- resetDirectiveComments: function* (endStr) {
234
- if (expectErrorToken) {
235
- const token = expectErrorToken;
236
- yield* (0, wrapWith_1.wrapWith)(expectErrorToken.node.loc.start.offset, expectErrorToken.node.loc.end.offset, {
237
- verification: {
238
- // If no errors/warnings/diagnostics were reported within the region of code covered
239
- // by the @vue-expect-error directive, then we should allow any `unused @ts-expect-error`
240
- // diagnostics to be reported upward.
241
- shouldReport: () => token.errors === 0,
242
- },
243
- }, `// @ts-expect-error __VLS_TS_EXPECT_ERROR`);
244
- yield `${utils_1.newLine}${utils_1.endOfLine}`;
245
- expectErrorToken = undefined;
246
- yield `// @vue-expect-error ${endStr}${utils_1.newLine}`;
247
- }
248
- if (ignoredError) {
249
- ignoredError = false;
250
- yield `// @vue-ignore ${endStr}${utils_1.newLine}`;
251
- }
252
- },
253
- generateAutoImportCompletion: function* () {
229
+ *generateAutoImportCompletion() {
254
230
  const all = [...accessExternalVariables.entries()];
255
231
  if (!all.some(([_, offsets]) => offsets.size)) {
256
232
  return;
@@ -284,7 +260,65 @@ function createTemplateCodegenContext(options) {
284
260
  offsets.clear();
285
261
  }
286
262
  yield `]${utils_1.endOfLine}`;
287
- }
263
+ },
264
+ enter(node) {
265
+ if (node.type === CompilerDOM.NodeTypes.COMMENT) {
266
+ commentBuffer.push(node);
267
+ return false;
268
+ }
269
+ const data = {};
270
+ const comments = [...commentBuffer];
271
+ commentBuffer.length = 0;
272
+ for (const comment of comments) {
273
+ const match = comment.loc.source.match(commentDirectiveRegex);
274
+ if (match) {
275
+ const { name, content } = match.groups;
276
+ switch (name) {
277
+ case 'skip': {
278
+ return false;
279
+ }
280
+ case 'ignore': {
281
+ data.ignoreError = true;
282
+ break;
283
+ }
284
+ case 'expect-error': {
285
+ data.expectError = {
286
+ token: 0,
287
+ node: comment,
288
+ };
289
+ break;
290
+ }
291
+ case 'generic': {
292
+ const text = content.trim();
293
+ if (text.startsWith('{') && text.endsWith('}')) {
294
+ data.generic = {
295
+ content: text.slice(1, -1),
296
+ offset: comment.loc.start.offset + comment.loc.source.indexOf('{') + 1,
297
+ };
298
+ }
299
+ break;
300
+ }
301
+ }
302
+ }
303
+ }
304
+ stack.push(data);
305
+ return true;
306
+ },
307
+ *exit() {
308
+ const data = stack.pop();
309
+ commentBuffer.length = 0;
310
+ if (data.expectError !== undefined) {
311
+ yield* (0, wrapWith_1.wrapWith)(data.expectError.node.loc.start.offset, data.expectError.node.loc.end.offset, {
312
+ verification: {
313
+ // If no errors/warnings/diagnostics were reported within the region of code covered
314
+ // by the @vue-expect-error directive, then we should allow any `unused @ts-expect-error`
315
+ // diagnostics to be reported upward.
316
+ shouldReport: () => data.expectError.token === 0,
317
+ },
318
+ }, `// @ts-expect-error`);
319
+ yield `${utils_1.newLine}${utils_1.endOfLine}`;
320
+ }
321
+ },
288
322
  };
289
323
  }
290
324
  //# sourceMappingURL=context.js.map
@@ -2,5 +2,5 @@ import * as CompilerDOM from '@vue/compiler-dom';
2
2
  import type { Code } from '../../types';
3
3
  import type { TemplateCodegenContext } from './context';
4
4
  import type { TemplateCodegenOptions } from './index';
5
- export declare function generateComponent(options: TemplateCodegenOptions, ctx: TemplateCodegenContext, node: CompilerDOM.ElementNode, isVForChild: boolean): Generator<Code>;
6
- export declare function generateElement(options: TemplateCodegenOptions, ctx: TemplateCodegenContext, node: CompilerDOM.ElementNode, isVForChild: boolean): Generator<Code>;
5
+ export declare function generateComponent(options: TemplateCodegenOptions, ctx: TemplateCodegenContext, node: CompilerDOM.ElementNode): Generator<Code>;
6
+ export declare function generateElement(options: TemplateCodegenOptions, ctx: TemplateCodegenContext, node: CompilerDOM.ElementNode): Generator<Code>;