UNPKG

16.6 kBTypeScriptView Raw
1import * as _babel_types from '@babel/types';
2import { Statement, Expression, TSType, Node, Program, CallExpression, ObjectPattern, TSModuleDeclaration, TSPropertySignature, TSMethodSignature, TSCallSignatureDeclaration, TSFunctionType } from '@babel/types';
3import { RootNode, CompilerOptions, CodegenResult, ParserOptions, CompilerError, RawSourceMap, SourceLocation, BindingMetadata as BindingMetadata$1 } from '@vue/compiler-core';
4export { BindingMetadata, CompilerError, CompilerOptions, extractIdentifiers, generateCodeFrame, isInDestructureAssignment, isStaticProperty, walkIdentifiers } from '@vue/compiler-core';
5import { ParserPlugin } from '@babel/parser';
6export { parse as babelParse } from '@babel/parser';
7import { Result, LazyResult } from 'postcss';
8import MagicString from 'magic-string';
9export { default as MagicString } from 'magic-string';
10import TS from 'typescript';
11
12export interface AssetURLTagConfig {
13 [name: string]: string[];
14}
15export interface AssetURLOptions {
16 /**
17 * If base is provided, instead of transforming relative asset urls into
18 * imports, they will be directly rewritten to absolute urls.
19 */
20 base?: string | null;
21 /**
22 * If true, also processes absolute urls.
23 */
24 includeAbsolute?: boolean;
25 tags?: AssetURLTagConfig;
26}
27
28export interface TemplateCompiler {
29 compile(source: string | RootNode, options: CompilerOptions): CodegenResult;
30 parse(template: string, options: ParserOptions): RootNode;
31}
32export interface SFCTemplateCompileResults {
33 code: string;
34 ast?: RootNode;
35 preamble?: string;
36 source: string;
37 tips: string[];
38 errors: (string | CompilerError)[];
39 map?: RawSourceMap;
40}
41export interface SFCTemplateCompileOptions {
42 source: string;
43 ast?: RootNode;
44 filename: string;
45 id: string;
46 scoped?: boolean;
47 slotted?: boolean;
48 isProd?: boolean;
49 ssr?: boolean;
50 ssrCssVars?: string[];
51 inMap?: RawSourceMap;
52 compiler?: TemplateCompiler;
53 compilerOptions?: CompilerOptions;
54 preprocessLang?: string;
55 preprocessOptions?: any;
56 /**
57 * In some cases, compiler-sfc may not be inside the project root (e.g. when
58 * linked or globally installed). In such cases a custom `require` can be
59 * passed to correctly resolve the preprocessors.
60 */
61 preprocessCustomRequire?: (id: string) => any;
62 /**
63 * Configure what tags/attributes to transform into asset url imports,
64 * or disable the transform altogether with `false`.
65 */
66 transformAssetUrls?: AssetURLOptions | AssetURLTagConfig | boolean;
67}
68export declare function compileTemplate(options: SFCTemplateCompileOptions): SFCTemplateCompileResults;
69
70export interface SFCScriptCompileOptions {
71 /**
72 * Scope ID for prefixing injected CSS variables.
73 * This must be consistent with the `id` passed to `compileStyle`.
74 */
75 id: string;
76 /**
77 * Production mode. Used to determine whether to generate hashed CSS variables
78 */
79 isProd?: boolean;
80 /**
81 * Enable/disable source map. Defaults to true.
82 */
83 sourceMap?: boolean;
84 /**
85 * https://babeljs.io/docs/en/babel-parser#plugins
86 */
87 babelParserPlugins?: ParserPlugin[];
88 /**
89 * A list of files to parse for global types to be made available for type
90 * resolving in SFC macros. The list must be fully resolved file system paths.
91 */
92 globalTypeFiles?: string[];
93 /**
94 * Compile the template and inline the resulting render function
95 * directly inside setup().
96 * - Only affects `<script setup>`
97 * - This should only be used in production because it prevents the template
98 * from being hot-reloaded separately from component state.
99 */
100 inlineTemplate?: boolean;
101 /**
102 * Generate the final component as a variable instead of default export.
103 * This is useful in e.g. @vitejs/plugin-vue where the script needs to be
104 * placed inside the main module.
105 */
106 genDefaultAs?: string;
107 /**
108 * Options for template compilation when inlining. Note these are options that
109 * would normally be passed to `compiler-sfc`'s own `compileTemplate()`, not
110 * options passed to `compiler-dom`.
111 */
112 templateOptions?: Partial<SFCTemplateCompileOptions>;
113 /**
114 * Hoist <script setup> static constants.
115 * - Only enables when one `<script setup>` exists.
116 * @default true
117 */
118 hoistStatic?: boolean;
119 /**
120 * Set to `false` to disable reactive destructure for `defineProps` (pre-3.5
121 * behavior), or set to `'error'` to throw hard error on props destructures.
122 * @default true
123 */
124 propsDestructure?: boolean | 'error';
125 /**
126 * File system access methods to be used when resolving types
127 * imported in SFC macros. Defaults to ts.sys in Node.js, can be overwritten
128 * to use a virtual file system for use in browsers (e.g. in REPLs)
129 */
130 fs?: {
131 fileExists(file: string): boolean;
132 readFile(file: string): string | undefined;
133 realpath?(file: string): string;
134 };
135 /**
136 * Transform Vue SFCs into custom elements.
137 */
138 customElement?: boolean | ((filename: string) => boolean);
139}
140interface ImportBinding {
141 isType: boolean;
142 imported: string;
143 local: string;
144 source: string;
145 isFromSetup: boolean;
146 isUsedInTemplate: boolean;
147}
148/**
149 * Compile `<script setup>`
150 * It requires the whole SFC descriptor because we need to handle and merge
151 * normal `<script>` + `<script setup>` if both are present.
152 */
153export declare function compileScript(sfc: SFCDescriptor, options: SFCScriptCompileOptions): SFCScriptBlock;
154
155export interface SFCParseOptions {
156 filename?: string;
157 sourceMap?: boolean;
158 sourceRoot?: string;
159 pad?: boolean | 'line' | 'space';
160 ignoreEmpty?: boolean;
161 compiler?: TemplateCompiler;
162 templateParseOptions?: ParserOptions;
163}
164export interface SFCBlock {
165 type: string;
166 content: string;
167 attrs: Record<string, string | true>;
168 loc: SourceLocation;
169 map?: RawSourceMap;
170 lang?: string;
171 src?: string;
172}
173export interface SFCTemplateBlock extends SFCBlock {
174 type: 'template';
175 ast?: RootNode;
176}
177export interface SFCScriptBlock extends SFCBlock {
178 type: 'script';
179 setup?: string | boolean;
180 bindings?: BindingMetadata$1;
181 imports?: Record<string, ImportBinding>;
182 scriptAst?: _babel_types.Statement[];
183 scriptSetupAst?: _babel_types.Statement[];
184 warnings?: string[];
185 /**
186 * Fully resolved dependency file paths (unix slashes) with imported types
187 * used in macros, used for HMR cache busting in @vitejs/plugin-vue and
188 * vue-loader.
189 */
190 deps?: string[];
191}
192export interface SFCStyleBlock extends SFCBlock {
193 type: 'style';
194 scoped?: boolean;
195 module?: string | boolean;
196}
197export interface SFCDescriptor {
198 filename: string;
199 source: string;
200 template: SFCTemplateBlock | null;
201 script: SFCScriptBlock | null;
202 scriptSetup: SFCScriptBlock | null;
203 styles: SFCStyleBlock[];
204 customBlocks: SFCBlock[];
205 cssVars: string[];
206 /**
207 * whether the SFC uses :slotted() modifier.
208 * this is used as a compiler optimization hint.
209 */
210 slotted: boolean;
211 /**
212 * compare with an existing descriptor to determine whether HMR should perform
213 * a reload vs. re-render.
214 *
215 * Note: this comparison assumes the prev/next script are already identical,
216 * and only checks the special case where <script setup lang="ts"> unused import
217 * pruning result changes due to template changes.
218 */
219 shouldForceReload: (prevImports: Record<string, ImportBinding>) => boolean;
220}
221export interface SFCParseResult {
222 descriptor: SFCDescriptor;
223 errors: (CompilerError | SyntaxError)[];
224}
225export declare function parse(source: string, options?: SFCParseOptions): SFCParseResult;
226
227type PreprocessLang = 'less' | 'sass' | 'scss' | 'styl' | 'stylus';
228
229export interface SFCStyleCompileOptions {
230 source: string;
231 filename: string;
232 id: string;
233 scoped?: boolean;
234 trim?: boolean;
235 isProd?: boolean;
236 inMap?: RawSourceMap;
237 preprocessLang?: PreprocessLang;
238 preprocessOptions?: any;
239 preprocessCustomRequire?: (id: string) => any;
240 postcssOptions?: any;
241 postcssPlugins?: any[];
242 /**
243 * @deprecated use `inMap` instead.
244 */
245 map?: RawSourceMap;
246}
247/**
248 * Aligns with postcss-modules
249 * https://github.com/css-modules/postcss-modules
250 */
251interface CSSModulesOptions {
252 scopeBehaviour?: 'global' | 'local';
253 generateScopedName?: string | ((name: string, filename: string, css: string) => string);
254 hashPrefix?: string;
255 localsConvention?: 'camelCase' | 'camelCaseOnly' | 'dashes' | 'dashesOnly';
256 exportGlobals?: boolean;
257 globalModulePaths?: RegExp[];
258}
259export interface SFCAsyncStyleCompileOptions extends SFCStyleCompileOptions {
260 isAsync?: boolean;
261 modules?: boolean;
262 modulesOptions?: CSSModulesOptions;
263}
264export interface SFCStyleCompileResults {
265 code: string;
266 map: RawSourceMap | undefined;
267 rawResult: Result | LazyResult | undefined;
268 errors: Error[];
269 modules?: Record<string, string>;
270 dependencies: Set<string>;
271}
272export declare function compileStyle(options: SFCStyleCompileOptions): SFCStyleCompileResults;
273export declare function compileStyleAsync(options: SFCAsyncStyleCompileOptions): Promise<SFCStyleCompileResults>;
274
275export declare function rewriteDefault(input: string, as: string, parserPlugins?: ParserPlugin[]): string;
276/**
277 * Utility for rewriting `export default` in a script block into a variable
278 * declaration so that we can inject things into it
279 */
280export declare function rewriteDefaultAST(ast: Statement[], s: MagicString, as: string): void;
281
282type PropsDestructureBindings = Record<string, // public prop key
283{
284 local: string;
285 default?: Expression;
286}>;
287export declare function extractRuntimeProps(ctx: TypeResolveContext): string | undefined;
288
289interface ModelDecl {
290 type: TSType | undefined;
291 options: string | undefined;
292 identifier: string | undefined;
293 runtimeOptionNodes: Node[];
294}
295
296declare enum BindingTypes {
297 /**
298 * returned from data()
299 */
300 DATA = "data",
301 /**
302 * declared as a prop
303 */
304 PROPS = "props",
305 /**
306 * a local alias of a `<script setup>` destructured prop.
307 * the original is stored in __propsAliases of the bindingMetadata object.
308 */
309 PROPS_ALIASED = "props-aliased",
310 /**
311 * a let binding (may or may not be a ref)
312 */
313 SETUP_LET = "setup-let",
314 /**
315 * a const binding that can never be a ref.
316 * these bindings don't need `unref()` calls when processed in inlined
317 * template expressions.
318 */
319 SETUP_CONST = "setup-const",
320 /**
321 * a const binding that does not need `unref()`, but may be mutated.
322 */
323 SETUP_REACTIVE_CONST = "setup-reactive-const",
324 /**
325 * a const binding that may be a ref.
326 */
327 SETUP_MAYBE_REF = "setup-maybe-ref",
328 /**
329 * bindings that are guaranteed to be refs
330 */
331 SETUP_REF = "setup-ref",
332 /**
333 * declared by other options, e.g. computed, inject
334 */
335 OPTIONS = "options",
336 /**
337 * a literal constant, e.g. 'foo', 1, true
338 */
339 LITERAL_CONST = "literal-const"
340}
341type BindingMetadata = {
342 [key: string]: BindingTypes | undefined;
343} & {
344 __isScriptSetup?: boolean;
345 __propsAliases?: Record<string, string>;
346};
347
348export declare class ScriptCompileContext {
349 descriptor: SFCDescriptor;
350 options: Partial<SFCScriptCompileOptions>;
351 isJS: boolean;
352 isTS: boolean;
353 isCE: boolean;
354 scriptAst: Program | null;
355 scriptSetupAst: Program | null;
356 source: string;
357 filename: string;
358 s: MagicString;
359 startOffset: number | undefined;
360 endOffset: number | undefined;
361 scope?: TypeScope;
362 globalScopes?: TypeScope[];
363 userImports: Record<string, ImportBinding>;
364 hasDefinePropsCall: boolean;
365 hasDefineEmitCall: boolean;
366 hasDefineExposeCall: boolean;
367 hasDefaultExportName: boolean;
368 hasDefaultExportRender: boolean;
369 hasDefineOptionsCall: boolean;
370 hasDefineSlotsCall: boolean;
371 hasDefineModelCall: boolean;
372 propsCall: CallExpression | undefined;
373 propsDecl: Node | undefined;
374 propsRuntimeDecl: Node | undefined;
375 propsTypeDecl: Node | undefined;
376 propsDestructureDecl: ObjectPattern | undefined;
377 propsDestructuredBindings: PropsDestructureBindings;
378 propsDestructureRestId: string | undefined;
379 propsRuntimeDefaults: Node | undefined;
380 emitsRuntimeDecl: Node | undefined;
381 emitsTypeDecl: Node | undefined;
382 emitDecl: Node | undefined;
383 modelDecls: Record<string, ModelDecl>;
384 optionsRuntimeDecl: Node | undefined;
385 bindingMetadata: BindingMetadata;
386 helperImports: Set<string>;
387 helper(key: string): string;
388 /**
389 * to be exposed on compiled script block for HMR cache busting
390 */
391 deps?: Set<string>;
392 /**
393 * cache for resolved fs
394 */
395 fs?: NonNullable<SFCScriptCompileOptions['fs']>;
396 constructor(descriptor: SFCDescriptor, options: Partial<SFCScriptCompileOptions>);
397 getString(node: Node, scriptSetup?: boolean): string;
398 warn(msg: string, node: Node, scope?: TypeScope): void;
399 error(msg: string, node: Node, scope?: TypeScope): never;
400}
401
402export type SimpleTypeResolveOptions = Partial<Pick<SFCScriptCompileOptions, 'globalTypeFiles' | 'fs' | 'babelParserPlugins' | 'isProd'>>;
403/**
404 * TypeResolveContext is compatible with ScriptCompileContext
405 * but also allows a simpler version of it with minimal required properties
406 * when resolveType needs to be used in a non-SFC context, e.g. in a babel
407 * plugin. The simplest context can be just:
408 * ```ts
409 * const ctx: SimpleTypeResolveContext = {
410 * filename: '...',
411 * source: '...',
412 * options: {},
413 * error() {},
414 * ast: []
415 * }
416 * ```
417 */
418export type SimpleTypeResolveContext = Pick<ScriptCompileContext, 'source' | 'filename' | 'error' | 'helper' | 'getString' | 'propsTypeDecl' | 'propsRuntimeDefaults' | 'propsDestructuredBindings' | 'emitsTypeDecl' | 'isCE'> & Partial<Pick<ScriptCompileContext, 'scope' | 'globalScopes' | 'deps' | 'fs'>> & {
419 ast: Statement[];
420 options: SimpleTypeResolveOptions;
421};
422export type TypeResolveContext = ScriptCompileContext | SimpleTypeResolveContext;
423type Import = Pick<ImportBinding, 'source' | 'imported'>;
424interface WithScope {
425 _ownerScope: TypeScope;
426}
427type ScopeTypeNode = Node & WithScope & {
428 _ns?: TSModuleDeclaration & WithScope;
429};
430declare class TypeScope {
431 filename: string;
432 source: string;
433 offset: number;
434 imports: Record<string, Import>;
435 types: Record<string, ScopeTypeNode>;
436 declares: Record<string, ScopeTypeNode>;
437 constructor(filename: string, source: string, offset?: number, imports?: Record<string, Import>, types?: Record<string, ScopeTypeNode>, declares?: Record<string, ScopeTypeNode>);
438 isGenericScope: boolean;
439 resolvedImportSources: Record<string, string>;
440 exportedTypes: Record<string, ScopeTypeNode>;
441 exportedDeclares: Record<string, ScopeTypeNode>;
442}
443interface MaybeWithScope {
444 _ownerScope?: TypeScope;
445}
446interface ResolvedElements {
447 props: Record<string, (TSPropertySignature | TSMethodSignature) & {
448 _ownerScope: TypeScope;
449 }>;
450 calls?: (TSCallSignatureDeclaration | TSFunctionType)[];
451}
452/**
453 * Resolve arbitrary type node to a list of type elements that can be then
454 * mapped to runtime props or emits.
455 */
456export declare function resolveTypeElements(ctx: TypeResolveContext, node: Node & MaybeWithScope & {
457 _resolvedElements?: ResolvedElements;
458}, scope?: TypeScope, typeParameters?: Record<string, Node>): ResolvedElements;
459/**
460 * @private
461 */
462export declare function registerTS(_loadTS: () => typeof TS): void;
463/**
464 * @private
465 */
466export declare function invalidateTypeCache(filename: string): void;
467export declare function inferRuntimeType(ctx: TypeResolveContext, node: Node & MaybeWithScope, scope?: TypeScope, isKeyOf?: boolean): string[];
468
469export declare function extractRuntimeEmits(ctx: TypeResolveContext): Set<string>;
470
471export declare const version: string;
472
473export declare const parseCache: Map<string, SFCParseResult>;
474export declare const errorMessages: Record<number, string>;
475
476export declare const walk: any;
477
478/**
479 * @deprecated this is preserved to avoid breaking vite-plugin-vue < 5.0
480 * with reactivityTransform: true. The desired behavior should be silently
481 * ignoring the option instead of breaking.
482 */
483export declare const shouldTransformRef: () => boolean;
484